Mercurial > cgi-bin > hgweb.cgi > tincan
annotate tincan.py @ 53:3a6180c1feea draft
Remove some needless repetition.
author | David Barts <n5jrn@me.com> |
---|---|
date | Fri, 31 May 2019 08:23:37 -0700 |
parents | 997d0c8c174f |
children | cb5a6e200c95 |
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 | |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
11 import email.utils |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
12 import functools |
2 | 13 import importlib |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
14 from inspect import isclass |
0 | 15 import io |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
16 import logging |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
17 import mimetypes |
2 | 18 import py_compile |
19 from stat import S_ISDIR, S_ISREG | |
5 | 20 from string import whitespace |
43 | 21 from threading import Lock |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
22 import time |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
23 import urllib |
0 | 24 |
25 import bottle | |
26 | |
2 | 27 # E x c e p t i o n s |
0 | 28 |
29 class TinCanException(Exception): | |
30 """ | |
31 The parent class of all exceptions we raise. | |
32 """ | |
33 pass | |
34 | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
35 class TemplateHeaderError(TinCanException): |
0 | 36 """ |
37 Raised upon encountering a syntax error in the template headers. | |
38 """ | |
39 def __init__(self, message, line): | |
40 super().__init__(message, line) | |
41 self.message = message | |
42 self.line = line | |
43 | |
44 def __str__(self): | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
45 return "line {0}: {1}".format(self.line, self.message) |
0 | 46 |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
47 class LoadError(TinCanException): |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
48 """ |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
49 Raised when we run into problems #load'ing something, usually |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
50 because it doesn't exist. |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
51 """ |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
52 def __init__(self, message, source): |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
53 super().__init__(message, source) |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
54 self.message = message |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
55 self.source = source |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
56 |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
57 def __str__(self): |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
58 return "{0}: #load error: {1}".format(self.source, self.message) |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
59 |
0 | 60 class ForwardException(TinCanException): |
61 """ | |
62 Raised to effect the flow control needed to do a forward (server-side | |
63 redirect). It is ugly to do this, but other Python frameworks do and | |
64 there seems to be no good alternative. | |
65 """ | |
66 def __init__(self, target): | |
67 self.target = target | |
68 | |
69 class TinCanError(TinCanException): | |
70 """ | |
71 General-purpose exception thrown by TinCan when things go wrong, often | |
72 when attempting to launch webapps. | |
73 """ | |
74 pass | |
75 | |
2 | 76 # T e m p l a t e s |
77 # | |
0 | 78 # Template (.pspx) files. These are standard templates for a supported |
79 # template engine, but with an optional set of header lines that begin | |
80 # with '#'. | |
81 | |
82 class TemplateFile(object): | |
83 """ | |
84 Parse a template file into a header part and the body part. The header | |
85 is always a leading set of lines, each starting with '#', that is of the | |
86 same format regardless of the template body. The template body varies | |
87 depending on the selected templating engine. The body part has | |
88 each header line replaced by a blank line. This preserves the overall | |
89 line numbering when processing the body. The added newlines are normally | |
90 stripped out before the rendered page is sent back to the client. | |
91 """ | |
5 | 92 _END = "#end" |
93 _LEND = len(_END) | |
94 _WS = set(whitespace) | |
95 | |
0 | 96 def __init__(self, raw, encoding='utf-8'): |
97 if isinstance(raw, io.TextIOBase): | |
98 self._do_init(raw) | |
99 elif isinstance(raw, str): | |
100 with open(raw, "r", encoding=encoding) as fp: | |
101 self._do_init(fp) | |
102 else: | |
103 raise TypeError("Expecting a string or Text I/O object.") | |
104 | |
105 def _do_init(self, fp): | |
106 self._hbuf = [] | |
107 self._bbuf = [] | |
108 self._state = self._header | |
109 while True: | |
110 line = fp.readline() | |
111 if line == '': | |
112 break | |
113 self._state(line) | |
114 self.header = ''.join(self._hbuf) | |
115 self.body = ''.join(self._bbuf) | |
116 | |
117 def _header(self, line): | |
118 if not line.startswith('#'): | |
119 self._state = self._body | |
120 self._state(line) | |
121 return | |
5 | 122 if line.startswith(self._END) and (len(line) == self._LEND or line[self._LEND] in self._WS): |
123 self._state = self._body | |
0 | 124 self._hbuf.append(line) |
36 | 125 self._bbuf.append("\n") |
0 | 126 |
127 def _body(self, line): | |
128 self._bbuf.append(line) | |
129 | |
130 class TemplateHeader(object): | |
131 """ | |
132 Parses and represents a set of header lines. | |
133 """ | |
2 | 134 _NAMES = [ "errors", "forward", "methods", "python", "template" ] |
0 | 135 _FNAMES = [ "hidden" ] |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
136 _ANAMES = [ "load" ] |
0 | 137 |
138 def __init__(self, string): | |
139 # Initialize our state | |
140 for i in self._NAMES: | |
141 setattr(self, i, None) | |
142 for i in self._FNAMES: | |
143 setattr(self, i, False) | |
25
e93e5e746cc5
Preliminary debugging, still not fully tested.
David Barts <n5jrn@me.com>
parents:
24
diff
changeset
|
144 for i in self._ANAMES: |
e93e5e746cc5
Preliminary debugging, still not fully tested.
David Barts <n5jrn@me.com>
parents:
24
diff
changeset
|
145 setattr(self, i, []) |
0 | 146 # Parse the string |
147 count = 0 | |
25
e93e5e746cc5
Preliminary debugging, still not fully tested.
David Barts <n5jrn@me.com>
parents:
24
diff
changeset
|
148 nameset = set(self._NAMES + self._FNAMES + self._ANAMES) |
0 | 149 seen = set() |
150 lines = string.split("\n") | |
151 if lines and lines[-1] == "": | |
152 del lines[-1] | |
153 for line in lines: | |
154 # Get line | |
155 count += 1 | |
156 if not line.startswith("#"): | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
157 raise TemplateHeaderError("Does not start with '#'.", count) |
0 | 158 try: |
159 rna, rpa = line.split(maxsplit=1) | |
160 except ValueError: | |
5 | 161 rna = line.rstrip() |
162 rpa = None | |
0 | 163 # Get name, ignoring remarks. |
164 name = rna[1:] | |
165 if name == "rem": | |
166 continue | |
5 | 167 if name == "end": |
168 break | |
0 | 169 if name not in nameset: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
170 raise TemplateHeaderError("Invalid directive: {0!r}".format(rna), count) |
0 | 171 if name in seen: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
172 raise TemplateHeaderError("Duplicate {0!r} directive.".format(rna), count) |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
173 if name not in self._ANAMES: |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
174 seen.add(name) |
0 | 175 # Flags |
5 | 176 if name in self._FNAMES: |
0 | 177 setattr(self, name, True) |
178 continue | |
179 # Get parameter | |
5 | 180 if rpa is None: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
181 raise TemplateHeaderError("Missing parameter.", count) |
0 | 182 param = rpa.strip() |
183 for i in [ "'", '"']: | |
184 if param.startswith(i) and param.endswith(i): | |
185 param = ast.literal_eval(param) | |
186 break | |
187 # Update this object | |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
188 if name in self._ANAMES: |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
189 getattr(self, name).append(param) |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
190 else: |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
191 setattr(self, name, param) |
0 | 192 |
23
e8b6ee7e5b6b
Well, *that* attempt at includes didn't work. Revert.
David Barts <n5jrn@me.com>
parents:
22
diff
changeset
|
193 # C h a m e l e o n |
2 | 194 # |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
195 # Support for Chameleon templates (the kind TinCan uses). |
0 | 196 |
197 class ChameleonTemplate(bottle.BaseTemplate): | |
198 def prepare(self, **options): | |
23
e8b6ee7e5b6b
Well, *that* attempt at includes didn't work. Revert.
David Barts <n5jrn@me.com>
parents:
22
diff
changeset
|
199 from chameleon import PageTemplate, PageTemplateFile |
0 | 200 if self.source: |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
201 self.tpl = PageTemplate(self.source, **options) |
0 | 202 else: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
203 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
|
204 search_path=self.lookup, **options) |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
205 # XXX - work around broken Chameleon decoding |
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
206 self.tpl.default_encoding = self.encoding |
0 | 207 |
208 def render(self, *args, **kwargs): | |
209 for dictarg in args: | |
210 kwargs.update(dictarg) | |
211 _defaults = self.defaults.copy() | |
212 _defaults.update(kwargs) | |
213 return self.tpl.render(**_defaults) | |
214 | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
215 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
|
216 chameleon_view = functools.partial(bottle.view, template_adapter=ChameleonTemplate) |
0 | 217 |
2 | 218 # U t i l i t i e s |
0 | 219 |
220 def _normpath(base, unsplit): | |
221 """ | |
222 Split, normalize and ensure a possibly relative path is absolute. First | |
223 argument is a list of directory names, defining a base. Second | |
224 argument is a string, which may either be relative to that base, or | |
225 absolute. Only '/' is supported as a separator. | |
226 """ | |
227 scratch = unsplit.strip('/').split('/') | |
228 if not unsplit.startswith('/'): | |
229 scratch = base + scratch | |
230 ret = [] | |
231 for i in scratch: | |
232 if i == '.': | |
233 continue | |
234 if i == '..': | |
235 ret.pop() # may raise IndexError | |
236 continue | |
237 ret.append(i) | |
238 return ret | |
239 | |
240 def _mangle(string): | |
241 """ | |
242 Turn a possibly troublesome identifier into a mangled one. | |
243 """ | |
244 first = True | |
245 ret = [] | |
246 for ch in string: | |
247 if ch == '_' or not (ch if first else "x" + ch).isidentifier(): | |
248 ret.append('_') | |
249 ret.append(b16encode(ch.encode("utf-8")).decode("us-ascii")) | |
250 else: | |
251 ret.append(ch) | |
252 first = False | |
253 return ''.join(ret) | |
254 | |
255 # The TinCan class. Simply a Bottle webapp that contains a forward method, so | |
256 # the code-behind can call request.app.forward(). | |
257 | |
258 class TinCan(bottle.Bottle): | |
259 def forward(self, target): | |
260 """ | |
261 Forward this request to the specified target route. | |
262 """ | |
263 source = bottle.request.environ['PATH_INFO'] | |
264 base = source.strip('/').split('/')[:-1] | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
265 if bottle.request.environ.get(_FTYPE, False): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
266 raise TinCanError("{0}: forward from error page".format(source)) |
0 | 267 try: |
268 exc = ForwardException('/' + '/'.join(_normpath(base, target))) | |
269 except IndexError as e: | |
270 raise TinCanError("{0}: invalid forward to {1!r}".format(source, target)) from e | |
271 raise exc | |
272 | |
2 | 273 # C o d e B e h i n d |
274 # | |
0 | 275 # Represents the code-behind of one of our pages. This gets subclassed, of |
276 # course. | |
277 | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
278 class BasePage(object): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
279 """ |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
280 The parent class of both error and normal pages' code-behind. |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
281 """ |
0 | 282 def handle(self): |
283 """ | |
284 This is the entry point for the code-behind logic. It is intended | |
285 to be overridden. | |
286 """ | |
287 pass | |
288 | |
289 def export(self): | |
290 """ | |
291 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
|
292 non-hidden non-callables that don't start with an underscore. |
0 | 293 This method can be overridden if a different behavior is |
294 desired. It should always return a dict or dict-like object. | |
295 """ | |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
296 ret = { 'page': self } |
0 | 297 for name in dir(self): |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
298 if name in self._HIDDEN or name.startswith('_'): |
0 | 299 continue |
300 value = getattr(self, name) | |
301 if callable(value): | |
302 continue | |
303 ret[name] = value | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
304 return ret |
0 | 305 |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
306 class Page(BasePage): |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
307 """ |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
308 The code-behind for a normal page. |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
309 """ |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
310 # 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
|
311 _HIDDEN = set([ "request", "response" ]) |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
312 |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
313 def __init__(self, req, resp): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
314 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
315 Constructor. This is a lightweight operation. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
316 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
317 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
|
318 self.response = resp |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
319 |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
320 class ErrorPage(BasePage): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
321 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
322 The code-behind for an error page. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
323 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
324 _HIDDEN = set() |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
325 |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
326 def __init__(self, req, err): |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
327 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
328 Constructor. This is a lightweight operation. |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
329 """ |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
330 self.request = req |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
331 self.error = err |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
332 |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
333 # I n c l u s i o n |
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
334 # |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
335 # Most processing is in the TinCanRoute class; this just interprets and |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
336 # represents arguments to the #load header directive. |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
337 |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
338 class _LoadedFile(object): |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
339 def __init__(self, raw): |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
340 if raw.startswith('<') and raw.endswith('>'): |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
341 raw = raw[1:-1] |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
342 self.in_lib = True |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
343 else: |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
344 self.in_lib = False |
31
443a0001d841
Improve the #include syntax a bit.
David Barts <n5jrn@me.com>
parents:
30
diff
changeset
|
345 equals = raw.find('=') |
443a0001d841
Improve the #include syntax a bit.
David Barts <n5jrn@me.com>
parents:
30
diff
changeset
|
346 if equals < 0: |
33
cc975bf7a3fa
Fix bug in auto-generated include variables.
David Barts <n5jrn@me.com>
parents:
32
diff
changeset
|
347 self.vname = os.path.splitext(os.path.basename(raw))[0] |
31
443a0001d841
Improve the #include syntax a bit.
David Barts <n5jrn@me.com>
parents:
30
diff
changeset
|
348 self.fname = raw |
443a0001d841
Improve the #include syntax a bit.
David Barts <n5jrn@me.com>
parents:
30
diff
changeset
|
349 else: |
443a0001d841
Improve the #include syntax a bit.
David Barts <n5jrn@me.com>
parents:
30
diff
changeset
|
350 self.vname = raw[:equals] |
443a0001d841
Improve the #include syntax a bit.
David Barts <n5jrn@me.com>
parents:
30
diff
changeset
|
351 self.fname = raw[equals+1:] |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
352 if self.vname == "": |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
353 raise ValueError("empty variable name") |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
354 if self.fname == "": |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
355 raise ValueError("empty file name") |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
356 if not self.fname.endswith(_IEXTEN): |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
357 raise ValueError("file does not end in {0}".format(_IEXTEN)) |
24
34d3cfcd37ef
First batch of work on getting a #include header. Unfinished.
David Barts <n5jrn@me.com>
parents:
23
diff
changeset
|
358 |
34 | 359 # Using a cache is likely to help efficiency a lot, since many pages |
43 | 360 # will typically #load the same standard stuff. Except if we're |
361 # multithreading, then we want each page's templates to be private. | |
34 | 362 _tcache = {} |
43 | 363 def _get_template_cache(name, direct, coding): |
34 | 364 aname = os.path.abspath(os.path.join(direct, name)) |
365 if aname not in _tcache: | |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
366 tmpl = ChameleonTemplate(name=name, lookup=[direct], encoding=coding) |
34 | 367 assert aname == tmpl.filename |
368 _tcache[aname] = tmpl | |
369 return _tcache[aname] | |
370 | |
43 | 371 def _get_template_nocache(name, direct, coding): |
372 return ChameleonTemplate(name=name, lookup=[direct], encoding=coding) | |
373 | |
2 | 374 # R o u t e s |
375 # | |
0 | 376 # Represents a route in TinCan. Our launcher creates these on-the-fly based |
377 # on the files it finds. | |
378 | |
2 | 379 _ERRMIN = 400 |
380 _ERRMAX = 599 | |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
381 _IEXTEN = ".pt" |
2 | 382 _PEXTEN = ".py" |
383 _TEXTEN = ".pspx" | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
384 _FLOOP = "tincan.forwards" |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
385 _FORIG = "tincan.origin" |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
386 _FTYPE = "tincan.iserror" |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
387 |
43 | 388 class _TinCanBaseRoute(object): |
389 """ | |
390 The base class for all NON ERROR routes. Error routes are just a little | |
391 bit different. | |
392 """ | |
393 def __init__(self, launcher, name, subdir): | |
394 global _get_template_cache, _get_template_nocache | |
395 if launcher.multithread: | |
396 self.lock = Lock() | |
397 self.get_template = _get_template_nocache | |
398 else: | |
399 self.lock = _DummyLock() | |
400 self.get_template = _get_template_cache | |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
401 self.logger = launcher.logger |
43 | 402 |
403 def urljoin(self, *args): | |
404 """ | |
405 Normalize a parsed-out URL fragment. | |
406 """ | |
407 args = list(args) | |
408 if args[0] == '/': | |
409 args[0] = '' | |
410 return '/'.join(args) | |
411 | |
412 def launch(self): | |
413 raise NotImplementedError("This must be overridden.") | |
414 | |
415 def __call__(self): | |
416 raise NotImplementedError("This must be overridden.") | |
417 | |
418 class _TinCanStaticRoute(_TinCanBaseRoute): | |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
419 """ |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
420 A route to a static file. These are useful for test servers. For |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
421 production servers, one is better off using a real web server and |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
422 a WSGI plugin, and having that handle static files. Much of this |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
423 logic is cribbed from the Bottle source code (we don't call it |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
424 directly because it is undocumented and thus subject to change). |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
425 """ |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
426 def __init__(self, launcher, name, subdir): |
43 | 427 super().__init__(launcher, name, subdir) |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
428 self._app = launcher.app |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
429 self._fspath = os.path.join(launcher.fsroot, *subdir, name) |
43 | 430 self._urlpath = self.urljoin(launcher.urlroot, *subdir, name) |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
431 self._type = mimetypes.guess_type(name)[0] |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
432 if self._type is None: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
433 self._type = "application/octet-stream" |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
434 if self._type.startswith("text/"): |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
435 self._encoding = launcher.encoding |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
436 self._type += "; charset=" + launcher.encoding |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
437 else: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
438 self._encoding = None |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
439 |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
440 def launch(self): |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
441 self.logger.info("adding static route: %s", self._urlpath) |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
442 self._app.route(self._urlpath, 'GET', self) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
443 |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
444 def _parse_date(self, ims): |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
445 """ |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
446 Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
447 """ |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
448 try: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
449 ts = email.utils.parsedate_tz(ims) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
450 return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
451 except (TypeError, ValueError, IndexError, OverflowError): |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
452 return None |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
453 |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
454 def __call__(self): |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
455 # Get file contents and time stamp. If we can't, return an |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
456 # appropriate HTTP error response. |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
457 try: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
458 with open(self._fspath, "rb") as fp: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
459 mtime = os.fstat(fp.fileno()).st_mtime |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
460 bytes = fp.read() |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
461 except FileNotFoundError as e: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
462 return bottle.HTTPError(status=404, exception=e) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
463 except PermissionError as e: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
464 return bottle.HTTPError(status=403, exception=e) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
465 except OSError as e: |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
466 self.logger.exception("unexpected exception reading %r", self._fspath) |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
467 return bottle.HTTPError(status=500, exception=e) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
468 # Establish preliminary standard headers. |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
469 headers = { |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
470 "Content-Type": self._type, |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
471 "Last-Modified": time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(mtime)), |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
472 } |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
473 if self._encoding: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
474 headers["Content-Encoding"] = self._encoding |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
475 # Support the If-Modified-Since request header. |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
476 ims = bottle.request.environ.get('HTTP_IF_MODIFIED_SINCE') |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
477 if ims: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
478 ims = self._parse_date(ims.split(";")[0].strip()) |
41 | 479 if ims is not None and ims >= int(mtime): |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
480 headers["Content-Length"] = "0" |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
481 return bottle.HTTPResponse(body=b"", status=304, headers=headers) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
482 # Standard response. |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
483 headers["Content-Length"] = str(len(bytes)) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
484 return bottle.HTTPResponse(body=bytes, status=200, headers=headers) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
485 |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
486 class _TinCanErrorRoute(object): |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
487 """ |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
488 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
|
489 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
|
490 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
|
491 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
|
492 """ |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
493 def __init__(self, template, loads, klass, lock, logger): |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
494 self._template = template |
23
e8b6ee7e5b6b
Well, *that* attempt at includes didn't work. Revert.
David Barts <n5jrn@me.com>
parents:
22
diff
changeset
|
495 self._template.prepare() |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
496 self._loads = loads |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
497 self._class = klass |
43 | 498 self.lock = lock |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
499 self.logger = logger |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
500 |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
501 def __call__(self, e): |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
502 bottle.request.environ[_FTYPE] = True |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
503 try: |
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
504 obj = self._class(bottle.request, e) |
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
505 obj.handle() |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
506 tvars = self._loads.copy() |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
507 tvars.update(obj.export()) |
43 | 508 with self.lock: |
509 return self._template.render(tvars).lstrip('\n') | |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
510 except bottle.HTTPResponse as e: |
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
511 return e |
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
512 except Exception as e: |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
513 self.logger.exception("unexpected exception in error page") |
18
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
514 # Bottle doesn't allow error handlers to themselves cause |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
515 # errors, most likely as a measure to prevent looping. So |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
516 # this will cause a "Critical error while processing request" |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
517 # page to be displayed, and any installed error pages to be |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
518 # ignored. |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
519 raise bottle.HTTPError(status=500, exception=e) |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
520 |
43 | 521 class _TinCanRoute(_TinCanBaseRoute): |
0 | 522 """ |
523 A route created by the TinCan launcher. | |
524 """ | |
525 def __init__(self, launcher, name, subdir): | |
43 | 526 super().__init__(launcher, name, subdir) |
0 | 527 self._fsroot = launcher.fsroot |
528 self._urlroot = launcher.urlroot | |
529 self._name = name | |
2 | 530 self._python = name + _PEXTEN |
531 self._fspath = os.path.join(launcher.fsroot, *subdir, name + _TEXTEN) | |
43 | 532 self._urlpath = self.urljoin(launcher.urlroot, *subdir, name + _TEXTEN) |
0 | 533 self._origin = self._urlpath |
534 self._subdir = subdir | |
535 self._seen = set() | |
536 self._app = launcher.app | |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
537 self._encoding = launcher.encoding |
0 | 538 |
2 | 539 def launch(self): |
0 | 540 """ |
541 Launch a single page. | |
542 """ | |
543 # Build master and header objects, process #forward directives | |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
544 oheader = None |
0 | 545 while True: |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
546 try: |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
547 self._template = TemplateFile(self._fspath) |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
548 except IOError as e: |
12
496d43d551d2
More redirecting fixes and improved error reportage.
David Barts <n5jrn@me.com>
parents:
11
diff
changeset
|
549 if oheader is not None: |
496d43d551d2
More redirecting fixes and improved error reportage.
David Barts <n5jrn@me.com>
parents:
11
diff
changeset
|
550 note = "{0}: invalid #forward: ".format(self._origin) |
496d43d551d2
More redirecting fixes and improved error reportage.
David Barts <n5jrn@me.com>
parents:
11
diff
changeset
|
551 else: |
496d43d551d2
More redirecting fixes and improved error reportage.
David Barts <n5jrn@me.com>
parents:
11
diff
changeset
|
552 note = "" |
496d43d551d2
More redirecting fixes and improved error reportage.
David Barts <n5jrn@me.com>
parents:
11
diff
changeset
|
553 raise TinCanError("{0}{1!s}".format(note, e)) from e |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
554 try: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
555 self._header = TemplateHeader(self._template.header) |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
556 except TemplateHeaderError as e: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
557 raise TinCanError("{0}: {1!s}".format(self._fspath, e)) from e |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
558 if oheader is None: |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
559 oheader = self._header # save original header |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
560 elif (oheader.errors is None) != (self._header.errors is None): |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
561 raise TinCanError("{0}: invalid #forward".format(self._origin)) |
0 | 562 if self._header.forward is None: |
563 break | |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
564 # self.logger.debug("forwarding from: %s", self._urlpath) # debug |
0 | 565 self._redirect() |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
566 # self.logger.debug("forwarded to: %s", self._urlpath) # debug |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
567 # If this is a #hidden page, we ignore it for now, since hidden pages |
0 | 568 # don't get routes made for them. |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
569 if oheader.hidden and not oheader.errors: |
0 | 570 return |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
571 # Get the code-behind #python |
15
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
572 if self._header.python is None: |
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
573 self._python_specified = False |
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
574 else: |
2 | 575 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
|
576 raise TinCanError("{0}: #python files must end in {1}".format(self._urlpath, _PEXTEN)) |
0 | 577 self._python = self._header.python |
15
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
578 self._python_specified = True |
0 | 579 # Obtain a class object by importing and introspecting a module. |
3 | 580 self._getclass() |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
581 # Build body object (#template) and obtain #loads. |
3 | 582 if self._header.template is not None: |
583 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
|
584 raise TinCanError("{0}: #template files must end in {1}".format(self._urlpath, _TEXTEN)) |
16 | 585 try: |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
586 rtpath = self._splitpath(self._header.template) |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
587 tpath = os.path.normpath(os.path.join(self._fsroot, *rtpath)) |
16 | 588 tfile = TemplateFile(tpath) |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
589 except OSError as e: |
16 | 590 raise TinCanError("{0}: invalid #template: {1!s}".format(self._urlpath, e)) from e |
591 except IndexError as e: | |
592 raise TinCanError("{0}: invalid #template".format(self._urlpath)) from e | |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
593 self._body = ChameleonTemplate(source=tfile.body, encoding=self._encoding) |
3 | 594 else: |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
595 self._body = ChameleonTemplate(source=self._template.body, encoding=self._encoding) |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
596 self._body.prepare() |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
597 # Process loads |
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
598 self._loads = {} |
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
599 for load in self._header.load: |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
600 try: |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
601 load = _LoadedFile(load) |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
602 except ValueError as e: |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
603 raise TinCanError("{0}: bad #load: {1!s}".format(self._urlpath, e)) from e |
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
604 if load.in_lib: |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
605 fdir = os.path.join(self._fsroot, _WINF, "tlib") |
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
606 else: |
32 | 607 fdir = os.path.join(self._fsroot, *self._subdir) |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
608 try: |
43 | 609 tmpl = self.get_template(load.fname, fdir, self._encoding) |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
610 except Exception as e: |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
611 raise TinCanError("{0}: bad #load: {1!s}".format(self._urlpath, e)) from e |
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
612 self._loads[load.vname] = tmpl.tpl |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
613 # If this is an #errors page, register it as such. |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
614 if oheader.errors is not None: |
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
615 self._mkerror(oheader.errors) |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
616 return # this implies #hidden |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
617 # Get #methods for this route |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
618 if self._header.methods is None: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
619 methods = [ 'GET' ] |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
620 else: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
621 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
|
622 if not methods: |
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
623 raise TinCanError("{0}: no #methods specified".format(self._urlpath)) |
3 | 624 # Register this thing with Bottle |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
625 self.logger.info("adding route: %s (%s)", self._origin, ','.join(methods)) |
3 | 626 self._app.route(self._origin, methods, self) |
627 | |
628 def _splitpath(self, unsplit): | |
629 return _normpath(self._subdir, unsplit) | |
630 | |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
631 def _mkerror(self, rerrors): |
3 | 632 try: |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
633 errors = [ int(i) for i in rerrors.split() ] |
3 | 634 except ValueError as e: |
635 raise TinCanError("{0}: bad #errors line".format(self._urlpath)) from e | |
636 if not errors: | |
637 errors = range(_ERRMIN, _ERRMAX+1) | |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
638 route = _TinCanErrorRoute( |
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
639 ChameleonTemplate(source=self._template.body, encoding=self._encoding), |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
640 self._loads, self._class, self.lock, self.logger) |
3 | 641 for error in errors: |
642 if error < _ERRMIN or error > _ERRMAX: | |
643 raise TinCanError("{0}: bad #errors code".format(self._urlpath)) | |
5 | 644 self._app.error_handler[error] = route # XXX |
3 | 645 |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
646 def _gettime(self, path): |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
647 try: |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
648 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
|
649 except FileNotFoundError: |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
650 return 0 |
8 | 651 except OSError as e: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
652 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
|
653 |
3 | 654 def _getclass(self): |
15
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
655 try: |
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
656 pypath = os.path.normpath(os.path.join(self._fsroot, *self._splitpath(self._python))) |
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
657 except IndexError as e: |
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
658 raise TinCanError("{0}: invalid #python".format(self._urlpath)) from e |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
659 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
|
660 # 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
|
661 pytime = self._gettime(pypath) |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
662 if not pytime: |
15
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
663 if self._python_specified: |
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
664 raise TinCanError("{0}: #python file not found".format(self._urlpath)) |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
665 self._class = klass |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
666 return |
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
667 # Else load the code-behind from a .py file |
0 | 668 pycpath = pypath + 'c' |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
669 pyctime = self._gettime(pycpath) |
0 | 670 try: |
7
57ec65f527e9
Eliminate a stat() call, allow no code-behind on pages.
David Barts <n5jrn@me.com>
parents:
6
diff
changeset
|
671 if pyctime < pytime: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
672 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
|
673 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
|
674 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
|
675 except Exception as e: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
676 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
|
677 try: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
678 spec = importlib.util.spec_from_file_location(_mangle(self._name), pycpath) |
0 | 679 mod = importlib.util.module_from_spec(spec) |
680 spec.loader.exec_module(mod) | |
681 except Exception as e: | |
16 | 682 raise TinCanError("{0}: error importing: {1!s}".format(pycpath, e)) from e |
19
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
683 # Locate a suitable class. We look for the "deepest" class object |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
684 # we can find in the inheritance tree. |
0 | 685 self._class = None |
19
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
686 score = -1 |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
687 ambig = False |
0 | 688 for i in dir(mod): |
689 v = getattr(mod, i) | |
19
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
690 if not isclass(v): |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
691 continue |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
692 d = self._cldepth(klass, v) |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
693 if d > score: |
15
560c8fb55e4a
Fix bugs in #python directive, make code-behind class loading simpler.
David Barts <n5jrn@me.com>
parents:
14
diff
changeset
|
694 self._class = v |
19
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
695 score = d |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
696 ambig = False |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
697 elif d == score: |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
698 ambig = True |
3 | 699 if self._class is None: |
9
75e375b1976a
Error pages now can have code-behind.
David Barts <n5jrn@me.com>
parents:
8
diff
changeset
|
700 raise TinCanError("{0}: contains no {1} classes".format(pypath, klass.__name__)) |
19
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
701 if ambig: |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
702 raise TinCanError("{0}: contains ambiguous {1} classes".format(pypath, klass.__name__)) |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
703 |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
704 # This might fail for complex inheritance schemes from the classes of |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
705 # interest (so don't use them!). |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
706 def _cldepth(self, base, klass, count=0): |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
707 if klass is object: |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
708 # not found |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
709 return -1 |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
710 elif klass is base: |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
711 # just found |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
712 return count |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
713 else: |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
714 # must recurse |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
715 for c in klass.__bases__: |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
716 result = self._cldepth(base, c, count=count+1) |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
717 if result > 0: |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
718 return result |
5d9a1b82251a
Return the "deepest" subclass; this allows subclassing tincan.Page and
David Barts <n5jrn@me.com>
parents:
18
diff
changeset
|
719 return -1 |
0 | 720 |
721 def _redirect(self): | |
722 try: | |
723 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
|
724 forw = '/' + '/'.join(rlist) |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
725 if forw in self._seen: |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
726 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
|
727 self._seen.add(forw) |
0 | 728 rname = rlist.pop() |
729 except IndexError as e: | |
730 raise TinCanError("{0}: invalid #forward".format(self._urlpath)) from e | |
11
8037bad7d5a8
Update documentation, fix some #forward bugs.
David Barts <n5jrn@me.com>
parents:
9
diff
changeset
|
731 name, ext = os.path.splitext(rname) |
2 | 732 if ext != _TEXTEN: |
0 | 733 raise TinCanError("{0}: invalid #forward".format(self._urlpath)) |
734 self._subdir = rlist | |
2 | 735 self._python = name + _PEXTEN |
0 | 736 self._fspath = os.path.join(self._fsroot, *self._subdir, rname) |
43 | 737 self._urlpath = '/' + self.urljoin(*self._subdir, rname) |
0 | 738 |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
739 def __call__(self): |
0 | 740 """ |
741 This gets called by the framework AFTER the page is launched. | |
742 """ | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
743 target = None |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
744 try: |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
745 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
|
746 obj.handle() |
35
41da0b3d2156
Rename #include to #load (more descriptive).
David Barts <n5jrn@me.com>
parents:
34
diff
changeset
|
747 tvars = self._loads.copy() |
29
2e3ac3d7b0a4
A possible workaround for the drainbamage (needs testing)?
David Barts <n5jrn@me.com>
parents:
26
diff
changeset
|
748 tvars.update(obj.export()) |
43 | 749 with self.lock: |
750 return self._body.render(tvars).lstrip('\n') | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
751 except ForwardException as fwd: |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
752 target = fwd.target |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
753 except bottle.HTTPResponse as e: |
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
754 return e |
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
755 except Exception as e: |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
756 self.logger.exception("%s: unexpected exception", self._urlpath) |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
757 raise bottle.HTTPError(status=500, exception=e) |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
758 if target is None: |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
759 self.logger.error("%s: unexpected null target", self._urlpath) |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
760 raise bottle.HTTPError(status=500, exception=TinCanError(message)) |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
761 # 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
|
762 # forward. |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
763 environ = bottle.request.environ |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
764 if _FORIG not in environ: |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
765 environ[_FORIG] = self._urlpath |
2 | 766 if _FLOOP not in environ: |
767 environ[_FLOOP] = set([self._urlpath]) | |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
768 elif target in environ[_FLOOP]: |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
769 self.logger.error("%s: forward loop detected", environ[_FORIG]) |
17
8186de188daf
Improve the run-time error handling in code-behinds.
David Barts <n5jrn@me.com>
parents:
16
diff
changeset
|
770 raise bottle.HTTPError(status=500, exception=TinCanError(message)) |
1
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
771 environ[_FLOOP].add(target) |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
772 environ['bottle.raw_path'] = target |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
773 environ['PATH_INFO'] = urllib.parse.quote(target) |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
774 route, args = self._app.router.match(environ) |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
775 environ['route.handle'] = environ['bottle.route'] = route |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
776 environ['route.url_args'] = args |
94b36e721500
Another check in to back stuff up.
David Barts <n5jrn@me.com>
parents:
0
diff
changeset
|
777 return route.call(**args) |
0 | 778 |
43 | 779 # M u t e x |
780 # | |
781 # A dummy lock class, which is what we use if we don't need locking. | |
782 | |
783 class _DummyLock(object): | |
784 def acquire(self, blocking=True, timeout=-1): | |
785 pass | |
786 | |
787 def release(self): | |
788 pass | |
789 | |
790 def __enter__(self): | |
791 self.acquire() | |
792 return self | |
793 | |
794 def __exit__(self, exc_type, exc_value, traceback): | |
795 self.release() | |
796 return False | |
797 | |
2 | 798 # L a u n c h e r |
799 | |
800 _WINF = "WEB-INF" | |
801 _BANNED = set([_WINF]) | |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
802 _EBANNED = set([_IEXTEN, _TEXTEN, _PEXTEN, _PEXTEN+"c"]) |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
803 ENCODING = "utf-8" |
53 | 804 _BITBUCKET = logging.getLogger(__name__) |
805 _BITBUCKET.addHandler(logging.NullHandler) | |
2 | 806 |
807 class _Launcher(object): | |
808 """ | |
809 Helper class for launching webapps. | |
810 """ | |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
811 def __init__(self, fsroot, urlroot, multithread): |
2 | 812 """ |
813 Lightweight constructor. The real action happens in .launch() below. | |
814 """ | |
815 self.fsroot = fsroot | |
816 self.urlroot = urlroot | |
817 self.app = None | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
818 self.errors = 0 |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
819 self.debug = False |
37
ce67eac10fc7
Allow global character encoding specification.
David Barts <n5jrn@me.com>
parents:
36
diff
changeset
|
820 self.encoding = ENCODING |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
821 self.static = False |
43 | 822 self.multithread = multithread |
53 | 823 self.logger = _BITBUCKET |
2 | 824 |
825 def launch(self): | |
826 """ | |
827 Does the actual work of launching something. XXX - modifies sys.path | |
828 and never un-modifies it. | |
829 """ | |
830 # Sanity checks | |
831 if not self.urlroot.startswith("/"): | |
18
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
832 self.errors = 1 |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
833 self.logger("urlroot not absolute: {0!r}".format(self.urlroot)) |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
834 return self |
2 | 835 if not os.path.isdir(self.fsroot): |
18
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
836 self.errors = 1 |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
837 self.logger("no such directory: {0!r}".format(self.fsroot)) |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
838 return self |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
839 # Make any needed directories. Refuse to launch things that don't |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
840 # contain WEB-INF, to prevent accidental launches of undesired |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
841 # directory trees containing sensitive files. |
2 | 842 winf = os.path.join(self.fsroot, _WINF) |
18
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
843 if not os.path.isdir(winf): |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
844 self.errors = 1 |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
845 self.logger("no WEB-INF directory in {0!r}".format(self.fsroot)) |
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
846 return self |
2 | 847 lib = os.path.join(winf, "lib") |
18
e88ab99914cf
More improvements to the error reportage.
David Barts <n5jrn@me.com>
parents:
17
diff
changeset
|
848 for i in [ lib ]: |
2 | 849 if not os.path.isdir(i): |
850 os.mkdir(i) | |
851 # Add our private lib directory to sys.path | |
852 sys.path.insert(1, os.path.abspath(lib)) | |
853 # Do what we gotta do | |
854 self.app = TinCan() | |
855 self._launch([]) | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
856 return self |
2 | 857 |
858 def _launch(self, subdir): | |
859 for entry in os.listdir(os.path.join(self.fsroot, *subdir)): | |
42
8948020c54fd
Remove some debug deadwood, ignore hidden files.
David Barts <n5jrn@me.com>
parents:
41
diff
changeset
|
860 if entry.startswith("."): |
8948020c54fd
Remove some debug deadwood, ignore hidden files.
David Barts <n5jrn@me.com>
parents:
41
diff
changeset
|
861 continue # hidden file |
2 | 862 if not subdir and entry in _BANNED: |
863 continue | |
864 etype = os.stat(os.path.join(self.fsroot, *subdir, entry)).st_mode | |
865 if S_ISREG(etype): | |
866 ename, eext = os.path.splitext(entry) | |
40
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
867 if eext == _TEXTEN: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
868 route = _TinCanRoute(self, ename, subdir) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
869 else: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
870 if eext in _EBANNED: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
871 continue |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
872 if self.static: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
873 route = _TinCanStaticRoute(self, entry, subdir) |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
874 else: |
df27cf08c093
Add support for serving static files.
David Barts <n5jrn@me.com>
parents:
37
diff
changeset
|
875 continue |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
876 try: |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
877 route.launch() |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
878 except TinCanError as e: |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
879 if self.logger.getEffectiveLevel() <= logging.DEBUG: |
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
880 self.logger.exception(str(e)) |
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
881 else: |
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
882 self.logger.error(str(e)) |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
883 self.errors += 1 |
2 | 884 elif S_ISDIR(etype): |
885 self._launch(subdir + [entry]) | |
886 | |
53 | 887 def launch(fsroot=None, urlroot='/', multithread=True, **kwargs): |
2 | 888 """ |
889 Launch and return a TinCan webapp. Does not run the app; it is the | |
890 caller's responsibility to call app.run() | |
891 """ | |
892 if fsroot is None: | |
893 fsroot = os.getcwd() | |
45
969f515b505b
Make it easy to leave stdout and stderr alone (untested).
David Barts <n5jrn@me.com>
parents:
44
diff
changeset
|
894 launcher = _Launcher(fsroot, urlroot, multithread) |
53 | 895 for i in [ "logger", "encoding", "static" ]: |
896 if i in kwargs: | |
897 setattr(launcher, i, kwargs[i]) | |
4
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
898 launcher.launch() |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
899 return launcher.app, launcher.errors |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
900 |
0d47859f792a
Finally got "hello, world" working. Still likely many bugs.
David Barts <n5jrn@me.com>
parents:
3
diff
changeset
|
901 # 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
|
902 # launcher script for why. |