Mercurial > cgi-bin > hgweb.cgi > tincan
annotate tincan.py @ 10:84998cd4e123 draft
Add more provisional documentation.
author | David Barts <n5jrn@me.com> |
---|---|
date | Mon, 13 May 2019 21:24:48 -0700 |
parents | 75e375b1976a |
children | 8037bad7d5a8 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/env python3 |
2 # -*- coding: utf-8 -*- | |
3 # As with Bottle, it's all in one big, ugly file. For now. | |
4 | |
5 # I m p o r t s | |
6 | |
7 import os, sys | |
8 import ast | |
9 import binascii | |
10 from base64 import b16encode, b16decode | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
11 import functools |
2 | 12 import importlib |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
13 from inspect import isclass |
0 | 14 import io |
2 | 15 import py_compile |
16 from stat import S_ISDIR, S_ISREG | |
5 | 17 from string import whitespace |
0 | 18 |
19 import bottle | |
20 | |
2 | 21 # E x c e p t i o n s |
0 | 22 |
23 class TinCanException(Exception): | |
24 """ | |
25 The parent class of all exceptions we raise. | |
26 """ | |
27 pass | |
28 | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
29 class TemplateHeaderError(TinCanException): |
0 | 30 """ |
31 Raised upon encountering a syntax error in the template headers. | |
32 """ | |
33 def __init__(self, message, line): | |
34 super().__init__(message, line) | |
35 self.message = message | |
36 self.line = line | |
37 | |
38 def __str__(self): | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
39 return "line {0}: {1}".format(self.line, self.message) |
0 | 40 |
41 class ForwardException(TinCanException): | |
42 """ | |
43 Raised to effect the flow control needed to do a forward (server-side | |
44 redirect). It is ugly to do this, but other Python frameworks do and | |
45 there seems to be no good alternative. | |
46 """ | |
47 def __init__(self, target): | |
48 self.target = target | |
49 | |
50 class TinCanError(TinCanException): | |
51 """ | |
52 General-purpose exception thrown by TinCan when things go wrong, often | |
53 when attempting to launch webapps. | |
54 """ | |
55 pass | |
56 | |
2 | 57 # T e m p l a t e s |
58 # | |
0 | 59 # Template (.pspx) files. These are standard templates for a supported |
60 # template engine, but with an optional set of header lines that begin | |
61 # with '#'. | |
62 | |
63 class TemplateFile(object): | |
64 """ | |
65 Parse a template file into a header part and the body part. The header | |
66 is always a leading set of lines, each starting with '#', that is of the | |
67 same format regardless of the template body. The template body varies | |
68 depending on the selected templating engine. The body part has | |
69 each header line replaced by a blank line. This preserves the overall | |
70 line numbering when processing the body. The added newlines are normally | |
71 stripped out before the rendered page is sent back to the client. | |
72 """ | |
5 | 73 _END = "#end" |
74 _LEND = len(_END) | |
75 _WS = set(whitespace) | |
76 | |
0 | 77 def __init__(self, raw, encoding='utf-8'): |
78 if isinstance(raw, io.TextIOBase): | |
79 self._do_init(raw) | |
80 elif isinstance(raw, str): | |
81 with open(raw, "r", encoding=encoding) as fp: | |
82 self._do_init(fp) | |
83 else: | |
84 raise TypeError("Expecting a string or Text I/O object.") | |
85 | |
86 def _do_init(self, fp): | |
87 self._hbuf = [] | |
88 self._bbuf = [] | |
89 self._state = self._header | |
90 while True: | |
91 line = fp.readline() | |
92 if line == '': | |
93 break | |
94 self._state(line) | |
95 self.header = ''.join(self._hbuf) | |
96 self.body = ''.join(self._bbuf) | |
97 | |
98 def _header(self, line): | |
99 if not line.startswith('#'): | |
100 self._state = self._body | |
101 self._state(line) | |
102 return | |
5 | 103 if line.startswith(self._END) and (len(line) == self._LEND or line[self._LEND] in self._WS): |
104 self._state = self._body | |
0 | 105 self._hbuf.append(line) |
106 self._bbuf.append("\n") | |
107 | |
108 def _body(self, line): | |
109 self._bbuf.append(line) | |
110 | |
111 class TemplateHeader(object): | |
112 """ | |
113 Parses and represents a set of header lines. | |
114 """ | |
2 | 115 _NAMES = [ "errors", "forward", "methods", "python", "template" ] |
0 | 116 _FNAMES = [ "hidden" ] |
117 | |
118 def __init__(self, string): | |
119 # Initialize our state | |
120 for i in self._NAMES: | |
121 setattr(self, i, None) | |
122 for i in self._FNAMES: | |
123 setattr(self, i, False) | |
124 # Parse the string | |
125 count = 0 | |
126 nameset = set(self._NAMES + self._FNAMES) | |
127 seen = set() | |
128 lines = string.split("\n") | |
129 if lines and lines[-1] == "": | |
130 del lines[-1] | |
131 for line in lines: | |
132 # Get line | |
133 count += 1 | |
134 if not line.startswith("#"): | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
135 raise TemplateHeaderError("Does not start with '#'.", count) |
0 | 136 try: |
137 rna, rpa = line.split(maxsplit=1) | |
138 except ValueError: | |
5 | 139 rna = line.rstrip() |
140 rpa = None | |
0 | 141 # Get name, ignoring remarks. |
142 name = rna[1:] | |
143 if name == "rem": | |
144 continue | |
5 | 145 if name == "end": |
146 break | |
0 | 147 if name not in nameset: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
148 raise TemplateHeaderError("Invalid directive: {0!r}".format(rna), count) |
0 | 149 if name in seen: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
150 raise TemplateHeaderError("Duplicate {0!r} directive.".format(rna), count) |
0 | 151 seen.add(name) |
152 # Flags | |
5 | 153 if name in self._FNAMES: |
0 | 154 setattr(self, name, True) |
155 continue | |
156 # Get parameter | |
5 | 157 if rpa is None: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
158 raise TemplateHeaderError("Missing parameter.", count) |
0 | 159 param = rpa.strip() |
160 for i in [ "'", '"']: | |
161 if param.startswith(i) and param.endswith(i): | |
162 param = ast.literal_eval(param) | |
163 break | |
164 # Update this object | |
165 setattr(self, name, param) | |
166 | |
2 | 167 # C h a m e l e o n |
168 # | |
0 | 169 # Support for Chameleon templates (the kind TinCan uses by default). |
170 | |
171 class ChameleonTemplate(bottle.BaseTemplate): | |
172 def prepare(self, **options): | |
173 from chameleon import PageTemplate, PageTemplateFile | |
174 if self.source: | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
175 self.tpl = PageTemplate(self.source, encoding=self.encoding, |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
176 **options) |
0 | 177 else: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
178 self.tpl = PageTemplateFile(self.filename, encoding=self.encoding, |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
179 search_path=self.lookup, **options) |
0 | 180 |
181 def render(self, *args, **kwargs): | |
182 for dictarg in args: | |
183 kwargs.update(dictarg) | |
184 _defaults = self.defaults.copy() | |
185 _defaults.update(kwargs) | |
186 return self.tpl.render(**_defaults) | |
187 | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
188 chameleon_template = functools.partial(bottle.template, template_adapter=ChameleonTemplate) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
189 chameleon_view = functools.partial(bottle.view, template_adapter=ChameleonTemplate) |
0 | 190 |
2 | 191 # U t i l i t i e s |
0 | 192 |
193 def _normpath(base, unsplit): | |
194 """ | |
195 Split, normalize and ensure a possibly relative path is absolute. First | |
196 argument is a list of directory names, defining a base. Second | |
197 argument is a string, which may either be relative to that base, or | |
198 absolute. Only '/' is supported as a separator. | |
199 """ | |
200 scratch = unsplit.strip('/').split('/') | |
201 if not unsplit.startswith('/'): | |
202 scratch = base + scratch | |
203 ret = [] | |
204 for i in scratch: | |
205 if i == '.': | |
206 continue | |
207 if i == '..': | |
208 ret.pop() # may raise IndexError | |
209 continue | |
210 ret.append(i) | |
211 return ret | |
212 | |
213 def _mangle(string): | |
214 """ | |
215 Turn a possibly troublesome identifier into a mangled one. | |
216 """ | |
217 first = True | |
218 ret = [] | |
219 for ch in string: | |
220 if ch == '_' or not (ch if first else "x" + ch).isidentifier(): | |
221 ret.append('_') | |
222 ret.append(b16encode(ch.encode("utf-8")).decode("us-ascii")) | |
223 else: | |
224 ret.append(ch) | |
225 first = False | |
226 return ''.join(ret) | |
227 | |
228 # The TinCan class. Simply a Bottle webapp that contains a forward method, so | |
229 # the code-behind can call request.app.forward(). | |
230 | |
231 class TinCan(bottle.Bottle): | |
232 def forward(self, target): | |
233 """ | |
234 Forward this request to the specified target route. | |
235 """ | |
236 source = bottle.request.environ['PATH_INFO'] | |
237 base = source.strip('/').split('/')[:-1] | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
238 if bottle.request.environ.get(_FTYPE, False): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
239 raise TinCanError("{0}: forward from error page".format(source)) |
0 | 240 try: |
241 exc = ForwardException('/' + '/'.join(_normpath(base, target))) | |
242 except IndexError as e: | |
243 raise TinCanError("{0}: invalid forward to {1!r}".format(source, target)) from e | |
244 raise exc | |
245 | |
2 | 246 # C o d e B e h i n d |
247 # | |
0 | 248 # Represents the code-behind of one of our pages. This gets subclassed, of |
249 # course. | |
250 | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
251 class BasePage(object): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
252 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
253 The parent class of both error and normal pages. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
254 """ |
0 | 255 def handle(self): |
256 """ | |
257 This is the entry point for the code-behind logic. It is intended | |
258 to be overridden. | |
259 """ | |
260 pass | |
261 | |
262 def export(self): | |
263 """ | |
264 Export template variables. The default behavior is to export all | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
265 non-hidden non-callables that don't start with an underscore. |
0 | 266 This method can be overridden if a different behavior is |
267 desired. It should always return a dict or dict-like object. | |
268 """ | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
269 ret = { 'page': self } |
0 | 270 for name in dir(self): |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
271 if name in self._HIDDEN or name.startswith('_'): |
0 | 272 continue |
273 value = getattr(self, name) | |
274 if callable(value): | |
275 continue | |
276 ret[name] = value | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
277 return ret |
0 | 278 |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
279 class Page(BasePage): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
280 # Non-private things we refuse to export anyhow. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
281 _HIDDEN = set([ "request", "response" ]) |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
282 |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
283 def __init__(self, req, resp): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
284 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
285 Constructor. This is a lightweight operation. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
286 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
287 self.request = req # app context is request.app in Bottle |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
288 self.response = resp |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
289 |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
290 class ErrorPage(BasePage): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
291 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
292 The code-behind for an error page. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
293 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
294 _HIDDEN = set() |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
295 |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
296 def __init__(self, req, err): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
297 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
298 Constructor. This is a lightweight operation. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
299 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
300 self.request = req |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
301 self.error = err |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
302 |
2 | 303 # R o u t e s |
304 # | |
0 | 305 # Represents a route in TinCan. Our launcher creates these on-the-fly based |
306 # on the files it finds. | |
307 | |
2 | 308 _ERRMIN = 400 |
309 _ERRMAX = 599 | |
310 _PEXTEN = ".py" | |
311 _TEXTEN = ".pspx" | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
312 _FLOOP = "tincan.forwards" |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
313 _FORIG = "tincan.origin" |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
314 _FTYPE = "tincan.iserror" |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
315 |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
316 class _TinCanErrorRoute(object): |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
317 """ |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
318 A route to an error page. These don't get routes created for them, |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
319 and are only reached if an error routes them there. Unless you create |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
320 custom code-behind, only two variables are available to your template: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
321 request (bottle.Request) and error (bottle.HTTPError). |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
322 """ |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
323 def __init__(self, template, klass): |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
324 self._template = template |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
325 self._template.prepare() |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
326 self._class = klass |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
327 |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
328 def __call__(self, e): |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
329 obj = self._class(bottle.request, e) |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
330 obj.handle() |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
331 return self._template.render(obj.export()).lstrip('\n') |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
332 |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
333 class _TinCanRoute(object): |
0 | 334 """ |
335 A route created by the TinCan launcher. | |
336 """ | |
337 def __init__(self, launcher, name, subdir): | |
338 self._fsroot = launcher.fsroot | |
339 self._urlroot = launcher.urlroot | |
340 self._name = name | |
2 | 341 self._python = name + _PEXTEN |
342 self._fspath = os.path.join(launcher.fsroot, *subdir, name + _TEXTEN) | |
343 self._urlpath = self._urljoin(launcher.urlroot, *subdir, name + _TEXTEN) | |
0 | 344 self._origin = self._urlpath |
345 self._subdir = subdir | |
346 self._seen = set() | |
347 self._tclass = launcher.tclass | |
348 self._app = launcher.app | |
349 | |
2 | 350 def launch(self): |
0 | 351 """ |
352 Launch a single page. | |
353 """ | |
354 # Build master and header objects, process #forward directives | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
355 hidden = oerrors = None |
0 | 356 while True: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
357 if oerrors is not None and oerrors != self._header.errors: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
358 raise TinCanError("{0}: invalid redirect") |
0 | 359 self._template = TemplateFile(self._fspath) |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
360 try: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
361 self._header = TemplateHeader(self._template.header) |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
362 except TemplateHeaderError as e: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
363 raise TinCanError("{0}: {1!s}".format(self._fspath, e)) from e |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
364 oerrors = self._header.errors |
0 | 365 if hidden is None: |
366 hidden = self._header.hidden | |
3 | 367 elif self._header.errors is not None: |
368 raise TinCanError("{0}: #forward to #errors not allowed".format(self._origin)) | |
0 | 369 if self._header.forward is None: |
370 break | |
371 self._redirect() | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
372 # If this is a #hidden page, we ignore it for now, since hidden pages |
0 | 373 # don't get routes made for them. |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
374 if hidden and not self._headers.errors: |
0 | 375 return |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
376 # Get the code-behind #python |
0 | 377 if self._header.python is not None: |
2 | 378 if not self._header.python.endswith(_PEXTEN): |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
379 raise TinCanError("{0}: #python files must end in {1}".format(self._urlpath, _PEXTEN)) |
0 | 380 self._python = self._header.python |
381 # Obtain a class object by importing and introspecting a module. | |
3 | 382 self._getclass() |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
383 # Build body object (#template) |
3 | 384 if self._header.template is not None: |
385 if not self._header.template.endswith(_TEXTEN): | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
386 raise TinCanError("{0}: #template files must end in {1}".format(self._urlpath, _TEXTEN)) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
387 tpath = os.path.normpath(os.path.join(self._fsroot, *self._splitpath(self._header.template))) |
3 | 388 tfile = TemplateFile(tpath) |
389 self._body = self._tclass(source=tfile.body) | |
390 else: | |
391 self._body = self._tclass(source=self._template.body) | |
392 self._body.prepare() | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
393 # If this is an #errors page, register it as such. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
394 if self._header.errors is not None: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
395 self._mkerror() |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
396 return # this implies #hidden |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
397 # Get #methods for this route |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
398 if self._header.methods is None: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
399 methods = [ 'GET' ] |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
400 else: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
401 methods = [ i.upper() for i in self._header.methods.split() ] |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
402 if not methods: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
403 raise TinCanError("{0}: no #methods specified".format(self._urlpath)) |
3 | 404 # Register this thing with Bottle |
6 | 405 print("adding route:", self._origin, '('+','.join(methods)+')') # debug |
3 | 406 self._app.route(self._origin, methods, self) |
407 | |
408 def _splitpath(self, unsplit): | |
409 return _normpath(self._subdir, unsplit) | |
410 | |
411 def _mkerror(self): | |
412 try: | |
413 errors = [ int(i) for i in self._header.errors.split() ] | |
414 except ValueError as e: | |
415 raise TinCanError("{0}: bad #errors line".format(self._urlpath)) from e | |
416 if not errors: | |
417 errors = range(_ERRMIN, _ERRMAX+1) | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
418 route = _TinCanErrorRoute(self._tclass(source=self._template.body), self._class) |
3 | 419 for error in errors: |
420 if error < _ERRMIN or error > _ERRMAX: | |
421 raise TinCanError("{0}: bad #errors code".format(self._urlpath)) | |
5 | 422 self._app.error_handler[error] = route # XXX |
3 | 423 |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
424 def _gettime(self, path): |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
425 try: |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
426 return os.stat(path).st_mtime |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
427 except FileNotFoundError: |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
428 return 0 |
8 | 429 except OSError as e: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
430 raise TinCanError(str(e)) from e |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
431 |
3 | 432 def _getclass(self): |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
433 pypath = os.path.normpath(os.path.join(self._fsroot, *self._splitpath(self._python))) |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
434 klass = ErrorPage if self._header.errors else Page |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
435 # Give 'em a default code-behind if they don't furnish one |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
436 pytime = self._gettime(pypath) |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
437 if not pytime: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
438 self._class = klass |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
439 return |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
440 # Else load the code-behind from a .py file |
0 | 441 pycpath = pypath + 'c' |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
442 pyctime = self._gettime(pycpath) |
0 | 443 try: |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
444 if pyctime < pytime: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
445 py_compile.compile(pypath, cfile=pycpath, doraise=True) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
446 except py_compile.PyCompileError as e: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
447 raise TinCanError(str(e)) from e |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
448 except Exception as e: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
449 raise TinCanError("{0}: {1!s}".format(pypath, e)) from e |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
450 try: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
451 spec = importlib.util.spec_from_file_location(_mangle(self._name), pycpath) |
0 | 452 mod = importlib.util.module_from_spec(spec) |
453 spec.loader.exec_module(mod) | |
454 except Exception as e: | |
455 raise TinCanError("{0}: error importing".format(pycpath)) from e | |
456 self._class = None | |
457 for i in dir(mod): | |
458 v = getattr(mod, i) | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
459 if isclass(v) and issubclass(v, klass): |
0 | 460 if self._class is not None: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
461 raise TinCanError("{0}: contains multiple {1} classes".format(pypath, klass.__name__)) |
0 | 462 self._class = v |
3 | 463 if self._class is None: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
464 raise TinCanError("{0}: contains no {1} classes".format(pypath, klass.__name__)) |
0 | 465 |
466 def _redirect(self): | |
467 try: | |
468 rlist = self._splitpath(self._header.forward) | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
469 forw = '/' + '/'.join(rlist) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
470 if forw in self.seen: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
471 raise TinCanError("{0}: #forward loop".format(self._origin)) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
472 self._seen.add(forw) |
0 | 473 rname = rlist.pop() |
474 except IndexError as e: | |
475 raise TinCanError("{0}: invalid #forward".format(self._urlpath)) from e | |
476 name, ext = os.path.splitext(rname)[1] | |
2 | 477 if ext != _TEXTEN: |
0 | 478 raise TinCanError("{0}: invalid #forward".format(self._urlpath)) |
479 self._subdir = rlist | |
2 | 480 self._python = name + _PEXTEN |
0 | 481 self._fspath = os.path.join(self._fsroot, *self._subdir, rname) |
482 self._urlpath = self._urljoin(*self._subdir, rname) | |
483 | |
484 def _urljoin(self, *args): | |
485 args = list(args) | |
486 if args[0] == '/': | |
487 args[0] = '' | |
488 return '/'.join(args) | |
489 | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
490 def __call__(self): |
0 | 491 """ |
492 This gets called by the framework AFTER the page is launched. | |
493 """ | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
494 target = None |
2 | 495 obj = self._class(bottle.request, bottle.response) |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
496 try: |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
497 obj.handle() |
2 | 498 return self._body.render(obj.export()).lstrip('\n') |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
499 except ForwardException as fwd: |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
500 target = fwd.target |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
501 if target is None: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
502 raise TinCanError("{0}: unexpected null target".format(self._urlpath)) |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
503 # We get here if we are doing a server-side programmatic |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
504 # forward. |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
505 environ = bottle.request.environ |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
506 if _FORIG not in environ: |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
507 environ[_FORIG] = self._urlpath |
2 | 508 if _FLOOP not in environ: |
509 environ[_FLOOP] = set([self._urlpath]) | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
510 elif target in environ[_FLOOP]: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
511 raise TinCanError("{0}: forward loop detected".format(environ[_FORIG])) |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
512 environ[_FLOOP].add(target) |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
513 environ['bottle.raw_path'] = target |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
514 environ['PATH_INFO'] = urllib.parse.quote(target) |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
515 route, args = self._app.router.match(environ) |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
516 environ['route.handle'] = environ['bottle.route'] = route |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
517 environ['route.url_args'] = args |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
518 return route.call(**args) |
0 | 519 |
520 def _mkdict(self, obj): | |
521 ret = {} | |
522 for name in dir(obj): | |
523 if name.startswith('_'): | |
524 continue | |
525 value = getattr(obj, name) | |
526 if not callable(value): | |
527 ret[name] = value | |
528 return ret | |
2 | 529 |
530 # L a u n c h e r | |
531 | |
532 _WINF = "WEB-INF" | |
533 _BANNED = set([_WINF]) | |
534 | |
535 class _Launcher(object): | |
536 """ | |
537 Helper class for launching webapps. | |
538 """ | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
539 def __init__(self, fsroot, urlroot, tclass, logger): |
2 | 540 """ |
541 Lightweight constructor. The real action happens in .launch() below. | |
542 """ | |
543 self.fsroot = fsroot | |
544 self.urlroot = urlroot | |
545 self.tclass = tclass | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
546 self.logger = logger |
2 | 547 self.app = None |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
548 self.errors = 0 |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
549 self.debug = False |
2 | 550 |
551 def launch(self): | |
552 """ | |
553 Does the actual work of launching something. XXX - modifies sys.path | |
554 and never un-modifies it. | |
555 """ | |
556 # Sanity checks | |
557 if not self.urlroot.startswith("/"): | |
558 raise TinCanError("urlroot must be absolute") | |
559 if not os.path.isdir(self.fsroot): | |
560 raise TinCanError("no such directory: {0!r}".format(self.fsroot)) | |
561 # Make WEB-INF, if needed | |
562 winf = os.path.join(self.fsroot, _WINF) | |
563 lib = os.path.join(winf, "lib") | |
564 for i in [ winf, lib ]: | |
565 if not os.path.isdir(i): | |
566 os.mkdir(i) | |
567 # Add our private lib directory to sys.path | |
568 sys.path.insert(1, os.path.abspath(lib)) | |
569 # Do what we gotta do | |
570 self.app = TinCan() | |
571 self._launch([]) | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
572 return self |
2 | 573 |
574 def _launch(self, subdir): | |
575 for entry in os.listdir(os.path.join(self.fsroot, *subdir)): | |
576 if not subdir and entry in _BANNED: | |
577 continue | |
578 etype = os.stat(os.path.join(self.fsroot, *subdir, entry)).st_mode | |
579 if S_ISREG(etype): | |
580 ename, eext = os.path.splitext(entry) | |
581 if eext != _TEXTEN: | |
582 continue # only look at interesting files | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
583 route = _TinCanRoute(self, ename, subdir) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
584 try: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
585 route.launch() |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
586 except TinCanError as e: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
587 self.logger(str(e)) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
588 if self.debug: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
589 while e.__cause__ != None: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
590 e = e.__cause__ |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
591 self.logger("\t{0}: {1!s}".format(e.__class__.__name__, e)) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
592 self.errors += 1 |
2 | 593 elif S_ISDIR(etype): |
594 self._launch(subdir + [entry]) | |
595 | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
596 def _logger(message): |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
597 sys.stderr.write(message) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
598 sys.stderr.write('\n') |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
599 |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
600 def launch(fsroot=None, urlroot='/', tclass=ChameleonTemplate, logger=_logger): |
2 | 601 """ |
602 Launch and return a TinCan webapp. Does not run the app; it is the | |
603 caller's responsibility to call app.run() | |
604 """ | |
605 if fsroot is None: | |
606 fsroot = os.getcwd() | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
607 launcher = _Launcher(fsroot, urlroot, tclass, logger) |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
608 # launcher.debug = True |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
609 launcher.launch() |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
610 return launcher.app, launcher.errors |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
611 |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
612 # XXX - We cannot implement a command-line launcher here; see the |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
613 # launcher script for why. |