ezKit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ezKit/bottle.py ADDED
@@ -0,0 +1,3809 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Bottle is a fast and simple micro-framework for small web applications. It
5
+ offers request dispatching (Routes) with url parameter support, templates,
6
+ a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
7
+ template engines - all in a single file and with no dependencies other than the
8
+ Python Standard Library.
9
+
10
+ Homepage and documentation: http://bottlepy.org/
11
+
12
+ Copyright (c) 2016, Marcel Hellkamp.
13
+ License: MIT (see LICENSE for details)
14
+ """
15
+
16
+ from __future__ import with_statement
17
+
18
+ __author__ = 'Marcel Hellkamp'
19
+ __version__ = '0.12.25'
20
+ __license__ = 'MIT'
21
+
22
+ # The gevent server adapter needs to patch some modules before they are imported
23
+ # This is why we parse the commandline parameters here but handle them later
24
+ if __name__ == '__main__':
25
+ from optparse import OptionParser
26
+ _cmd_parser = OptionParser(usage="usage: %prog [options] package.module:app")
27
+ _opt = _cmd_parser.add_option
28
+ _opt("--version", action="store_true", help="show version number.")
29
+ _opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.")
30
+ _opt("-s", "--server", default='wsgiref', help="use SERVER as backend.")
31
+ _opt("-p", "--plugin", action="append", help="install additional plugin/s.")
32
+ _opt("--debug", action="store_true", help="start server in debug mode.")
33
+ _opt("--reload", action="store_true", help="auto-reload on file changes.")
34
+ _cmd_options, _cmd_args = _cmd_parser.parse_args()
35
+ if _cmd_options.server and _cmd_options.server.startswith('gevent'):
36
+ import gevent.monkey; gevent.monkey.patch_all()
37
+
38
+ import base64, cgi, email.utils, functools, hmac, itertools, mimetypes,\
39
+ os, re, subprocess, sys, tempfile, threading, time, warnings, hashlib
40
+
41
+ from datetime import date as datedate, datetime, timedelta
42
+ from tempfile import TemporaryFile
43
+ from traceback import format_exc, print_exc
44
+ from unicodedata import normalize
45
+
46
+
47
+ try: from simplejson import dumps as json_dumps, loads as json_lds
48
+ except ImportError: # pragma: no cover
49
+ try: from json import dumps as json_dumps, loads as json_lds
50
+ except ImportError:
51
+ try: from django.utils.simplejson import dumps as json_dumps, loads as json_lds
52
+ except ImportError:
53
+ def json_dumps(data):
54
+ raise ImportError("JSON support requires Python 2.6 or simplejson.")
55
+ json_lds = json_dumps
56
+
57
+
58
+
59
+ # We now try to fix 2.5/2.6/3.1/3.2 incompatibilities.
60
+ # It ain't pretty but it works... Sorry for the mess.
61
+
62
+ py = sys.version_info
63
+ py3k = py >= (3, 0, 0)
64
+ py25 = py < (2, 6, 0)
65
+ py31 = (3, 1, 0) <= py < (3, 2, 0)
66
+
67
+ # Workaround for the missing "as" keyword in py3k.
68
+ def _e(): return sys.exc_info()[1]
69
+
70
+ # Workaround for the "print is a keyword/function" Python 2/3 dilemma
71
+ # and a fallback for mod_wsgi (resticts stdout/err attribute access)
72
+ try:
73
+ _stdout, _stderr = sys.stdout.write, sys.stderr.write
74
+ except IOError:
75
+ _stdout = lambda x: sys.stdout.write(x)
76
+ _stderr = lambda x: sys.stderr.write(x)
77
+
78
+ # Lots of stdlib and builtin differences.
79
+ if py3k:
80
+ import http.client as httplib
81
+ import _thread as thread
82
+ from urllib.parse import urljoin, SplitResult as UrlSplitResult
83
+ from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote
84
+ urlunquote = functools.partial(urlunquote, encoding='latin1')
85
+ from http.cookies import SimpleCookie
86
+ if py >= (3, 3, 0):
87
+ from collections.abc import MutableMapping as DictMixin
88
+ from types import ModuleType as new_module
89
+ else:
90
+ from collections import MutableMapping as DictMixin
91
+ from imp import new_module
92
+ import pickle
93
+ from io import BytesIO
94
+ from configparser import ConfigParser
95
+ from inspect import getfullargspec
96
+ def getargspec(func):
97
+ spec = getfullargspec(func)
98
+ kwargs = makelist(spec[0]) + makelist(spec.kwonlyargs)
99
+ return kwargs, spec[1], spec[2], spec[3]
100
+
101
+ basestring = str
102
+ unicode = str
103
+ json_loads = lambda s: json_lds(touni(s))
104
+ callable = lambda x: hasattr(x, '__call__')
105
+ imap = map
106
+ def _raise(*a): raise a[0](a[1]).with_traceback(a[2])
107
+ else: # 2.x
108
+ import httplib
109
+ import thread
110
+ from urlparse import urljoin, SplitResult as UrlSplitResult
111
+ from urllib import urlencode, quote as urlquote, unquote as urlunquote
112
+ from Cookie import SimpleCookie
113
+ from itertools import imap
114
+ import cPickle as pickle
115
+ from imp import new_module
116
+ from StringIO import StringIO as BytesIO
117
+ from ConfigParser import SafeConfigParser as ConfigParser
118
+ from inspect import getargspec
119
+ if py25:
120
+ msg = "Python 2.5 support may be dropped in future versions of Bottle."
121
+ warnings.warn(msg, DeprecationWarning)
122
+ from UserDict import DictMixin
123
+ def next(it): return it.next()
124
+ bytes = str
125
+ else: # 2.6, 2.7
126
+ from collections import MutableMapping as DictMixin
127
+ unicode = unicode
128
+ json_loads = json_lds
129
+ eval(compile('def _raise(*a): raise a[0], a[1], a[2]', '<py3fix>', 'exec'))
130
+
131
+ # Some helpers for string/byte handling
132
+ def tob(s, enc='utf8'):
133
+ return s.encode(enc) if isinstance(s, unicode) else bytes(s)
134
+ def touni(s, enc='utf8', err='strict'):
135
+ return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)
136
+ tonat = touni if py3k else tob
137
+
138
+ # 3.2 fixes cgi.FieldStorage to accept bytes (which makes a lot of sense).
139
+ # 3.1 needs a workaround.
140
+ if py31:
141
+ from io import TextIOWrapper
142
+ class NCTextIOWrapper(TextIOWrapper):
143
+ def close(self): pass # Keep wrapped buffer open.
144
+
145
+
146
+ # A bug in functools causes it to break if the wrapper is an instance method
147
+ def update_wrapper(wrapper, wrapped, *a, **ka):
148
+ try: functools.update_wrapper(wrapper, wrapped, *a, **ka)
149
+ except AttributeError: pass
150
+
151
+
152
+
153
+ # These helpers are used at module level and need to be defined first.
154
+ # And yes, I know PEP-8, but sometimes a lower-case classname makes more sense.
155
+
156
+ def depr(message, hard=False):
157
+ warnings.warn(message, DeprecationWarning, stacklevel=3)
158
+
159
+ def makelist(data): # This is just to handy
160
+ if isinstance(data, (tuple, list, set, dict)): return list(data)
161
+ elif data: return [data]
162
+ else: return []
163
+
164
+
165
+ class DictProperty(object):
166
+ ''' Property that maps to a key in a local dict-like attribute. '''
167
+ def __init__(self, attr, key=None, read_only=False):
168
+ self.attr, self.key, self.read_only = attr, key, read_only
169
+
170
+ def __call__(self, func):
171
+ functools.update_wrapper(self, func, updated=[])
172
+ self.getter, self.key = func, self.key or func.__name__
173
+ return self
174
+
175
+ def __get__(self, obj, cls):
176
+ if obj is None: return self
177
+ key, storage = self.key, getattr(obj, self.attr)
178
+ if key not in storage: storage[key] = self.getter(obj)
179
+ return storage[key]
180
+
181
+ def __set__(self, obj, value):
182
+ if self.read_only: raise AttributeError("Read-Only property.")
183
+ getattr(obj, self.attr)[self.key] = value
184
+
185
+ def __delete__(self, obj):
186
+ if self.read_only: raise AttributeError("Read-Only property.")
187
+ del getattr(obj, self.attr)[self.key]
188
+
189
+
190
+ class cached_property(object):
191
+ ''' A property that is only computed once per instance and then replaces
192
+ itself with an ordinary attribute. Deleting the attribute resets the
193
+ property. '''
194
+
195
+ def __init__(self, func):
196
+ self.__doc__ = getattr(func, '__doc__')
197
+ self.func = func
198
+
199
+ def __get__(self, obj, cls):
200
+ if obj is None: return self
201
+ value = obj.__dict__[self.func.__name__] = self.func(obj)
202
+ return value
203
+
204
+
205
+ class lazy_attribute(object):
206
+ ''' A property that caches itself to the class object. '''
207
+ def __init__(self, func):
208
+ functools.update_wrapper(self, func, updated=[])
209
+ self.getter = func
210
+
211
+ def __get__(self, obj, cls):
212
+ value = self.getter(cls)
213
+ setattr(cls, self.__name__, value)
214
+ return value
215
+
216
+
217
+
218
+
219
+
220
+
221
+ ###############################################################################
222
+ # Exceptions and Events ########################################################
223
+ ###############################################################################
224
+
225
+
226
+ class BottleException(Exception):
227
+ """ A base class for exceptions used by bottle. """
228
+ pass
229
+
230
+
231
+
232
+
233
+
234
+
235
+ ###############################################################################
236
+ # Routing ######################################################################
237
+ ###############################################################################
238
+
239
+
240
+ class RouteError(BottleException):
241
+ """ This is a base class for all routing related exceptions """
242
+
243
+
244
+ class RouteReset(BottleException):
245
+ """ If raised by a plugin or request handler, the route is reset and all
246
+ plugins are re-applied. """
247
+
248
+ class RouterUnknownModeError(RouteError): pass
249
+
250
+
251
+ class RouteSyntaxError(RouteError):
252
+ """ The route parser found something not supported by this router. """
253
+
254
+
255
+ class RouteBuildError(RouteError):
256
+ """ The route could not be built. """
257
+
258
+
259
+ def _re_flatten(p):
260
+ ''' Turn all capturing groups in a regular expression pattern into
261
+ non-capturing groups. '''
262
+ if '(' not in p: return p
263
+ return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))',
264
+ lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p)
265
+
266
+
267
+ class Router(object):
268
+ ''' A Router is an ordered collection of route->target pairs. It is used to
269
+ efficiently match WSGI requests against a number of routes and return
270
+ the first target that satisfies the request. The target may be anything,
271
+ usually a string, ID or callable object. A route consists of a path-rule
272
+ and a HTTP method.
273
+
274
+ The path-rule is either a static path (e.g. `/contact`) or a dynamic
275
+ path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax
276
+ and details on the matching order are described in docs:`routing`.
277
+ '''
278
+
279
+ default_pattern = '[^/]+'
280
+ default_filter = 're'
281
+
282
+ #: The current CPython regexp implementation does not allow more
283
+ #: than 99 matching groups per regular expression.
284
+ _MAX_GROUPS_PER_PATTERN = 99
285
+
286
+ def __init__(self, strict=False):
287
+ self.rules = [] # All rules in order
288
+ self._groups = {} # index of regexes to find them in dyna_routes
289
+ self.builder = {} # Data structure for the url builder
290
+ self.static = {} # Search structure for static routes
291
+ self.dyna_routes = {}
292
+ self.dyna_regexes = {} # Search structure for dynamic routes
293
+ #: If true, static routes are no longer checked first.
294
+ self.strict_order = strict
295
+ self.filters = {
296
+ 're': lambda conf:
297
+ (_re_flatten(conf or self.default_pattern), None, None),
298
+ 'int': lambda conf: (r'-?\d+', int, lambda x: str(int(x))),
299
+ 'float': lambda conf: (r'-?[\d.]+', float, lambda x: str(float(x))),
300
+ 'path': lambda conf: (r'.+?', None, None)}
301
+
302
+ def add_filter(self, name, func):
303
+ ''' Add a filter. The provided function is called with the configuration
304
+ string as parameter and must return a (regexp, to_python, to_url) tuple.
305
+ The first element is a string, the last two are callables or None. '''
306
+ self.filters[name] = func
307
+
308
+ rule_syntax = re.compile('(\\\\*)'\
309
+ '(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)'\
310
+ '|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)'\
311
+ '(?::((?:\\\\.|[^\\\\>])+)?)?)?>))')
312
+
313
+ def _itertokens(self, rule):
314
+ offset, prefix = 0, ''
315
+ for match in self.rule_syntax.finditer(rule):
316
+ prefix += rule[offset:match.start()]
317
+ g = match.groups()
318
+ if len(g[0])%2: # Escaped wildcard
319
+ prefix += match.group(0)[len(g[0]):]
320
+ offset = match.end()
321
+ continue
322
+ if prefix:
323
+ yield prefix, None, None
324
+ name, filtr, conf = g[4:7] if g[2] is None else g[1:4]
325
+ yield name, filtr or 'default', conf or None
326
+ offset, prefix = match.end(), ''
327
+ if offset <= len(rule) or prefix:
328
+ yield prefix+rule[offset:], None, None
329
+
330
+ def add(self, rule, method, target, name=None):
331
+ ''' Add a new rule or replace the target for an existing rule. '''
332
+ anons = 0 # Number of anonymous wildcards found
333
+ keys = [] # Names of keys
334
+ pattern = '' # Regular expression pattern with named groups
335
+ filters = [] # Lists of wildcard input filters
336
+ builder = [] # Data structure for the URL builder
337
+ is_static = True
338
+
339
+ for key, mode, conf in self._itertokens(rule):
340
+ if mode:
341
+ is_static = False
342
+ if mode == 'default': mode = self.default_filter
343
+ mask, in_filter, out_filter = self.filters[mode](conf)
344
+ if not key:
345
+ pattern += '(?:%s)' % mask
346
+ key = 'anon%d' % anons
347
+ anons += 1
348
+ else:
349
+ pattern += '(?P<%s>%s)' % (key, mask)
350
+ keys.append(key)
351
+ if in_filter: filters.append((key, in_filter))
352
+ builder.append((key, out_filter or str))
353
+ elif key:
354
+ pattern += re.escape(key)
355
+ builder.append((None, key))
356
+
357
+ self.builder[rule] = builder
358
+ if name: self.builder[name] = builder
359
+
360
+ if is_static and not self.strict_order:
361
+ self.static.setdefault(method, {})
362
+ self.static[method][self.build(rule)] = (target, None)
363
+ return
364
+
365
+ try:
366
+ re_pattern = re.compile('^(%s)$' % pattern)
367
+ re_match = re_pattern.match
368
+ except re.error:
369
+ raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, _e()))
370
+
371
+ if filters:
372
+ def getargs(path):
373
+ url_args = re_match(path).groupdict()
374
+ for name, wildcard_filter in filters:
375
+ try:
376
+ url_args[name] = wildcard_filter(url_args[name])
377
+ except ValueError:
378
+ raise HTTPError(400, 'Path has wrong format.')
379
+ return url_args
380
+ elif re_pattern.groupindex:
381
+ def getargs(path):
382
+ return re_match(path).groupdict()
383
+ else:
384
+ getargs = None
385
+
386
+ flatpat = _re_flatten(pattern)
387
+ whole_rule = (rule, flatpat, target, getargs)
388
+
389
+ if (flatpat, method) in self._groups:
390
+ if DEBUG:
391
+ msg = 'Route <%s %s> overwrites a previously defined route'
392
+ warnings.warn(msg % (method, rule), RuntimeWarning)
393
+ self.dyna_routes[method][self._groups[flatpat, method]] = whole_rule
394
+ else:
395
+ self.dyna_routes.setdefault(method, []).append(whole_rule)
396
+ self._groups[flatpat, method] = len(self.dyna_routes[method]) - 1
397
+
398
+ self._compile(method)
399
+
400
+ def _compile(self, method):
401
+ all_rules = self.dyna_routes[method]
402
+ comborules = self.dyna_regexes[method] = []
403
+ maxgroups = self._MAX_GROUPS_PER_PATTERN
404
+ for x in range(0, len(all_rules), maxgroups):
405
+ some = all_rules[x:x+maxgroups]
406
+ combined = (flatpat for (_, flatpat, _, _) in some)
407
+ combined = '|'.join('(^%s$)' % flatpat for flatpat in combined)
408
+ combined = re.compile(combined).match
409
+ rules = [(target, getargs) for (_, _, target, getargs) in some]
410
+ comborules.append((combined, rules))
411
+
412
+ def build(self, _name, *anons, **query):
413
+ ''' Build an URL by filling the wildcards in a rule. '''
414
+ builder = self.builder.get(_name)
415
+ if not builder: raise RouteBuildError("No route with that name.", _name)
416
+ try:
417
+ for i, value in enumerate(anons): query['anon%d'%i] = value
418
+ url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder])
419
+ return url if not query else url+'?'+urlencode(query)
420
+ except KeyError:
421
+ raise RouteBuildError('Missing URL argument: %r' % _e().args[0])
422
+
423
+ def match(self, environ):
424
+ ''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). '''
425
+ verb = environ['REQUEST_METHOD'].upper()
426
+ path = environ['PATH_INFO'] or '/'
427
+ target = None
428
+ if verb == 'HEAD':
429
+ methods = ['PROXY', verb, 'GET', 'ANY']
430
+ else:
431
+ methods = ['PROXY', verb, 'ANY']
432
+
433
+ for method in methods:
434
+ if method in self.static and path in self.static[method]:
435
+ target, getargs = self.static[method][path]
436
+ return target, getargs(path) if getargs else {}
437
+ elif method in self.dyna_regexes:
438
+ for combined, rules in self.dyna_regexes[method]:
439
+ match = combined(path)
440
+ if match:
441
+ target, getargs = rules[match.lastindex - 1]
442
+ return target, getargs(path) if getargs else {}
443
+
444
+ # No matching route found. Collect alternative methods for 405 response
445
+ allowed = set([])
446
+ nocheck = set(methods)
447
+ for method in set(self.static) - nocheck:
448
+ if path in self.static[method]:
449
+ allowed.add(method)
450
+ for method in set(self.dyna_regexes) - allowed - nocheck:
451
+ for combined, rules in self.dyna_regexes[method]:
452
+ match = combined(path)
453
+ if match:
454
+ allowed.add(method)
455
+ if allowed:
456
+ allow_header = ",".join(sorted(allowed))
457
+ raise HTTPError(405, "Method not allowed.", Allow=allow_header)
458
+
459
+ # No matching route and no alternative method found. We give up
460
+ raise HTTPError(404, "Not found: " + repr(path))
461
+
462
+
463
+
464
+
465
+
466
+
467
+ class Route(object):
468
+ ''' This class wraps a route callback along with route specific metadata and
469
+ configuration and applies Plugins on demand. It is also responsible for
470
+ turing an URL path rule into a regular expression usable by the Router.
471
+ '''
472
+
473
+ def __init__(self, app, rule, method, callback, name=None,
474
+ plugins=None, skiplist=None, **config):
475
+ #: The application this route is installed to.
476
+ self.app = app
477
+ #: The path-rule string (e.g. ``/wiki/:page``).
478
+ self.rule = rule
479
+ #: The HTTP method as a string (e.g. ``GET``).
480
+ self.method = method
481
+ #: The original callback with no plugins applied. Useful for introspection.
482
+ self.callback = callback
483
+ #: The name of the route (if specified) or ``None``.
484
+ self.name = name or None
485
+ #: A list of route-specific plugins (see :meth:`Bottle.route`).
486
+ self.plugins = plugins or []
487
+ #: A list of plugins to not apply to this route (see :meth:`Bottle.route`).
488
+ self.skiplist = skiplist or []
489
+ #: Additional keyword arguments passed to the :meth:`Bottle.route`
490
+ #: decorator are stored in this dictionary. Used for route-specific
491
+ #: plugin configuration and meta-data.
492
+ self.config = ConfigDict().load_dict(config, make_namespaces=True)
493
+
494
+ def __call__(self, *a, **ka):
495
+ depr("Some APIs changed to return Route() instances instead of"\
496
+ " callables. Make sure to use the Route.call method and not to"\
497
+ " call Route instances directly.") #0.12
498
+ return self.call(*a, **ka)
499
+
500
+ @cached_property
501
+ def call(self):
502
+ ''' The route callback with all plugins applied. This property is
503
+ created on demand and then cached to speed up subsequent requests.'''
504
+ return self._make_callback()
505
+
506
+ def reset(self):
507
+ ''' Forget any cached values. The next time :attr:`call` is accessed,
508
+ all plugins are re-applied. '''
509
+ self.__dict__.pop('call', None)
510
+
511
+ def prepare(self):
512
+ ''' Do all on-demand work immediately (useful for debugging).'''
513
+ self.call
514
+
515
+ @property
516
+ def _context(self):
517
+ depr('Switch to Plugin API v2 and access the Route object directly.') #0.12
518
+ return dict(rule=self.rule, method=self.method, callback=self.callback,
519
+ name=self.name, app=self.app, config=self.config,
520
+ apply=self.plugins, skip=self.skiplist)
521
+
522
+ def all_plugins(self):
523
+ ''' Yield all Plugins affecting this route. '''
524
+ unique = set()
525
+ for p in reversed(self.app.plugins + self.plugins):
526
+ if True in self.skiplist: break
527
+ name = getattr(p, 'name', False)
528
+ if name and (name in self.skiplist or name in unique): continue
529
+ if p in self.skiplist or type(p) in self.skiplist: continue
530
+ if name: unique.add(name)
531
+ yield p
532
+
533
+ def _make_callback(self):
534
+ callback = self.callback
535
+ for plugin in self.all_plugins():
536
+ try:
537
+ if hasattr(plugin, 'apply'):
538
+ api = getattr(plugin, 'api', 1)
539
+ context = self if api > 1 else self._context
540
+ callback = plugin.apply(callback, context)
541
+ else:
542
+ callback = plugin(callback)
543
+ except RouteReset: # Try again with changed configuration.
544
+ return self._make_callback()
545
+ if not callback is self.callback:
546
+ update_wrapper(callback, self.callback)
547
+ return callback
548
+
549
+ def get_undecorated_callback(self):
550
+ ''' Return the callback. If the callback is a decorated function, try to
551
+ recover the original function. '''
552
+ func = self.callback
553
+ func = getattr(func, '__func__' if py3k else 'im_func', func)
554
+ closure_attr = '__closure__' if py3k else 'func_closure'
555
+ while hasattr(func, closure_attr) and getattr(func, closure_attr):
556
+ func = getattr(func, closure_attr)[0].cell_contents
557
+ return func
558
+
559
+ def get_callback_args(self):
560
+ ''' Return a list of argument names the callback (most likely) accepts
561
+ as keyword arguments. If the callback is a decorated function, try
562
+ to recover the original function before inspection. '''
563
+ return getargspec(self.get_undecorated_callback())[0]
564
+
565
+ def get_config(self, key, default=None):
566
+ ''' Lookup a config field and return its value, first checking the
567
+ route.config, then route.app.config.'''
568
+ for conf in (self.config, self.app.config):
569
+ if key in conf: return conf[key]
570
+ return default
571
+
572
+ def __repr__(self):
573
+ cb = self.get_undecorated_callback()
574
+ return '<%s %r %r>' % (self.method, self.rule, cb)
575
+
576
+
577
+
578
+
579
+
580
+
581
+ ###############################################################################
582
+ # Application Object ###########################################################
583
+ ###############################################################################
584
+
585
+
586
+ class Bottle(object):
587
+ """ Each Bottle object represents a single, distinct web application and
588
+ consists of routes, callbacks, plugins, resources and configuration.
589
+ Instances are callable WSGI applications.
590
+
591
+ :param catchall: If true (default), handle all exceptions. Turn off to
592
+ let debugging middleware handle exceptions.
593
+ """
594
+
595
+ def __init__(self, catchall=True, autojson=True):
596
+
597
+ #: A :class:`ConfigDict` for app specific configuration.
598
+ self.config = ConfigDict()
599
+ self.config._on_change = functools.partial(self.trigger_hook, 'config')
600
+ self.config.meta_set('autojson', 'validate', bool)
601
+ self.config.meta_set('catchall', 'validate', bool)
602
+ self.config['catchall'] = catchall
603
+ self.config['autojson'] = autojson
604
+
605
+ #: A :class:`ResourceManager` for application files
606
+ self.resources = ResourceManager()
607
+
608
+ self.routes = [] # List of installed :class:`Route` instances.
609
+ self.router = Router() # Maps requests to :class:`Route` instances.
610
+ self.error_handler = {}
611
+
612
+ # Core plugins
613
+ self.plugins = [] # List of installed plugins.
614
+ if self.config['autojson']:
615
+ self.install(JSONPlugin())
616
+ self.install(TemplatePlugin())
617
+
618
+ #: If true, most exceptions are caught and returned as :exc:`HTTPError`
619
+ catchall = DictProperty('config', 'catchall')
620
+
621
+ __hook_names = 'before_request', 'after_request', 'app_reset', 'config'
622
+ __hook_reversed = 'after_request'
623
+
624
+ @cached_property
625
+ def _hooks(self):
626
+ return dict((name, []) for name in self.__hook_names)
627
+
628
+ def add_hook(self, name, func):
629
+ ''' Attach a callback to a hook. Three hooks are currently implemented:
630
+
631
+ before_request
632
+ Executed once before each request. The request context is
633
+ available, but no routing has happened yet.
634
+ after_request
635
+ Executed once after each request regardless of its outcome.
636
+ app_reset
637
+ Called whenever :meth:`Bottle.reset` is called.
638
+ '''
639
+ if name in self.__hook_reversed:
640
+ self._hooks[name].insert(0, func)
641
+ else:
642
+ self._hooks[name].append(func)
643
+
644
+ def remove_hook(self, name, func):
645
+ ''' Remove a callback from a hook. '''
646
+ if name in self._hooks and func in self._hooks[name]:
647
+ self._hooks[name].remove(func)
648
+ return True
649
+
650
+ def trigger_hook(self, __name, *args, **kwargs):
651
+ ''' Trigger a hook and return a list of results. '''
652
+ return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
653
+
654
+ def hook(self, name):
655
+ """ Return a decorator that attaches a callback to a hook. See
656
+ :meth:`add_hook` for details."""
657
+ def decorator(func):
658
+ self.add_hook(name, func)
659
+ return func
660
+ return decorator
661
+
662
+ def mount(self, prefix, app, **options):
663
+ ''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
664
+ URL prefix. Example::
665
+
666
+ root_app.mount('/admin/', admin_app)
667
+
668
+ :param prefix: path prefix or `mount-point`. If it ends in a slash,
669
+ that slash is mandatory.
670
+ :param app: an instance of :class:`Bottle` or a WSGI application.
671
+
672
+ All other parameters are passed to the underlying :meth:`route` call.
673
+ '''
674
+ if isinstance(app, basestring):
675
+ depr('Parameter order of Bottle.mount() changed.', True) # 0.10
676
+
677
+ segments = [p for p in prefix.split('/') if p]
678
+ if not segments: raise ValueError('Empty path prefix.')
679
+ path_depth = len(segments)
680
+
681
+ def mountpoint_wrapper():
682
+ try:
683
+ request.path_shift(path_depth)
684
+ rs = HTTPResponse([])
685
+ def start_response(status, headerlist, exc_info=None):
686
+ if exc_info:
687
+ try:
688
+ _raise(*exc_info)
689
+ finally:
690
+ exc_info = None
691
+ rs.status = status
692
+ for name, value in headerlist: rs.add_header(name, value)
693
+ return rs.body.append
694
+ body = app(request.environ, start_response)
695
+ if body and rs.body: body = itertools.chain(rs.body, body)
696
+ rs.body = body or rs.body
697
+ return rs
698
+ finally:
699
+ request.path_shift(-path_depth)
700
+
701
+ options.setdefault('skip', True)
702
+ options.setdefault('method', 'PROXY')
703
+ options.setdefault('mountpoint', {'prefix': prefix, 'target': app})
704
+ options['callback'] = mountpoint_wrapper
705
+
706
+ self.route('/%s/<:re:.*>' % '/'.join(segments), **options)
707
+ if not prefix.endswith('/'):
708
+ self.route('/' + '/'.join(segments), **options)
709
+
710
+ def merge(self, routes):
711
+ ''' Merge the routes of another :class:`Bottle` application or a list of
712
+ :class:`Route` objects into this application. The routes keep their
713
+ 'owner', meaning that the :data:`Route.app` attribute is not
714
+ changed. '''
715
+ if isinstance(routes, Bottle):
716
+ routes = routes.routes
717
+ for route in routes:
718
+ self.add_route(route)
719
+
720
+ def install(self, plugin):
721
+ ''' Add a plugin to the list of plugins and prepare it for being
722
+ applied to all routes of this application. A plugin may be a simple
723
+ decorator or an object that implements the :class:`Plugin` API.
724
+ '''
725
+ if hasattr(plugin, 'setup'): plugin.setup(self)
726
+ if not callable(plugin) and not hasattr(plugin, 'apply'):
727
+ raise TypeError("Plugins must be callable or implement .apply()")
728
+ self.plugins.append(plugin)
729
+ self.reset()
730
+ return plugin
731
+
732
+ def uninstall(self, plugin):
733
+ ''' Uninstall plugins. Pass an instance to remove a specific plugin, a type
734
+ object to remove all plugins that match that type, a string to remove
735
+ all plugins with a matching ``name`` attribute or ``True`` to remove all
736
+ plugins. Return the list of removed plugins. '''
737
+ removed, remove = [], plugin
738
+ for i, plugin in list(enumerate(self.plugins))[::-1]:
739
+ if remove is True or remove is plugin or remove is type(plugin) \
740
+ or getattr(plugin, 'name', True) == remove:
741
+ removed.append(plugin)
742
+ del self.plugins[i]
743
+ if hasattr(plugin, 'close'): plugin.close()
744
+ if removed: self.reset()
745
+ return removed
746
+
747
+ def reset(self, route=None):
748
+ ''' Reset all routes (force plugins to be re-applied) and clear all
749
+ caches. If an ID or route object is given, only that specific route
750
+ is affected. '''
751
+ if route is None: routes = self.routes
752
+ elif isinstance(route, Route): routes = [route]
753
+ else: routes = [self.routes[route]]
754
+ for route in routes: route.reset()
755
+ if DEBUG:
756
+ for route in routes: route.prepare()
757
+ self.trigger_hook('app_reset')
758
+
759
+ def close(self):
760
+ ''' Close the application and all installed plugins. '''
761
+ for plugin in self.plugins:
762
+ if hasattr(plugin, 'close'): plugin.close()
763
+ self.stopped = True
764
+
765
+ def run(self, **kwargs):
766
+ ''' Calls :func:`run` with the same parameters. '''
767
+ run(self, **kwargs)
768
+
769
+ def match(self, environ):
770
+ """ Search for a matching route and return a (:class:`Route` , urlargs)
771
+ tuple. The second value is a dictionary with parameters extracted
772
+ from the URL. Raise :exc:`HTTPError` (404/405) on a non-match."""
773
+ return self.router.match(environ)
774
+
775
+ def get_url(self, routename, **kargs):
776
+ """ Return a string that matches a named route """
777
+ scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
778
+ location = self.router.build(routename, **kargs).lstrip('/')
779
+ return urljoin(urljoin('/', scriptname), location)
780
+
781
+ def add_route(self, route):
782
+ ''' Add a route object, but do not change the :data:`Route.app`
783
+ attribute.'''
784
+ self.routes.append(route)
785
+ self.router.add(route.rule, route.method, route, name=route.name)
786
+ if DEBUG: route.prepare()
787
+
788
+ def route(self, path=None, method='GET', callback=None, name=None,
789
+ apply=None, skip=None, **config):
790
+ """ A decorator to bind a function to a request URL. Example::
791
+
792
+ @app.route('/hello/:name')
793
+ def hello(name):
794
+ return 'Hello %s' % name
795
+
796
+ The ``:name`` part is a wildcard. See :class:`Router` for syntax
797
+ details.
798
+
799
+ :param path: Request path or a list of paths to listen to. If no
800
+ path is specified, it is automatically generated from the
801
+ signature of the function.
802
+ :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
803
+ methods to listen to. (default: `GET`)
804
+ :param callback: An optional shortcut to avoid the decorator
805
+ syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
806
+ :param name: The name for this route. (default: None)
807
+ :param apply: A decorator or plugin or a list of plugins. These are
808
+ applied to the route callback in addition to installed plugins.
809
+ :param skip: A list of plugins, plugin classes or names. Matching
810
+ plugins are not installed to this route. ``True`` skips all.
811
+
812
+ Any additional keyword arguments are stored as route-specific
813
+ configuration and passed to plugins (see :meth:`Plugin.apply`).
814
+ """
815
+ if callable(path): path, callback = None, path
816
+ plugins = makelist(apply)
817
+ skiplist = makelist(skip)
818
+ def decorator(callback):
819
+ # TODO: Documentation and tests
820
+ if isinstance(callback, basestring): callback = load(callback)
821
+ for rule in makelist(path) or yieldroutes(callback):
822
+ for verb in makelist(method):
823
+ verb = verb.upper()
824
+ route = Route(self, rule, verb, callback, name=name,
825
+ plugins=plugins, skiplist=skiplist, **config)
826
+ self.add_route(route)
827
+ return callback
828
+ return decorator(callback) if callback else decorator
829
+
830
+ def get(self, path=None, method='GET', **options):
831
+ """ Equals :meth:`route`. """
832
+ return self.route(path, method, **options)
833
+
834
+ def post(self, path=None, method='POST', **options):
835
+ """ Equals :meth:`route` with a ``POST`` method parameter. """
836
+ return self.route(path, method, **options)
837
+
838
+ def put(self, path=None, method='PUT', **options):
839
+ """ Equals :meth:`route` with a ``PUT`` method parameter. """
840
+ return self.route(path, method, **options)
841
+
842
+ def delete(self, path=None, method='DELETE', **options):
843
+ """ Equals :meth:`route` with a ``DELETE`` method parameter. """
844
+ return self.route(path, method, **options)
845
+
846
+ def error(self, code=500):
847
+ """ Decorator: Register an output handler for a HTTP error code"""
848
+ def wrapper(handler):
849
+ self.error_handler[int(code)] = handler
850
+ return handler
851
+ return wrapper
852
+
853
+ def default_error_handler(self, res):
854
+ return tob(template(ERROR_PAGE_TEMPLATE, e=res))
855
+
856
+ def _handle(self, environ):
857
+ try:
858
+
859
+ environ['bottle.app'] = self
860
+ request.bind(environ)
861
+ response.bind()
862
+
863
+ path = environ['bottle.raw_path'] = environ['PATH_INFO']
864
+ if py3k:
865
+ try:
866
+ environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
867
+ except UnicodeError:
868
+ return HTTPError(400, 'Invalid path string. Expected UTF-8')
869
+
870
+ try:
871
+ self.trigger_hook('before_request')
872
+ route, args = self.router.match(environ)
873
+ environ['route.handle'] = route
874
+ environ['bottle.route'] = route
875
+ environ['route.url_args'] = args
876
+ return route.call(**args)
877
+ finally:
878
+ self.trigger_hook('after_request')
879
+
880
+ except HTTPResponse:
881
+ return _e()
882
+ except RouteReset:
883
+ route.reset()
884
+ return self._handle(environ)
885
+ except (KeyboardInterrupt, SystemExit, MemoryError):
886
+ raise
887
+ except Exception:
888
+ if not self.catchall: raise
889
+ stacktrace = format_exc()
890
+ environ['wsgi.errors'].write(stacktrace)
891
+ return HTTPError(500, "Internal Server Error", _e(), stacktrace)
892
+
893
+ def _cast(self, out, peek=None):
894
+ """ Try to convert the parameter into something WSGI compatible and set
895
+ correct HTTP headers when possible.
896
+ Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
897
+ iterable of strings and iterable of unicodes
898
+ """
899
+
900
+ # Empty output is done here
901
+ if not out:
902
+ if 'Content-Length' not in response:
903
+ response['Content-Length'] = 0
904
+ return []
905
+ # Join lists of byte or unicode strings. Mixed lists are NOT supported
906
+ if isinstance(out, (tuple, list))\
907
+ and isinstance(out[0], (bytes, unicode)):
908
+ out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
909
+ # Encode unicode strings
910
+ if isinstance(out, unicode):
911
+ out = out.encode(response.charset)
912
+ # Byte Strings are just returned
913
+ if isinstance(out, bytes):
914
+ if 'Content-Length' not in response:
915
+ response['Content-Length'] = len(out)
916
+ return [out]
917
+ # HTTPError or HTTPException (recursive, because they may wrap anything)
918
+ # TODO: Handle these explicitly in handle() or make them iterable.
919
+ if isinstance(out, HTTPError):
920
+ out.apply(response)
921
+ out = self.error_handler.get(out.status_code, self.default_error_handler)(out)
922
+ return self._cast(out)
923
+ if isinstance(out, HTTPResponse):
924
+ out.apply(response)
925
+ return self._cast(out.body)
926
+
927
+ # File-like objects.
928
+ if hasattr(out, 'read'):
929
+ if 'wsgi.file_wrapper' in request.environ:
930
+ return request.environ['wsgi.file_wrapper'](out)
931
+ elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
932
+ return WSGIFileWrapper(out)
933
+
934
+ # Handle Iterables. We peek into them to detect their inner type.
935
+ try:
936
+ iout = iter(out)
937
+ first = next(iout)
938
+ while not first:
939
+ first = next(iout)
940
+ except StopIteration:
941
+ return self._cast('')
942
+ except HTTPResponse:
943
+ first = _e()
944
+ except (KeyboardInterrupt, SystemExit, MemoryError):
945
+ raise
946
+ except Exception:
947
+ if not self.catchall: raise
948
+ first = HTTPError(500, 'Unhandled exception', _e(), format_exc())
949
+
950
+ # These are the inner types allowed in iterator or generator objects.
951
+ if isinstance(first, HTTPResponse):
952
+ return self._cast(first)
953
+ elif isinstance(first, bytes):
954
+ new_iter = itertools.chain([first], iout)
955
+ elif isinstance(first, unicode):
956
+ encoder = lambda x: x.encode(response.charset)
957
+ new_iter = imap(encoder, itertools.chain([first], iout))
958
+ else:
959
+ msg = 'Unsupported response type: %s' % type(first)
960
+ return self._cast(HTTPError(500, msg))
961
+ if hasattr(out, 'close'):
962
+ new_iter = _closeiter(new_iter, out.close)
963
+ return new_iter
964
+
965
+ def wsgi(self, environ, start_response):
966
+ """ The bottle WSGI-interface. """
967
+ try:
968
+ out = self._cast(self._handle(environ))
969
+ # rfc2616 section 4.3
970
+ if response._status_code in (100, 101, 204, 304)\
971
+ or environ['REQUEST_METHOD'] == 'HEAD':
972
+ if hasattr(out, 'close'): out.close()
973
+ out = []
974
+ start_response(response._status_line, response.headerlist)
975
+ return out
976
+ except (KeyboardInterrupt, SystemExit, MemoryError):
977
+ raise
978
+ except Exception:
979
+ if not self.catchall: raise
980
+ err = '<h1>Critical error while processing request: %s</h1>' \
981
+ % html_escape(environ.get('PATH_INFO', '/'))
982
+ if DEBUG:
983
+ err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
984
+ '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
985
+ % (html_escape(repr(_e())), html_escape(format_exc()))
986
+ environ['wsgi.errors'].write(err)
987
+ headers = [('Content-Type', 'text/html; charset=UTF-8')]
988
+ start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
989
+ return [tob(err)]
990
+
991
+ def __call__(self, environ, start_response):
992
+ ''' Each instance of :class:'Bottle' is a WSGI application. '''
993
+ return self.wsgi(environ, start_response)
994
+
995
+
996
+
997
+
998
+
999
+
1000
+ ###############################################################################
1001
+ # HTTP and WSGI Tools ##########################################################
1002
+ ###############################################################################
1003
+
1004
+ class BaseRequest(object):
1005
+ """ A wrapper for WSGI environment dictionaries that adds a lot of
1006
+ convenient access methods and properties. Most of them are read-only.
1007
+
1008
+ Adding new attributes to a request actually adds them to the environ
1009
+ dictionary (as 'bottle.request.ext.<name>'). This is the recommended
1010
+ way to store and access request-specific data.
1011
+ """
1012
+
1013
+ __slots__ = ('environ')
1014
+
1015
+ #: Maximum size of memory buffer for :attr:`body` in bytes.
1016
+ MEMFILE_MAX = 102400
1017
+
1018
+ def __init__(self, environ=None):
1019
+ """ Wrap a WSGI environ dictionary. """
1020
+ #: The wrapped WSGI environ dictionary. This is the only real attribute.
1021
+ #: All other attributes actually are read-only properties.
1022
+ self.environ = {} if environ is None else environ
1023
+ self.environ['bottle.request'] = self
1024
+
1025
+ @DictProperty('environ', 'bottle.app', read_only=True)
1026
+ def app(self):
1027
+ ''' Bottle application handling this request. '''
1028
+ raise RuntimeError('This request is not connected to an application.')
1029
+
1030
+ @DictProperty('environ', 'bottle.route', read_only=True)
1031
+ def route(self):
1032
+ """ The bottle :class:`Route` object that matches this request. """
1033
+ raise RuntimeError('This request is not connected to a route.')
1034
+
1035
+ @DictProperty('environ', 'route.url_args', read_only=True)
1036
+ def url_args(self):
1037
+ """ The arguments extracted from the URL. """
1038
+ raise RuntimeError('This request is not connected to a route.')
1039
+
1040
+ @property
1041
+ def path(self):
1042
+ ''' The value of ``PATH_INFO`` with exactly one prefixed slash (to fix
1043
+ broken clients and avoid the "empty path" edge case). '''
1044
+ return '/' + self.environ.get('PATH_INFO','').lstrip('/')
1045
+
1046
+ @property
1047
+ def method(self):
1048
+ ''' The ``REQUEST_METHOD`` value as an uppercase string. '''
1049
+ return self.environ.get('REQUEST_METHOD', 'GET').upper()
1050
+
1051
+ @DictProperty('environ', 'bottle.request.headers', read_only=True)
1052
+ def headers(self):
1053
+ ''' A :class:`WSGIHeaderDict` that provides case-insensitive access to
1054
+ HTTP request headers. '''
1055
+ return WSGIHeaderDict(self.environ)
1056
+
1057
+ def get_header(self, name, default=None):
1058
+ ''' Return the value of a request header, or a given default value. '''
1059
+ return self.headers.get(name, default)
1060
+
1061
+ @DictProperty('environ', 'bottle.request.cookies', read_only=True)
1062
+ def cookies(self):
1063
+ """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
1064
+ decoded. Use :meth:`get_cookie` if you expect signed cookies. """
1065
+ cookies = SimpleCookie(self.environ.get('HTTP_COOKIE','')).values()
1066
+ return FormsDict((c.key, c.value) for c in cookies)
1067
+
1068
+ def get_cookie(self, key, default=None, secret=None):
1069
+ """ Return the content of a cookie. To read a `Signed Cookie`, the
1070
+ `secret` must match the one used to create the cookie (see
1071
+ :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
1072
+ cookie or wrong signature), return a default value. """
1073
+ value = self.cookies.get(key)
1074
+ if secret and value:
1075
+ dec = cookie_decode(value, secret) # (key, value) tuple or None
1076
+ return dec[1] if dec and dec[0] == key else default
1077
+ return value or default
1078
+
1079
+ @DictProperty('environ', 'bottle.request.query', read_only=True)
1080
+ def query(self):
1081
+ ''' The :attr:`query_string` parsed into a :class:`FormsDict`. These
1082
+ values are sometimes called "URL arguments" or "GET parameters", but
1083
+ not to be confused with "URL wildcards" as they are provided by the
1084
+ :class:`Router`. '''
1085
+ get = self.environ['bottle.get'] = FormsDict()
1086
+ pairs = _parse_qsl(self.environ.get('QUERY_STRING', ''))
1087
+ for key, value in pairs:
1088
+ get[key] = value
1089
+ return get
1090
+
1091
+ @DictProperty('environ', 'bottle.request.forms', read_only=True)
1092
+ def forms(self):
1093
+ """ Form values parsed from an `url-encoded` or `multipart/form-data`
1094
+ encoded POST or PUT request body. The result is returned as a
1095
+ :class:`FormsDict`. All keys and values are strings. File uploads
1096
+ are stored separately in :attr:`files`. """
1097
+ forms = FormsDict()
1098
+ forms.recode_unicode = self.POST.recode_unicode
1099
+ for name, item in self.POST.allitems():
1100
+ if not isinstance(item, FileUpload):
1101
+ forms[name] = item
1102
+ return forms
1103
+
1104
+ @DictProperty('environ', 'bottle.request.params', read_only=True)
1105
+ def params(self):
1106
+ """ A :class:`FormsDict` with the combined values of :attr:`query` and
1107
+ :attr:`forms`. File uploads are stored in :attr:`files`. """
1108
+ params = FormsDict()
1109
+ for key, value in self.query.allitems():
1110
+ params[key] = value
1111
+ for key, value in self.forms.allitems():
1112
+ params[key] = value
1113
+ return params
1114
+
1115
+ @DictProperty('environ', 'bottle.request.files', read_only=True)
1116
+ def files(self):
1117
+ """ File uploads parsed from `multipart/form-data` encoded POST or PUT
1118
+ request body. The values are instances of :class:`FileUpload`.
1119
+
1120
+ """
1121
+ files = FormsDict()
1122
+ files.recode_unicode = self.POST.recode_unicode
1123
+ for name, item in self.POST.allitems():
1124
+ if isinstance(item, FileUpload):
1125
+ files[name] = item
1126
+ return files
1127
+
1128
+ @DictProperty('environ', 'bottle.request.json', read_only=True)
1129
+ def json(self):
1130
+ ''' If the ``Content-Type`` header is ``application/json``, this
1131
+ property holds the parsed content of the request body. Only requests
1132
+ smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
1133
+ exhaustion. '''
1134
+ ctype = self.environ.get('CONTENT_TYPE', '').lower().split(';')[0]
1135
+ if ctype == 'application/json':
1136
+ b = self._get_body_string()
1137
+ if not b:
1138
+ return None
1139
+ return json_loads(b)
1140
+ return None
1141
+
1142
+ def _iter_body(self, read, bufsize):
1143
+ maxread = max(0, self.content_length)
1144
+ while maxread:
1145
+ part = read(min(maxread, bufsize))
1146
+ if not part: break
1147
+ yield part
1148
+ maxread -= len(part)
1149
+
1150
+ def _iter_chunked(self, read, bufsize):
1151
+ err = HTTPError(400, 'Error while parsing chunked transfer body.')
1152
+ rn, sem, bs = tob('\r\n'), tob(';'), tob('')
1153
+ while True:
1154
+ header = read(1)
1155
+ while header[-2:] != rn:
1156
+ c = read(1)
1157
+ header += c
1158
+ if not c: raise err
1159
+ if len(header) > bufsize: raise err
1160
+ size, _, _ = header.partition(sem)
1161
+ try:
1162
+ maxread = int(tonat(size.strip()), 16)
1163
+ except ValueError:
1164
+ raise err
1165
+ if maxread == 0: break
1166
+ buff = bs
1167
+ while maxread > 0:
1168
+ if not buff:
1169
+ buff = read(min(maxread, bufsize))
1170
+ part, buff = buff[:maxread], buff[maxread:]
1171
+ if not part: raise err
1172
+ yield part
1173
+ maxread -= len(part)
1174
+ if read(2) != rn:
1175
+ raise err
1176
+
1177
+ @DictProperty('environ', 'bottle.request.body', read_only=True)
1178
+ def _body(self):
1179
+ body_iter = self._iter_chunked if self.chunked else self._iter_body
1180
+ read_func = self.environ['wsgi.input'].read
1181
+ body, body_size, is_temp_file = BytesIO(), 0, False
1182
+ for part in body_iter(read_func, self.MEMFILE_MAX):
1183
+ body.write(part)
1184
+ body_size += len(part)
1185
+ if not is_temp_file and body_size > self.MEMFILE_MAX:
1186
+ body, tmp = TemporaryFile(mode='w+b'), body
1187
+ body.write(tmp.getvalue())
1188
+ del tmp
1189
+ is_temp_file = True
1190
+ self.environ['wsgi.input'] = body
1191
+ body.seek(0)
1192
+ return body
1193
+
1194
+ def _get_body_string(self):
1195
+ ''' read body until content-length or MEMFILE_MAX into a string. Raise
1196
+ HTTPError(413) on requests that are to large. '''
1197
+ clen = self.content_length
1198
+ if clen > self.MEMFILE_MAX:
1199
+ raise HTTPError(413, 'Request to large')
1200
+ if clen < 0: clen = self.MEMFILE_MAX + 1
1201
+ data = self.body.read(clen)
1202
+ if len(data) > self.MEMFILE_MAX: # Fail fast
1203
+ raise HTTPError(413, 'Request to large')
1204
+ return data
1205
+
1206
+ @property
1207
+ def body(self):
1208
+ """ The HTTP request body as a seek-able file-like object. Depending on
1209
+ :attr:`MEMFILE_MAX`, this is either a temporary file or a
1210
+ :class:`io.BytesIO` instance. Accessing this property for the first
1211
+ time reads and replaces the ``wsgi.input`` environ variable.
1212
+ Subsequent accesses just do a `seek(0)` on the file object. """
1213
+ self._body.seek(0)
1214
+ return self._body
1215
+
1216
+ @property
1217
+ def chunked(self):
1218
+ ''' True if Chunked transfer encoding was. '''
1219
+ return 'chunked' in self.environ.get('HTTP_TRANSFER_ENCODING', '').lower()
1220
+
1221
+ #: An alias for :attr:`query`.
1222
+ GET = query
1223
+
1224
+ @DictProperty('environ', 'bottle.request.post', read_only=True)
1225
+ def POST(self):
1226
+ """ The values of :attr:`forms` and :attr:`files` combined into a single
1227
+ :class:`FormsDict`. Values are either strings (form values) or
1228
+ instances of :class:`cgi.FieldStorage` (file uploads).
1229
+ """
1230
+ post = FormsDict()
1231
+ # We default to application/x-www-form-urlencoded for everything that
1232
+ # is not multipart and take the fast path (also: 3.1 workaround)
1233
+ if not self.content_type.startswith('multipart/'):
1234
+ pairs = _parse_qsl(tonat(self._get_body_string(), 'latin1'))
1235
+ for key, value in pairs:
1236
+ post[key] = value
1237
+ return post
1238
+
1239
+ safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
1240
+ for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
1241
+ if key in self.environ: safe_env[key] = self.environ[key]
1242
+ args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)
1243
+ if py31:
1244
+ args['fp'] = NCTextIOWrapper(args['fp'], encoding='utf8',
1245
+ newline='\n')
1246
+ elif py3k:
1247
+ args['encoding'] = 'utf8'
1248
+ post.recode_unicode = False
1249
+ data = cgi.FieldStorage(**args)
1250
+ self['_cgi.FieldStorage'] = data #http://bugs.python.org/issue18394#msg207958
1251
+ data = data.list or []
1252
+ for item in data:
1253
+ if item.filename is None:
1254
+ post[item.name] = item.value
1255
+ else:
1256
+ post[item.name] = FileUpload(item.file, item.name,
1257
+ item.filename, item.headers)
1258
+ return post
1259
+
1260
+ @property
1261
+ def url(self):
1262
+ """ The full request URI including hostname and scheme. If your app
1263
+ lives behind a reverse proxy or load balancer and you get confusing
1264
+ results, make sure that the ``X-Forwarded-Host`` header is set
1265
+ correctly. """
1266
+ return self.urlparts.geturl()
1267
+
1268
+ @DictProperty('environ', 'bottle.request.urlparts', read_only=True)
1269
+ def urlparts(self):
1270
+ ''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
1271
+ The tuple contains (scheme, host, path, query_string and fragment),
1272
+ but the fragment is always empty because it is not visible to the
1273
+ server. '''
1274
+ env = self.environ
1275
+ http = env.get('HTTP_X_FORWARDED_PROTO') or env.get('wsgi.url_scheme', 'http')
1276
+ host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')
1277
+ if not host:
1278
+ # HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients.
1279
+ host = env.get('SERVER_NAME', '127.0.0.1')
1280
+ port = env.get('SERVER_PORT')
1281
+ if port and port != ('80' if http == 'http' else '443'):
1282
+ host += ':' + port
1283
+ path = urlquote(self.fullpath)
1284
+ return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '')
1285
+
1286
+ @property
1287
+ def fullpath(self):
1288
+ """ Request path including :attr:`script_name` (if present). """
1289
+ return urljoin(self.script_name, self.path.lstrip('/'))
1290
+
1291
+ @property
1292
+ def query_string(self):
1293
+ """ The raw :attr:`query` part of the URL (everything in between ``?``
1294
+ and ``#``) as a string. """
1295
+ return self.environ.get('QUERY_STRING', '')
1296
+
1297
+ @property
1298
+ def script_name(self):
1299
+ ''' The initial portion of the URL's `path` that was removed by a higher
1300
+ level (server or routing middleware) before the application was
1301
+ called. This script path is returned with leading and tailing
1302
+ slashes. '''
1303
+ script_name = self.environ.get('SCRIPT_NAME', '').strip('/')
1304
+ return '/' + script_name + '/' if script_name else '/'
1305
+
1306
+ def path_shift(self, shift=1):
1307
+ ''' Shift path segments from :attr:`path` to :attr:`script_name` and
1308
+ vice versa.
1309
+
1310
+ :param shift: The number of path segments to shift. May be negative
1311
+ to change the shift direction. (default: 1)
1312
+ '''
1313
+ script = self.environ.get('SCRIPT_NAME','/')
1314
+ self['SCRIPT_NAME'], self['PATH_INFO'] = path_shift(script, self.path, shift)
1315
+
1316
+ @property
1317
+ def content_length(self):
1318
+ ''' The request body length as an integer. The client is responsible to
1319
+ set this header. Otherwise, the real length of the body is unknown
1320
+ and -1 is returned. In this case, :attr:`body` will be empty. '''
1321
+ return int(self.environ.get('CONTENT_LENGTH') or -1)
1322
+
1323
+ @property
1324
+ def content_type(self):
1325
+ ''' The Content-Type header as a lowercase-string (default: empty). '''
1326
+ return self.environ.get('CONTENT_TYPE', '').lower()
1327
+
1328
+ @property
1329
+ def is_xhr(self):
1330
+ ''' True if the request was triggered by a XMLHttpRequest. This only
1331
+ works with JavaScript libraries that support the `X-Requested-With`
1332
+ header (most of the popular libraries do). '''
1333
+ requested_with = self.environ.get('HTTP_X_REQUESTED_WITH','')
1334
+ return requested_with.lower() == 'xmlhttprequest'
1335
+
1336
+ @property
1337
+ def is_ajax(self):
1338
+ ''' Alias for :attr:`is_xhr`. "Ajax" is not the right term. '''
1339
+ return self.is_xhr
1340
+
1341
+ @property
1342
+ def auth(self):
1343
+ """ HTTP authentication data as a (user, password) tuple. This
1344
+ implementation currently supports basic (not digest) authentication
1345
+ only. If the authentication happened at a higher level (e.g. in the
1346
+ front web-server or a middleware), the password field is None, but
1347
+ the user field is looked up from the ``REMOTE_USER`` environ
1348
+ variable. On any errors, None is returned. """
1349
+ basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION',''))
1350
+ if basic: return basic
1351
+ ruser = self.environ.get('REMOTE_USER')
1352
+ if ruser: return (ruser, None)
1353
+ return None
1354
+
1355
+ @property
1356
+ def remote_route(self):
1357
+ """ A list of all IPs that were involved in this request, starting with
1358
+ the client IP and followed by zero or more proxies. This does only
1359
+ work if all proxies support the ```X-Forwarded-For`` header. Note
1360
+ that this information can be forged by malicious clients. """
1361
+ proxy = self.environ.get('HTTP_X_FORWARDED_FOR')
1362
+ if proxy: return [ip.strip() for ip in proxy.split(',')]
1363
+ remote = self.environ.get('REMOTE_ADDR')
1364
+ return [remote] if remote else []
1365
+
1366
+ @property
1367
+ def remote_addr(self):
1368
+ """ The client IP as a string. Note that this information can be forged
1369
+ by malicious clients. """
1370
+ route = self.remote_route
1371
+ return route[0] if route else None
1372
+
1373
+ def copy(self):
1374
+ """ Return a new :class:`Request` with a shallow :attr:`environ` copy. """
1375
+ return Request(self.environ.copy())
1376
+
1377
+ def get(self, value, default=None): return self.environ.get(value, default)
1378
+ def __getitem__(self, key): return self.environ[key]
1379
+ def __delitem__(self, key): self[key] = ""; del(self.environ[key])
1380
+ def __iter__(self): return iter(self.environ)
1381
+ def __len__(self): return len(self.environ)
1382
+ def keys(self): return self.environ.keys()
1383
+ def __setitem__(self, key, value):
1384
+ """ Change an environ value and clear all caches that depend on it. """
1385
+
1386
+ if self.environ.get('bottle.request.readonly'):
1387
+ raise KeyError('The environ dictionary is read-only.')
1388
+
1389
+ self.environ[key] = value
1390
+ todelete = ()
1391
+
1392
+ if key == 'wsgi.input':
1393
+ todelete = ('body', 'forms', 'files', 'params', 'post', 'json')
1394
+ elif key == 'QUERY_STRING':
1395
+ todelete = ('query', 'params')
1396
+ elif key.startswith('HTTP_'):
1397
+ todelete = ('headers', 'cookies')
1398
+
1399
+ for key in todelete:
1400
+ self.environ.pop('bottle.request.'+key, None)
1401
+
1402
+ def __repr__(self):
1403
+ return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url)
1404
+
1405
+ def __getattr__(self, name):
1406
+ ''' Search in self.environ for additional user defined attributes. '''
1407
+ try:
1408
+ var = self.environ['bottle.request.ext.%s'%name]
1409
+ return var.__get__(self) if hasattr(var, '__get__') else var
1410
+ except KeyError:
1411
+ raise AttributeError('Attribute %r not defined.' % name)
1412
+
1413
+ def __setattr__(self, name, value):
1414
+ if name == 'environ': return object.__setattr__(self, name, value)
1415
+ self.environ['bottle.request.ext.%s'%name] = value
1416
+
1417
+
1418
+ def _hkey(key):
1419
+ if '\n' in key or '\r' in key or '\0' in key:
1420
+ raise ValueError("Header names must not contain control characters: %r" % key)
1421
+ return key.title().replace('_', '-')
1422
+
1423
+
1424
+ def _hval(value):
1425
+ value = tonat(value)
1426
+ if '\n' in value or '\r' in value or '\0' in value:
1427
+ raise ValueError("Header value must not contain control characters: %r" % value)
1428
+ return value
1429
+
1430
+
1431
+
1432
+ class HeaderProperty(object):
1433
+ def __init__(self, name, reader=None, writer=None, default=''):
1434
+ self.name, self.default = name, default
1435
+ self.reader, self.writer = reader, writer
1436
+ self.__doc__ = 'Current value of the %r header.' % name.title()
1437
+
1438
+ def __get__(self, obj, cls):
1439
+ if obj is None: return self
1440
+ value = obj.get_header(self.name, self.default)
1441
+ return self.reader(value) if self.reader else value
1442
+
1443
+ def __set__(self, obj, value):
1444
+ obj[self.name] = self.writer(value) if self.writer else value
1445
+
1446
+ def __delete__(self, obj):
1447
+ del obj[self.name]
1448
+
1449
+
1450
+ class BaseResponse(object):
1451
+ """ Storage class for a response body as well as headers and cookies.
1452
+
1453
+ This class does support dict-like case-insensitive item-access to
1454
+ headers, but is NOT a dict. Most notably, iterating over a response
1455
+ yields parts of the body and not the headers.
1456
+
1457
+ :param body: The response body as one of the supported types.
1458
+ :param status: Either an HTTP status code (e.g. 200) or a status line
1459
+ including the reason phrase (e.g. '200 OK').
1460
+ :param headers: A dictionary or a list of name-value pairs.
1461
+
1462
+ Additional keyword arguments are added to the list of headers.
1463
+ Underscores in the header name are replaced with dashes.
1464
+ """
1465
+
1466
+ default_status = 200
1467
+ default_content_type = 'text/html; charset=UTF-8'
1468
+
1469
+ # Header blacklist for specific response codes
1470
+ # (rfc2616 section 10.2.3 and 10.3.5)
1471
+ bad_headers = {
1472
+ 204: set(('Content-Type',)),
1473
+ 304: set(('Allow', 'Content-Encoding', 'Content-Language',
1474
+ 'Content-Length', 'Content-Range', 'Content-Type',
1475
+ 'Content-Md5', 'Last-Modified'))}
1476
+
1477
+ def __init__(self, body='', status=None, headers=None, **more_headers):
1478
+ self._cookies = None
1479
+ self._headers = {}
1480
+ self.body = body
1481
+ self.status = status or self.default_status
1482
+ if headers:
1483
+ if isinstance(headers, dict):
1484
+ headers = headers.items()
1485
+ for name, value in headers:
1486
+ self.add_header(name, value)
1487
+ if more_headers:
1488
+ for name, value in more_headers.items():
1489
+ self.add_header(name, value)
1490
+
1491
+ def copy(self, cls=None):
1492
+ ''' Returns a copy of self. '''
1493
+ cls = cls or BaseResponse
1494
+ assert issubclass(cls, BaseResponse)
1495
+ copy = cls()
1496
+ copy.status = self.status
1497
+ copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
1498
+ if self._cookies:
1499
+ copy._cookies = SimpleCookie()
1500
+ copy._cookies.load(self._cookies.output(header=''))
1501
+ return copy
1502
+
1503
+ def __iter__(self):
1504
+ return iter(self.body)
1505
+
1506
+ def close(self):
1507
+ if hasattr(self.body, 'close'):
1508
+ self.body.close()
1509
+
1510
+ @property
1511
+ def status_line(self):
1512
+ ''' The HTTP status line as a string (e.g. ``404 Not Found``).'''
1513
+ return self._status_line
1514
+
1515
+ @property
1516
+ def status_code(self):
1517
+ ''' The HTTP status code as an integer (e.g. 404).'''
1518
+ return self._status_code
1519
+
1520
+ def _set_status(self, status):
1521
+ if isinstance(status, int):
1522
+ code, status = status, _HTTP_STATUS_LINES.get(status)
1523
+ elif ' ' in status:
1524
+ status = status.strip()
1525
+ code = int(status.split()[0])
1526
+ else:
1527
+ raise ValueError('String status line without a reason phrase.')
1528
+ if not 100 <= code <= 999: raise ValueError('Status code out of range.')
1529
+ self._status_code = code
1530
+ self._status_line = str(status or ('%d Unknown' % code))
1531
+
1532
+ def _get_status(self):
1533
+ return self._status_line
1534
+
1535
+ status = property(_get_status, _set_status, None,
1536
+ ''' A writeable property to change the HTTP response status. It accepts
1537
+ either a numeric code (100-999) or a string with a custom reason
1538
+ phrase (e.g. "404 Brain not found"). Both :data:`status_line` and
1539
+ :data:`status_code` are updated accordingly. The return value is
1540
+ always a status string. ''')
1541
+ del _get_status, _set_status
1542
+
1543
+ @property
1544
+ def headers(self):
1545
+ ''' An instance of :class:`HeaderDict`, a case-insensitive dict-like
1546
+ view on the response headers. '''
1547
+ hdict = HeaderDict()
1548
+ hdict.dict = self._headers
1549
+ return hdict
1550
+
1551
+ def __contains__(self, name): return _hkey(name) in self._headers
1552
+ def __delitem__(self, name): del self._headers[_hkey(name)]
1553
+ def __getitem__(self, name): return self._headers[_hkey(name)][-1]
1554
+ def __setitem__(self, name, value): self._headers[_hkey(name)] = [_hval(value)]
1555
+
1556
+ def get_header(self, name, default=None):
1557
+ ''' Return the value of a previously defined header. If there is no
1558
+ header with that name, return a default value. '''
1559
+ return self._headers.get(_hkey(name), [default])[-1]
1560
+
1561
+ def set_header(self, name, value):
1562
+ ''' Create a new response header, replacing any previously defined
1563
+ headers with the same name. '''
1564
+ self._headers[_hkey(name)] = [_hval(value)]
1565
+
1566
+ def add_header(self, name, value):
1567
+ ''' Add an additional response header, not removing duplicates. '''
1568
+ self._headers.setdefault(_hkey(name), []).append(_hval(value))
1569
+
1570
+ def iter_headers(self):
1571
+ ''' Yield (header, value) tuples, skipping headers that are not
1572
+ allowed with the current response status code. '''
1573
+ return self.headerlist
1574
+
1575
+ @property
1576
+ def headerlist(self):
1577
+ """ WSGI conform list of (header, value) tuples. """
1578
+ out = []
1579
+ headers = list(self._headers.items())
1580
+ if 'Content-Type' not in self._headers:
1581
+ headers.append(('Content-Type', [self.default_content_type]))
1582
+ if self._status_code in self.bad_headers:
1583
+ bad_headers = self.bad_headers[self._status_code]
1584
+ headers = [h for h in headers if h[0] not in bad_headers]
1585
+ out += [(name, val) for (name, vals) in headers for val in vals]
1586
+ if self._cookies:
1587
+ for c in self._cookies.values():
1588
+ out.append(('Set-Cookie', _hval(c.OutputString())))
1589
+ if py3k:
1590
+ out = [(k, v.encode('utf8').decode('latin1')) for (k, v) in out]
1591
+ return out
1592
+
1593
+ content_type = HeaderProperty('Content-Type')
1594
+ content_length = HeaderProperty('Content-Length', reader=int)
1595
+ expires = HeaderProperty('Expires',
1596
+ reader=lambda x: datetime.utcfromtimestamp(parse_date(x)),
1597
+ writer=lambda x: http_date(x))
1598
+
1599
+ @property
1600
+ def charset(self, default='UTF-8'):
1601
+ """ Return the charset specified in the content-type header (default: utf8). """
1602
+ if 'charset=' in self.content_type:
1603
+ return self.content_type.split('charset=')[-1].split(';')[0].strip()
1604
+ return default
1605
+
1606
+ def set_cookie(self, name, value, secret=None, **options):
1607
+ ''' Create a new cookie or replace an old one. If the `secret` parameter is
1608
+ set, create a `Signed Cookie` (described below).
1609
+
1610
+ :param name: the name of the cookie.
1611
+ :param value: the value of the cookie.
1612
+ :param secret: a signature key required for signed cookies.
1613
+
1614
+ Additionally, this method accepts all RFC 2109 attributes that are
1615
+ supported by :class:`cookie.Morsel`, including:
1616
+
1617
+ :param max_age: maximum age in seconds. (default: None)
1618
+ :param expires: a datetime object or UNIX timestamp. (default: None)
1619
+ :param domain: the domain that is allowed to read the cookie.
1620
+ (default: current domain)
1621
+ :param path: limits the cookie to a given path (default: current path)
1622
+ :param secure: limit the cookie to HTTPS connections (default: off).
1623
+ :param httponly: prevents client-side javascript to read this cookie
1624
+ (default: off, requires Python 2.6 or newer).
1625
+
1626
+ If neither `expires` nor `max_age` is set (default), the cookie will
1627
+ expire at the end of the browser session (as soon as the browser
1628
+ window is closed).
1629
+
1630
+ Signed cookies may store any pickle-able object and are
1631
+ cryptographically signed to prevent manipulation. Keep in mind that
1632
+ cookies are limited to 4kb in most browsers.
1633
+
1634
+ Warning: Signed cookies are not encrypted (the client can still see
1635
+ the content) and not copy-protected (the client can restore an old
1636
+ cookie). The main intention is to make pickling and unpickling
1637
+ save, not to store secret information at client side.
1638
+ '''
1639
+ if not self._cookies:
1640
+ self._cookies = SimpleCookie()
1641
+
1642
+ if secret:
1643
+ value = touni(cookie_encode((name, value), secret))
1644
+ elif not isinstance(value, basestring):
1645
+ raise TypeError('Secret key missing for non-string Cookie.')
1646
+
1647
+ if len(value) > 4096: raise ValueError('Cookie value to long.')
1648
+ self._cookies[name] = value
1649
+
1650
+ for key, value in options.items():
1651
+ if key == 'max_age':
1652
+ if isinstance(value, timedelta):
1653
+ value = value.seconds + value.days * 24 * 3600
1654
+ if key == 'expires':
1655
+ if isinstance(value, (datedate, datetime)):
1656
+ value = value.timetuple()
1657
+ elif isinstance(value, (int, float)):
1658
+ value = time.gmtime(value)
1659
+ value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
1660
+ self._cookies[name][key.replace('_', '-')] = value
1661
+
1662
+ def delete_cookie(self, key, **kwargs):
1663
+ ''' Delete a cookie. Be sure to use the same `domain` and `path`
1664
+ settings as used to create the cookie. '''
1665
+ kwargs['max_age'] = -1
1666
+ kwargs['expires'] = 0
1667
+ self.set_cookie(key, '', **kwargs)
1668
+
1669
+ def __repr__(self):
1670
+ out = ''
1671
+ for name, value in self.headerlist:
1672
+ out += '%s: %s\n' % (name.title(), value.strip())
1673
+ return out
1674
+
1675
+
1676
+ def local_property(name=None):
1677
+ if name: depr('local_property() is deprecated and will be removed.') #0.12
1678
+ ls = threading.local()
1679
+ def fget(self):
1680
+ try: return ls.var
1681
+ except AttributeError:
1682
+ raise RuntimeError("Request context not initialized.")
1683
+ def fset(self, value): ls.var = value
1684
+ def fdel(self): del ls.var
1685
+ return property(fget, fset, fdel, 'Thread-local property')
1686
+
1687
+
1688
+ class LocalRequest(BaseRequest):
1689
+ ''' A thread-local subclass of :class:`BaseRequest` with a different
1690
+ set of attributes for each thread. There is usually only one global
1691
+ instance of this class (:data:`request`). If accessed during a
1692
+ request/response cycle, this instance always refers to the *current*
1693
+ request (even on a multithreaded server). '''
1694
+ bind = BaseRequest.__init__
1695
+ environ = local_property()
1696
+
1697
+
1698
+ class LocalResponse(BaseResponse):
1699
+ ''' A thread-local subclass of :class:`BaseResponse` with a different
1700
+ set of attributes for each thread. There is usually only one global
1701
+ instance of this class (:data:`response`). Its attributes are used
1702
+ to build the HTTP response at the end of the request/response cycle.
1703
+ '''
1704
+ bind = BaseResponse.__init__
1705
+ _status_line = local_property()
1706
+ _status_code = local_property()
1707
+ _cookies = local_property()
1708
+ _headers = local_property()
1709
+ body = local_property()
1710
+
1711
+
1712
+ Request = BaseRequest
1713
+ Response = BaseResponse
1714
+
1715
+
1716
+ class HTTPResponse(Response, BottleException):
1717
+ def __init__(self, body='', status=None, headers=None, **more_headers):
1718
+ super(HTTPResponse, self).__init__(body, status, headers, **more_headers)
1719
+
1720
+ def apply(self, response):
1721
+ response._status_code = self._status_code
1722
+ response._status_line = self._status_line
1723
+ response._headers = self._headers
1724
+ response._cookies = self._cookies
1725
+ response.body = self.body
1726
+
1727
+
1728
+ class HTTPError(HTTPResponse):
1729
+ default_status = 500
1730
+ def __init__(self, status=None, body=None, exception=None, traceback=None,
1731
+ **options):
1732
+ self.exception = exception
1733
+ self.traceback = traceback
1734
+ super(HTTPError, self).__init__(body, status, **options)
1735
+
1736
+
1737
+
1738
+
1739
+
1740
+ ###############################################################################
1741
+ # Plugins ######################################################################
1742
+ ###############################################################################
1743
+
1744
+ class PluginError(BottleException): pass
1745
+
1746
+
1747
+ class JSONPlugin(object):
1748
+ name = 'json'
1749
+ api = 2
1750
+
1751
+ def __init__(self, json_dumps=json_dumps):
1752
+ self.json_dumps = json_dumps
1753
+
1754
+ def apply(self, callback, route):
1755
+ dumps = self.json_dumps
1756
+ if not dumps: return callback
1757
+ def wrapper(*a, **ka):
1758
+ try:
1759
+ rv = callback(*a, **ka)
1760
+ except HTTPResponse:
1761
+ rv = _e()
1762
+
1763
+ if isinstance(rv, dict):
1764
+ #Attempt to serialize, raises exception on failure
1765
+ json_response = dumps(rv)
1766
+ #Set content type only if serialization succesful
1767
+ response.content_type = 'application/json'
1768
+ return json_response
1769
+ elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
1770
+ rv.body = dumps(rv.body)
1771
+ rv.content_type = 'application/json'
1772
+ return rv
1773
+
1774
+ return wrapper
1775
+
1776
+
1777
+ class TemplatePlugin(object):
1778
+ ''' This plugin applies the :func:`view` decorator to all routes with a
1779
+ `template` config parameter. If the parameter is a tuple, the second
1780
+ element must be a dict with additional options (e.g. `template_engine`)
1781
+ or default variables for the template. '''
1782
+ name = 'template'
1783
+ api = 2
1784
+
1785
+ def apply(self, callback, route):
1786
+ conf = route.config.get('template')
1787
+ if isinstance(conf, (tuple, list)) and len(conf) == 2:
1788
+ return view(conf[0], **conf[1])(callback)
1789
+ elif isinstance(conf, str):
1790
+ return view(conf)(callback)
1791
+ else:
1792
+ return callback
1793
+
1794
+
1795
+ #: Not a plugin, but part of the plugin API. TODO: Find a better place.
1796
+ class _ImportRedirect(object):
1797
+ def __init__(self, name, impmask):
1798
+ ''' Create a virtual package that redirects imports (see PEP 302). '''
1799
+ self.name = name
1800
+ self.impmask = impmask
1801
+ self.module = sys.modules.setdefault(name, new_module(name))
1802
+ self.module.__dict__.update({'__file__': __file__, '__path__': [],
1803
+ '__all__': [], '__loader__': self})
1804
+ sys.meta_path.append(self)
1805
+
1806
+ def find_module(self, fullname, path=None):
1807
+ if '.' not in fullname: return
1808
+ packname = fullname.rsplit('.', 1)[0]
1809
+ if packname != self.name: return
1810
+ return self
1811
+
1812
+ def load_module(self, fullname):
1813
+ if fullname in sys.modules: return sys.modules[fullname]
1814
+ modname = fullname.rsplit('.', 1)[1]
1815
+ realname = self.impmask % modname
1816
+ __import__(realname)
1817
+ module = sys.modules[fullname] = sys.modules[realname]
1818
+ setattr(self.module, modname, module)
1819
+ module.__loader__ = self
1820
+ return module
1821
+
1822
+
1823
+
1824
+
1825
+
1826
+
1827
+ ###############################################################################
1828
+ # Common Utilities #############################################################
1829
+ ###############################################################################
1830
+
1831
+
1832
+ class MultiDict(DictMixin):
1833
+ """ This dict stores multiple values per key, but behaves exactly like a
1834
+ normal dict in that it returns only the newest value for any given key.
1835
+ There are special methods available to access the full list of values.
1836
+ """
1837
+
1838
+ def __init__(self, *a, **k):
1839
+ self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items())
1840
+
1841
+ def __len__(self): return len(self.dict)
1842
+ def __iter__(self): return iter(self.dict)
1843
+ def __contains__(self, key): return key in self.dict
1844
+ def __delitem__(self, key): del self.dict[key]
1845
+ def __getitem__(self, key): return self.dict[key][-1]
1846
+ def __setitem__(self, key, value): self.append(key, value)
1847
+ def keys(self): return self.dict.keys()
1848
+
1849
+ if py3k:
1850
+ def values(self): return (v[-1] for v in self.dict.values())
1851
+ def items(self): return ((k, v[-1]) for k, v in self.dict.items())
1852
+ def allitems(self):
1853
+ return ((k, v) for k, vl in self.dict.items() for v in vl)
1854
+ iterkeys = keys
1855
+ itervalues = values
1856
+ iteritems = items
1857
+ iterallitems = allitems
1858
+
1859
+ else:
1860
+ def values(self): return [v[-1] for v in self.dict.values()]
1861
+ def items(self): return [(k, v[-1]) for k, v in self.dict.items()]
1862
+ def iterkeys(self): return self.dict.iterkeys()
1863
+ def itervalues(self): return (v[-1] for v in self.dict.itervalues())
1864
+ def iteritems(self):
1865
+ return ((k, v[-1]) for k, v in self.dict.iteritems())
1866
+ def iterallitems(self):
1867
+ return ((k, v) for k, vl in self.dict.iteritems() for v in vl)
1868
+ def allitems(self):
1869
+ return [(k, v) for k, vl in self.dict.iteritems() for v in vl]
1870
+
1871
+ def get(self, key, default=None, index=-1, type=None):
1872
+ ''' Return the most recent value for a key.
1873
+
1874
+ :param default: The default value to be returned if the key is not
1875
+ present or the type conversion fails.
1876
+ :param index: An index for the list of available values.
1877
+ :param type: If defined, this callable is used to cast the value
1878
+ into a specific type. Exception are suppressed and result in
1879
+ the default value to be returned.
1880
+ '''
1881
+ try:
1882
+ val = self.dict[key][index]
1883
+ return type(val) if type else val
1884
+ except Exception:
1885
+ pass
1886
+ return default
1887
+
1888
+ def append(self, key, value):
1889
+ ''' Add a new value to the list of values for this key. '''
1890
+ self.dict.setdefault(key, []).append(value)
1891
+
1892
+ def replace(self, key, value):
1893
+ ''' Replace the list of values with a single value. '''
1894
+ self.dict[key] = [value]
1895
+
1896
+ def getall(self, key):
1897
+ ''' Return a (possibly empty) list of values for a key. '''
1898
+ return self.dict.get(key) or []
1899
+
1900
+ #: Aliases for WTForms to mimic other multi-dict APIs (Django)
1901
+ getone = get
1902
+ getlist = getall
1903
+
1904
+
1905
+ class FormsDict(MultiDict):
1906
+ ''' This :class:`MultiDict` subclass is used to store request form data.
1907
+ Additionally to the normal dict-like item access methods (which return
1908
+ unmodified data as native strings), this container also supports
1909
+ attribute-like access to its values. Attributes are automatically de-
1910
+ or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing
1911
+ attributes default to an empty string. '''
1912
+
1913
+ #: Encoding used for attribute values.
1914
+ input_encoding = 'utf8'
1915
+ #: If true (default), unicode strings are first encoded with `latin1`
1916
+ #: and then decoded to match :attr:`input_encoding`.
1917
+ recode_unicode = True
1918
+
1919
+ def _fix(self, s, encoding=None):
1920
+ if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI
1921
+ return s.encode('latin1').decode(encoding or self.input_encoding)
1922
+ elif isinstance(s, bytes): # Python 2 WSGI
1923
+ return s.decode(encoding or self.input_encoding)
1924
+ else:
1925
+ return s
1926
+
1927
+ def decode(self, encoding=None):
1928
+ ''' Returns a copy with all keys and values de- or recoded to match
1929
+ :attr:`input_encoding`. Some libraries (e.g. WTForms) want a
1930
+ unicode dictionary. '''
1931
+ copy = FormsDict()
1932
+ enc = copy.input_encoding = encoding or self.input_encoding
1933
+ copy.recode_unicode = False
1934
+ for key, value in self.allitems():
1935
+ copy.append(self._fix(key, enc), self._fix(value, enc))
1936
+ return copy
1937
+
1938
+ def getunicode(self, name, default=None, encoding=None):
1939
+ ''' Return the value as a unicode string, or the default. '''
1940
+ try:
1941
+ return self._fix(self[name], encoding)
1942
+ except (UnicodeError, KeyError):
1943
+ return default
1944
+
1945
+ def __getattr__(self, name, default=unicode()):
1946
+ # Without this guard, pickle generates a cryptic TypeError:
1947
+ if name.startswith('__') and name.endswith('__'):
1948
+ return super(FormsDict, self).__getattr__(name)
1949
+ return self.getunicode(name, default=default)
1950
+
1951
+ class HeaderDict(MultiDict):
1952
+ """ A case-insensitive version of :class:`MultiDict` that defaults to
1953
+ replace the old value instead of appending it. """
1954
+
1955
+ def __init__(self, *a, **ka):
1956
+ self.dict = {}
1957
+ if a or ka: self.update(*a, **ka)
1958
+
1959
+ def __contains__(self, key): return _hkey(key) in self.dict
1960
+ def __delitem__(self, key): del self.dict[_hkey(key)]
1961
+ def __getitem__(self, key): return self.dict[_hkey(key)][-1]
1962
+ def __setitem__(self, key, value): self.dict[_hkey(key)] = [_hval(value)]
1963
+ def append(self, key, value): self.dict.setdefault(_hkey(key), []).append(_hval(value))
1964
+ def replace(self, key, value): self.dict[_hkey(key)] = [_hval(value)]
1965
+ def getall(self, key): return self.dict.get(_hkey(key)) or []
1966
+ def get(self, key, default=None, index=-1):
1967
+ return MultiDict.get(self, _hkey(key), default, index)
1968
+ def filter(self, names):
1969
+ for name in (_hkey(n) for n in names):
1970
+ if name in self.dict:
1971
+ del self.dict[name]
1972
+
1973
+
1974
+ class WSGIHeaderDict(DictMixin):
1975
+ ''' This dict-like class wraps a WSGI environ dict and provides convenient
1976
+ access to HTTP_* fields. Keys and values are native strings
1977
+ (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI
1978
+ environment contains non-native string values, these are de- or encoded
1979
+ using a lossless 'latin1' character set.
1980
+
1981
+ The API will remain stable even on changes to the relevant PEPs.
1982
+ Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one
1983
+ that uses non-native strings.)
1984
+ '''
1985
+ #: List of keys that do not have a ``HTTP_`` prefix.
1986
+ cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH')
1987
+
1988
+ def __init__(self, environ):
1989
+ self.environ = environ
1990
+
1991
+ def _ekey(self, key):
1992
+ ''' Translate header field name to CGI/WSGI environ key. '''
1993
+ key = key.replace('-','_').upper()
1994
+ if key in self.cgikeys:
1995
+ return key
1996
+ return 'HTTP_' + key
1997
+
1998
+ def raw(self, key, default=None):
1999
+ ''' Return the header value as is (may be bytes or unicode). '''
2000
+ return self.environ.get(self._ekey(key), default)
2001
+
2002
+ def __getitem__(self, key):
2003
+ return tonat(self.environ[self._ekey(key)], 'latin1')
2004
+
2005
+ def __setitem__(self, key, value):
2006
+ raise TypeError("%s is read-only." % self.__class__)
2007
+
2008
+ def __delitem__(self, key):
2009
+ raise TypeError("%s is read-only." % self.__class__)
2010
+
2011
+ def __iter__(self):
2012
+ for key in self.environ:
2013
+ if key[:5] == 'HTTP_':
2014
+ yield key[5:].replace('_', '-').title()
2015
+ elif key in self.cgikeys:
2016
+ yield key.replace('_', '-').title()
2017
+
2018
+ def keys(self): return [x for x in self]
2019
+ def __len__(self): return len(self.keys())
2020
+ def __contains__(self, key): return self._ekey(key) in self.environ
2021
+
2022
+
2023
+
2024
+ class ConfigDict(dict):
2025
+ ''' A dict-like configuration storage with additional support for
2026
+ namespaces, validators, meta-data, on_change listeners and more.
2027
+
2028
+ This storage is optimized for fast read access. Retrieving a key
2029
+ or using non-altering dict methods (e.g. `dict.get()`) has no overhead
2030
+ compared to a native dict.
2031
+ '''
2032
+ __slots__ = ('_meta', '_on_change')
2033
+
2034
+ class Namespace(DictMixin):
2035
+
2036
+ def __init__(self, config, namespace):
2037
+ self._config = config
2038
+ self._prefix = namespace
2039
+
2040
+ def __getitem__(self, key):
2041
+ depr('Accessing namespaces as dicts is discouraged. '
2042
+ 'Only use flat item access: '
2043
+ 'cfg["names"]["pace"]["key"] -> cfg["name.space.key"]') #0.12
2044
+ return self._config[self._prefix + '.' + key]
2045
+
2046
+ def __setitem__(self, key, value):
2047
+ self._config[self._prefix + '.' + key] = value
2048
+
2049
+ def __delitem__(self, key):
2050
+ del self._config[self._prefix + '.' + key]
2051
+
2052
+ def __iter__(self):
2053
+ ns_prefix = self._prefix + '.'
2054
+ for key in self._config:
2055
+ ns, dot, name = key.rpartition('.')
2056
+ if ns == self._prefix and name:
2057
+ yield name
2058
+
2059
+ def keys(self): return [x for x in self]
2060
+ def __len__(self): return len(self.keys())
2061
+ def __contains__(self, key): return self._prefix + '.' + key in self._config
2062
+ def __repr__(self): return '<Config.Namespace %s.*>' % self._prefix
2063
+ def __str__(self): return '<Config.Namespace %s.*>' % self._prefix
2064
+
2065
+ # Deprecated ConfigDict features
2066
+ def __getattr__(self, key):
2067
+ depr('Attribute access is deprecated.') #0.12
2068
+ if key not in self and key[0].isupper():
2069
+ self[key] = ConfigDict.Namespace(self._config, self._prefix + '.' + key)
2070
+ if key not in self and key.startswith('__'):
2071
+ raise AttributeError(key)
2072
+ return self.get(key)
2073
+
2074
+ def __setattr__(self, key, value):
2075
+ if key in ('_config', '_prefix'):
2076
+ self.__dict__[key] = value
2077
+ return
2078
+ depr('Attribute assignment is deprecated.') #0.12
2079
+ if hasattr(DictMixin, key):
2080
+ raise AttributeError('Read-only attribute.')
2081
+ if key in self and self[key] and isinstance(self[key], self.__class__):
2082
+ raise AttributeError('Non-empty namespace attribute.')
2083
+ self[key] = value
2084
+
2085
+ def __delattr__(self, key):
2086
+ if key in self:
2087
+ val = self.pop(key)
2088
+ if isinstance(val, self.__class__):
2089
+ prefix = key + '.'
2090
+ for key in self:
2091
+ if key.startswith(prefix):
2092
+ del self[prefix+key]
2093
+
2094
+ def __call__(self, *a, **ka):
2095
+ depr('Calling ConfDict is deprecated. Use the update() method.') #0.12
2096
+ self.update(*a, **ka)
2097
+ return self
2098
+
2099
+ def __init__(self, *a, **ka):
2100
+ self._meta = {}
2101
+ self._on_change = lambda name, value: None
2102
+ if a or ka:
2103
+ depr('Constructor does no longer accept parameters.') #0.12
2104
+ self.update(*a, **ka)
2105
+
2106
+ def load_config(self, filename):
2107
+ ''' Load values from an *.ini style config file.
2108
+
2109
+ If the config file contains sections, their names are used as
2110
+ namespaces for the values within. The two special sections
2111
+ ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
2112
+ '''
2113
+ conf = ConfigParser()
2114
+ conf.read(filename)
2115
+ for section in conf.sections():
2116
+ for key, value in conf.items(section):
2117
+ if section not in ('DEFAULT', 'bottle'):
2118
+ key = section + '.' + key
2119
+ self[key] = value
2120
+ return self
2121
+
2122
+ def load_dict(self, source, namespace='', make_namespaces=False):
2123
+ ''' Import values from a dictionary structure. Nesting can be used to
2124
+ represent namespaces.
2125
+
2126
+ >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}})
2127
+ {'name.space.key': 'value'}
2128
+ '''
2129
+ stack = [(namespace, source)]
2130
+ while stack:
2131
+ prefix, source = stack.pop()
2132
+ if not isinstance(source, dict):
2133
+ raise TypeError('Source is not a dict (r)' % type(key))
2134
+ for key, value in source.items():
2135
+ if not isinstance(key, basestring):
2136
+ raise TypeError('Key is not a string (%r)' % type(key))
2137
+ full_key = prefix + '.' + key if prefix else key
2138
+ if isinstance(value, dict):
2139
+ stack.append((full_key, value))
2140
+ if make_namespaces:
2141
+ self[full_key] = self.Namespace(self, full_key)
2142
+ else:
2143
+ self[full_key] = value
2144
+ return self
2145
+
2146
+ def update(self, *a, **ka):
2147
+ ''' If the first parameter is a string, all keys are prefixed with this
2148
+ namespace. Apart from that it works just as the usual dict.update().
2149
+ Example: ``update('some.namespace', key='value')`` '''
2150
+ prefix = ''
2151
+ if a and isinstance(a[0], basestring):
2152
+ prefix = a[0].strip('.') + '.'
2153
+ a = a[1:]
2154
+ for key, value in dict(*a, **ka).items():
2155
+ self[prefix+key] = value
2156
+
2157
+ def setdefault(self, key, value):
2158
+ if key not in self:
2159
+ self[key] = value
2160
+ return self[key]
2161
+
2162
+ def __setitem__(self, key, value):
2163
+ if not isinstance(key, basestring):
2164
+ raise TypeError('Key has type %r (not a string)' % type(key))
2165
+
2166
+ value = self.meta_get(key, 'filter', lambda x: x)(value)
2167
+ if key in self and self[key] is value:
2168
+ return
2169
+ self._on_change(key, value)
2170
+ dict.__setitem__(self, key, value)
2171
+
2172
+ def __delitem__(self, key):
2173
+ dict.__delitem__(self, key)
2174
+
2175
+ def clear(self):
2176
+ for key in self:
2177
+ del self[key]
2178
+
2179
+ def meta_get(self, key, metafield, default=None):
2180
+ ''' Return the value of a meta field for a key. '''
2181
+ return self._meta.get(key, {}).get(metafield, default)
2182
+
2183
+ def meta_set(self, key, metafield, value):
2184
+ ''' Set the meta field for a key to a new value. This triggers the
2185
+ on-change handler for existing keys. '''
2186
+ self._meta.setdefault(key, {})[metafield] = value
2187
+ if key in self:
2188
+ self[key] = self[key]
2189
+
2190
+ def meta_list(self, key):
2191
+ ''' Return an iterable of meta field names defined for a key. '''
2192
+ return self._meta.get(key, {}).keys()
2193
+
2194
+ # Deprecated ConfigDict features
2195
+ def __getattr__(self, key):
2196
+ depr('Attribute access is deprecated.') #0.12
2197
+ if key not in self and key[0].isupper():
2198
+ self[key] = self.Namespace(self, key)
2199
+ if key not in self and key.startswith('__'):
2200
+ raise AttributeError(key)
2201
+ return self.get(key)
2202
+
2203
+ def __setattr__(self, key, value):
2204
+ if key in self.__slots__:
2205
+ return dict.__setattr__(self, key, value)
2206
+ depr('Attribute assignment is deprecated.') #0.12
2207
+ if hasattr(dict, key):
2208
+ raise AttributeError('Read-only attribute.')
2209
+ if key in self and self[key] and isinstance(self[key], self.Namespace):
2210
+ raise AttributeError('Non-empty namespace attribute.')
2211
+ self[key] = value
2212
+
2213
+ def __delattr__(self, key):
2214
+ if key in self:
2215
+ val = self.pop(key)
2216
+ if isinstance(val, self.Namespace):
2217
+ prefix = key + '.'
2218
+ for key in self:
2219
+ if key.startswith(prefix):
2220
+ del self[prefix+key]
2221
+
2222
+ def __call__(self, *a, **ka):
2223
+ depr('Calling ConfDict is deprecated. Use the update() method.') #0.12
2224
+ self.update(*a, **ka)
2225
+ return self
2226
+
2227
+
2228
+
2229
+ class AppStack(list):
2230
+ """ A stack-like list. Calling it returns the head of the stack. """
2231
+
2232
+ def __call__(self):
2233
+ """ Return the current default application. """
2234
+ return self[-1]
2235
+
2236
+ def push(self, value=None):
2237
+ """ Add a new :class:`Bottle` instance to the stack """
2238
+ if not isinstance(value, Bottle):
2239
+ value = Bottle()
2240
+ self.append(value)
2241
+ return value
2242
+
2243
+
2244
+ class WSGIFileWrapper(object):
2245
+
2246
+ def __init__(self, fp, buffer_size=1024*64):
2247
+ self.fp, self.buffer_size = fp, buffer_size
2248
+ for attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'):
2249
+ if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))
2250
+
2251
+ def __iter__(self):
2252
+ buff, read = self.buffer_size, self.read
2253
+ while True:
2254
+ part = read(buff)
2255
+ if not part: return
2256
+ yield part
2257
+
2258
+
2259
+ class _closeiter(object):
2260
+ ''' This only exists to be able to attach a .close method to iterators that
2261
+ do not support attribute assignment (most of itertools). '''
2262
+
2263
+ def __init__(self, iterator, close=None):
2264
+ self.iterator = iterator
2265
+ self.close_callbacks = makelist(close)
2266
+
2267
+ def __iter__(self):
2268
+ return iter(self.iterator)
2269
+
2270
+ def close(self):
2271
+ for func in self.close_callbacks:
2272
+ func()
2273
+
2274
+
2275
+ class ResourceManager(object):
2276
+ ''' This class manages a list of search paths and helps to find and open
2277
+ application-bound resources (files).
2278
+
2279
+ :param base: default value for :meth:`add_path` calls.
2280
+ :param opener: callable used to open resources.
2281
+ :param cachemode: controls which lookups are cached. One of 'all',
2282
+ 'found' or 'none'.
2283
+ '''
2284
+
2285
+ def __init__(self, base='./', opener=open, cachemode='all'):
2286
+ self.opener = open
2287
+ self.base = base
2288
+ self.cachemode = cachemode
2289
+
2290
+ #: A list of search paths. See :meth:`add_path` for details.
2291
+ self.path = []
2292
+ #: A cache for resolved paths. ``res.cache.clear()`` clears the cache.
2293
+ self.cache = {}
2294
+
2295
+ def add_path(self, path, base=None, index=None, create=False):
2296
+ ''' Add a new path to the list of search paths. Return False if the
2297
+ path does not exist.
2298
+
2299
+ :param path: The new search path. Relative paths are turned into
2300
+ an absolute and normalized form. If the path looks like a file
2301
+ (not ending in `/`), the filename is stripped off.
2302
+ :param base: Path used to absolutize relative search paths.
2303
+ Defaults to :attr:`base` which defaults to ``os.getcwd()``.
2304
+ :param index: Position within the list of search paths. Defaults
2305
+ to last index (appends to the list).
2306
+
2307
+ The `base` parameter makes it easy to reference files installed
2308
+ along with a python module or package::
2309
+
2310
+ res.add_path('./resources/', __file__)
2311
+ '''
2312
+ base = os.path.abspath(os.path.dirname(base or self.base))
2313
+ path = os.path.abspath(os.path.join(base, os.path.dirname(path)))
2314
+ path += os.sep
2315
+ if path in self.path:
2316
+ self.path.remove(path)
2317
+ if create and not os.path.isdir(path):
2318
+ os.makedirs(path)
2319
+ if index is None:
2320
+ self.path.append(path)
2321
+ else:
2322
+ self.path.insert(index, path)
2323
+ self.cache.clear()
2324
+ return os.path.exists(path)
2325
+
2326
+ def __iter__(self):
2327
+ ''' Iterate over all existing files in all registered paths. '''
2328
+ search = self.path[:]
2329
+ while search:
2330
+ path = search.pop()
2331
+ if not os.path.isdir(path): continue
2332
+ for name in os.listdir(path):
2333
+ full = os.path.join(path, name)
2334
+ if os.path.isdir(full): search.append(full)
2335
+ else: yield full
2336
+
2337
+ def lookup(self, name):
2338
+ ''' Search for a resource and return an absolute file path, or `None`.
2339
+
2340
+ The :attr:`path` list is searched in order. The first match is
2341
+ returend. Symlinks are followed. The result is cached to speed up
2342
+ future lookups. '''
2343
+ if name not in self.cache or DEBUG:
2344
+ for path in self.path:
2345
+ fpath = os.path.join(path, name)
2346
+ if os.path.isfile(fpath):
2347
+ if self.cachemode in ('all', 'found'):
2348
+ self.cache[name] = fpath
2349
+ return fpath
2350
+ if self.cachemode == 'all':
2351
+ self.cache[name] = None
2352
+ return self.cache[name]
2353
+
2354
+ def open(self, name, mode='r', *args, **kwargs):
2355
+ ''' Find a resource and return a file object, or raise IOError. '''
2356
+ fname = self.lookup(name)
2357
+ if not fname: raise IOError("Resource %r not found." % name)
2358
+ return self.opener(fname, mode=mode, *args, **kwargs)
2359
+
2360
+
2361
+ class FileUpload(object):
2362
+
2363
+ def __init__(self, fileobj, name, filename, headers=None):
2364
+ ''' Wrapper for file uploads. '''
2365
+ #: Open file(-like) object (BytesIO buffer or temporary file)
2366
+ self.file = fileobj
2367
+ #: Name of the upload form field
2368
+ self.name = name
2369
+ #: Raw filename as sent by the client (may contain unsafe characters)
2370
+ self.raw_filename = filename
2371
+ #: A :class:`HeaderDict` with additional headers (e.g. content-type)
2372
+ self.headers = HeaderDict(headers) if headers else HeaderDict()
2373
+
2374
+ content_type = HeaderProperty('Content-Type')
2375
+ content_length = HeaderProperty('Content-Length', reader=int, default=-1)
2376
+
2377
+ def get_header(self, name, default=None):
2378
+ """ Return the value of a header within the mulripart part. """
2379
+ return self.headers.get(name, default)
2380
+
2381
+ @cached_property
2382
+ def filename(self):
2383
+ ''' Name of the file on the client file system, but normalized to ensure
2384
+ file system compatibility. An empty filename is returned as 'empty'.
2385
+
2386
+ Only ASCII letters, digits, dashes, underscores and dots are
2387
+ allowed in the final filename. Accents are removed, if possible.
2388
+ Whitespace is replaced by a single dash. Leading or tailing dots
2389
+ or dashes are removed. The filename is limited to 255 characters.
2390
+ '''
2391
+ fname = self.raw_filename
2392
+ if not isinstance(fname, unicode):
2393
+ fname = fname.decode('utf8', 'ignore')
2394
+ fname = normalize('NFKD', fname).encode('ASCII', 'ignore').decode('ASCII')
2395
+ fname = os.path.basename(fname.replace('\\', os.path.sep))
2396
+ fname = re.sub(r'[^a-zA-Z0-9-_.\s]', '', fname).strip()
2397
+ fname = re.sub(r'[-\s]+', '-', fname).strip('.-')
2398
+ return fname[:255] or 'empty'
2399
+
2400
+ def _copy_file(self, fp, chunk_size=2**16):
2401
+ read, write, offset = self.file.read, fp.write, self.file.tell()
2402
+ while 1:
2403
+ buf = read(chunk_size)
2404
+ if not buf: break
2405
+ write(buf)
2406
+ self.file.seek(offset)
2407
+
2408
+ def save(self, destination, overwrite=False, chunk_size=2**16):
2409
+ ''' Save file to disk or copy its content to an open file(-like) object.
2410
+ If *destination* is a directory, :attr:`filename` is added to the
2411
+ path. Existing files are not overwritten by default (IOError).
2412
+
2413
+ :param destination: File path, directory or file(-like) object.
2414
+ :param overwrite: If True, replace existing files. (default: False)
2415
+ :param chunk_size: Bytes to read at a time. (default: 64kb)
2416
+ '''
2417
+ if isinstance(destination, basestring): # Except file-likes here
2418
+ if os.path.isdir(destination):
2419
+ destination = os.path.join(destination, self.filename)
2420
+ if not overwrite and os.path.exists(destination):
2421
+ raise IOError('File exists.')
2422
+ with open(destination, 'wb') as fp:
2423
+ self._copy_file(fp, chunk_size)
2424
+ else:
2425
+ self._copy_file(destination, chunk_size)
2426
+
2427
+
2428
+
2429
+
2430
+
2431
+
2432
+ ###############################################################################
2433
+ # Application Helper ###########################################################
2434
+ ###############################################################################
2435
+
2436
+
2437
+ def abort(code=500, text='Unknown Error.'):
2438
+ """ Aborts execution and causes a HTTP error. """
2439
+ raise HTTPError(code, text)
2440
+
2441
+
2442
+ def redirect(url, code=None):
2443
+ """ Aborts execution and causes a 303 or 302 redirect, depending on
2444
+ the HTTP protocol version. """
2445
+ if not code:
2446
+ code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
2447
+ res = response.copy(cls=HTTPResponse)
2448
+ res.status = code
2449
+ res.body = ""
2450
+ res.set_header('Location', urljoin(request.url, url))
2451
+ raise res
2452
+
2453
+
2454
+ def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
2455
+ ''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
2456
+ fp.seek(offset)
2457
+ while bytes > 0:
2458
+ part = fp.read(min(bytes, maxread))
2459
+ if not part: break
2460
+ bytes -= len(part)
2461
+ yield part
2462
+
2463
+
2464
+ def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8'):
2465
+ """ Open a file in a safe way and return :exc:`HTTPResponse` with status
2466
+ code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
2467
+ ``Content-Length`` and ``Last-Modified`` headers are set if possible.
2468
+ Special support for ``If-Modified-Since``, ``Range`` and ``HEAD``
2469
+ requests.
2470
+
2471
+ :param filename: Name or path of the file to send.
2472
+ :param root: Root path for file lookups. Should be an absolute directory
2473
+ path.
2474
+ :param mimetype: Defines the content-type header (default: guess from
2475
+ file extension)
2476
+ :param download: If True, ask the browser to open a `Save as...` dialog
2477
+ instead of opening the file with the associated program. You can
2478
+ specify a custom filename as a string. If not specified, the
2479
+ original filename is used (default: False).
2480
+ :param charset: The charset to use for files with a ``text/*``
2481
+ mime-type. (default: UTF-8)
2482
+ """
2483
+
2484
+ root = os.path.abspath(root) + os.sep
2485
+ filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
2486
+ headers = dict()
2487
+
2488
+ if not filename.startswith(root):
2489
+ return HTTPError(403, "Access denied.")
2490
+ if not os.path.exists(filename) or not os.path.isfile(filename):
2491
+ return HTTPError(404, "File does not exist.")
2492
+ if not os.access(filename, os.R_OK):
2493
+ return HTTPError(403, "You do not have permission to access this file.")
2494
+
2495
+ if mimetype == 'auto':
2496
+ mimetype, encoding = mimetypes.guess_type(filename)
2497
+ if encoding: headers['Content-Encoding'] = encoding
2498
+
2499
+ if mimetype:
2500
+ if mimetype[:5] == 'text/' and charset and 'charset' not in mimetype:
2501
+ mimetype += '; charset=%s' % charset
2502
+ headers['Content-Type'] = mimetype
2503
+
2504
+ if download:
2505
+ download = os.path.basename(filename if download == True else download)
2506
+ headers['Content-Disposition'] = 'attachment; filename="%s"' % download
2507
+
2508
+ stats = os.stat(filename)
2509
+ headers['Content-Length'] = clen = stats.st_size
2510
+ lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
2511
+ headers['Last-Modified'] = lm
2512
+
2513
+ ims = request.environ.get('HTTP_IF_MODIFIED_SINCE')
2514
+ if ims:
2515
+ ims = parse_date(ims.split(";")[0].strip())
2516
+ if ims is not None and ims >= int(stats.st_mtime):
2517
+ headers['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
2518
+ return HTTPResponse(status=304, **headers)
2519
+
2520
+ body = '' if request.method == 'HEAD' else open(filename, 'rb')
2521
+
2522
+ headers["Accept-Ranges"] = "bytes"
2523
+ ranges = request.environ.get('HTTP_RANGE')
2524
+ if 'HTTP_RANGE' in request.environ:
2525
+ ranges = list(parse_range_header(request.environ['HTTP_RANGE'], clen))
2526
+ if not ranges:
2527
+ return HTTPError(416, "Requested Range Not Satisfiable")
2528
+ offset, end = ranges[0]
2529
+ headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end-1, clen)
2530
+ headers["Content-Length"] = str(end-offset)
2531
+ if body: body = _file_iter_range(body, offset, end-offset)
2532
+ return HTTPResponse(body, status=206, **headers)
2533
+ return HTTPResponse(body, **headers)
2534
+
2535
+
2536
+
2537
+
2538
+
2539
+
2540
+ ###############################################################################
2541
+ # HTTP Utilities and MISC (TODO) ###############################################
2542
+ ###############################################################################
2543
+
2544
+
2545
+ def debug(mode=True):
2546
+ """ Change the debug level.
2547
+ There is only one debug level supported at the moment."""
2548
+ global DEBUG
2549
+ if mode: warnings.simplefilter('default')
2550
+ DEBUG = bool(mode)
2551
+
2552
+ def http_date(value):
2553
+ if isinstance(value, (datedate, datetime)):
2554
+ value = value.utctimetuple()
2555
+ elif isinstance(value, (int, float)):
2556
+ value = time.gmtime(value)
2557
+ if not isinstance(value, basestring):
2558
+ value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
2559
+ return value
2560
+
2561
+ def parse_date(ims):
2562
+ """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
2563
+ try:
2564
+ ts = email.utils.parsedate_tz(ims)
2565
+ return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
2566
+ except (TypeError, ValueError, IndexError, OverflowError):
2567
+ return None
2568
+
2569
+ def parse_auth(header):
2570
+ """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
2571
+ try:
2572
+ method, data = header.split(None, 1)
2573
+ if method.lower() == 'basic':
2574
+ user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
2575
+ return user, pwd
2576
+ except (KeyError, ValueError):
2577
+ return None
2578
+
2579
+ def parse_range_header(header, maxlen=0):
2580
+ ''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
2581
+ unsatisfiable ranges. The end index is non-inclusive.'''
2582
+ if not header or header[:6] != 'bytes=': return
2583
+ ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
2584
+ for start, end in ranges:
2585
+ try:
2586
+ if not start: # bytes=-100 -> last 100 bytes
2587
+ start, end = max(0, maxlen-int(end)), maxlen
2588
+ elif not end: # bytes=100- -> all but the first 99 bytes
2589
+ start, end = int(start), maxlen
2590
+ else: # bytes=100-200 -> bytes 100-200 (inclusive)
2591
+ start, end = int(start), min(int(end)+1, maxlen)
2592
+ if 0 <= start < end <= maxlen:
2593
+ yield start, end
2594
+ except ValueError:
2595
+ pass
2596
+
2597
+ def _parse_qsl(qs):
2598
+ r = []
2599
+ for pair in qs.split('&'):
2600
+ if not pair: continue
2601
+ nv = pair.split('=', 1)
2602
+ if len(nv) != 2: nv.append('')
2603
+ key = urlunquote(nv[0].replace('+', ' '))
2604
+ value = urlunquote(nv[1].replace('+', ' '))
2605
+ r.append((key, value))
2606
+ return r
2607
+
2608
+ def _lscmp(a, b):
2609
+ ''' Compares two strings in a cryptographically safe way:
2610
+ Runtime is not affected by length of common prefix. '''
2611
+ return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b)
2612
+
2613
+
2614
+ def cookie_encode(data, key):
2615
+ ''' Encode and sign a pickle-able object. Return a (byte) string '''
2616
+ msg = base64.b64encode(pickle.dumps(data, -1))
2617
+ sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())
2618
+ return tob('!') + sig + tob('?') + msg
2619
+
2620
+
2621
+ def cookie_decode(data, key):
2622
+ ''' Verify and decode an encoded string. Return an object or None.'''
2623
+ data = tob(data)
2624
+ if cookie_is_encoded(data):
2625
+ sig, msg = data.split(tob('?'), 1)
2626
+ if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())):
2627
+ return pickle.loads(base64.b64decode(msg))
2628
+ return None
2629
+
2630
+
2631
+ def cookie_is_encoded(data):
2632
+ ''' Return True if the argument looks like a encoded cookie.'''
2633
+ return bool(data.startswith(tob('!')) and tob('?') in data)
2634
+
2635
+
2636
+ def html_escape(string):
2637
+ ''' Escape HTML special characters ``&<>`` and quotes ``'"``. '''
2638
+ return string.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')\
2639
+ .replace('"','&quot;').replace("'",'&#039;')
2640
+
2641
+
2642
+ def html_quote(string):
2643
+ ''' Escape and quote a string to be used as an HTTP attribute.'''
2644
+ return '"%s"' % html_escape(string).replace('\n','&#10;')\
2645
+ .replace('\r','&#13;').replace('\t','&#9;')
2646
+
2647
+
2648
+ def yieldroutes(func):
2649
+ """ Return a generator for routes that match the signature (name, args)
2650
+ of the func parameter. This may yield more than one route if the function
2651
+ takes optional keyword arguments. The output is best described by example::
2652
+
2653
+ a() -> '/a'
2654
+ b(x, y) -> '/b/<x>/<y>'
2655
+ c(x, y=5) -> '/c/<x>' and '/c/<x>/<y>'
2656
+ d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>'
2657
+ """
2658
+ path = '/' + func.__name__.replace('__','/').lstrip('/')
2659
+ spec = getargspec(func)
2660
+ argc = len(spec[0]) - len(spec[3] or [])
2661
+ path += ('/<%s>' * argc) % tuple(spec[0][:argc])
2662
+ yield path
2663
+ for arg in spec[0][argc:]:
2664
+ path += '/<%s>' % arg
2665
+ yield path
2666
+
2667
+
2668
+ def path_shift(script_name, path_info, shift=1):
2669
+ ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
2670
+
2671
+ :return: The modified paths.
2672
+ :param script_name: The SCRIPT_NAME path.
2673
+ :param script_name: The PATH_INFO path.
2674
+ :param shift: The number of path fragments to shift. May be negative to
2675
+ change the shift direction. (default: 1)
2676
+ '''
2677
+ if shift == 0: return script_name, path_info
2678
+ pathlist = path_info.strip('/').split('/')
2679
+ scriptlist = script_name.strip('/').split('/')
2680
+ if pathlist and pathlist[0] == '': pathlist = []
2681
+ if scriptlist and scriptlist[0] == '': scriptlist = []
2682
+ if shift > 0 and shift <= len(pathlist):
2683
+ moved = pathlist[:shift]
2684
+ scriptlist = scriptlist + moved
2685
+ pathlist = pathlist[shift:]
2686
+ elif shift < 0 and shift >= -len(scriptlist):
2687
+ moved = scriptlist[shift:]
2688
+ pathlist = moved + pathlist
2689
+ scriptlist = scriptlist[:shift]
2690
+ else:
2691
+ empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
2692
+ raise AssertionError("Cannot shift. Nothing left from %s" % empty)
2693
+ new_script_name = '/' + '/'.join(scriptlist)
2694
+ new_path_info = '/' + '/'.join(pathlist)
2695
+ if path_info.endswith('/') and pathlist: new_path_info += '/'
2696
+ return new_script_name, new_path_info
2697
+
2698
+
2699
+ def auth_basic(check, realm="private", text="Access denied"):
2700
+ ''' Callback decorator to require HTTP auth (basic).
2701
+ TODO: Add route(check_auth=...) parameter. '''
2702
+ def decorator(func):
2703
+ @functools.wraps(func)
2704
+ def wrapper(*a, **ka):
2705
+ user, password = request.auth or (None, None)
2706
+ if user is None or not check(user, password):
2707
+ err = HTTPError(401, text)
2708
+ err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
2709
+ return err
2710
+ return func(*a, **ka)
2711
+ return wrapper
2712
+ return decorator
2713
+
2714
+
2715
+ # Shortcuts for common Bottle methods.
2716
+ # They all refer to the current default application.
2717
+
2718
+ def make_default_app_wrapper(name):
2719
+ ''' Return a callable that relays calls to the current default app. '''
2720
+ @functools.wraps(getattr(Bottle, name))
2721
+ def wrapper(*a, **ka):
2722
+ return getattr(app(), name)(*a, **ka)
2723
+ return wrapper
2724
+
2725
+ route = make_default_app_wrapper('route')
2726
+ get = make_default_app_wrapper('get')
2727
+ post = make_default_app_wrapper('post')
2728
+ put = make_default_app_wrapper('put')
2729
+ delete = make_default_app_wrapper('delete')
2730
+ error = make_default_app_wrapper('error')
2731
+ mount = make_default_app_wrapper('mount')
2732
+ hook = make_default_app_wrapper('hook')
2733
+ install = make_default_app_wrapper('install')
2734
+ uninstall = make_default_app_wrapper('uninstall')
2735
+ url = make_default_app_wrapper('get_url')
2736
+
2737
+
2738
+
2739
+
2740
+
2741
+
2742
+
2743
+ ###############################################################################
2744
+ # Server Adapter ###############################################################
2745
+ ###############################################################################
2746
+
2747
+
2748
+ class ServerAdapter(object):
2749
+ quiet = False
2750
+ def __init__(self, host='127.0.0.1', port=8080, **options):
2751
+ self.options = options
2752
+ self.host = host
2753
+ self.port = int(port)
2754
+
2755
+ def run(self, handler): # pragma: no cover
2756
+ pass
2757
+
2758
+ def __repr__(self):
2759
+ args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()])
2760
+ return "%s(%s)" % (self.__class__.__name__, args)
2761
+
2762
+
2763
+ class CGIServer(ServerAdapter):
2764
+ quiet = True
2765
+ def run(self, handler): # pragma: no cover
2766
+ from wsgiref.handlers import CGIHandler
2767
+ def fixed_environ(environ, start_response):
2768
+ environ.setdefault('PATH_INFO', '')
2769
+ return handler(environ, start_response)
2770
+ CGIHandler().run(fixed_environ)
2771
+
2772
+
2773
+ class FlupFCGIServer(ServerAdapter):
2774
+ def run(self, handler): # pragma: no cover
2775
+ import flup.server.fcgi
2776
+ self.options.setdefault('bindAddress', (self.host, self.port))
2777
+ flup.server.fcgi.WSGIServer(handler, **self.options).run()
2778
+
2779
+
2780
+ class WSGIRefServer(ServerAdapter):
2781
+ def run(self, app): # pragma: no cover
2782
+ from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
2783
+ from wsgiref.simple_server import make_server
2784
+ import socket
2785
+
2786
+ class FixedHandler(WSGIRequestHandler):
2787
+ def address_string(self): # Prevent reverse DNS lookups please.
2788
+ return self.client_address[0]
2789
+ def log_request(*args, **kw):
2790
+ if not self.quiet:
2791
+ return WSGIRequestHandler.log_request(*args, **kw)
2792
+
2793
+ handler_cls = self.options.get('handler_class', FixedHandler)
2794
+ server_cls = self.options.get('server_class', WSGIServer)
2795
+
2796
+ if ':' in self.host: # Fix wsgiref for IPv6 addresses.
2797
+ if getattr(server_cls, 'address_family') == socket.AF_INET:
2798
+ class server_cls(server_cls):
2799
+ address_family = socket.AF_INET6
2800
+
2801
+ srv = make_server(self.host, self.port, app, server_cls, handler_cls)
2802
+ srv.serve_forever()
2803
+
2804
+
2805
+ class CherryPyServer(ServerAdapter):
2806
+ def run(self, handler): # pragma: no cover
2807
+ depr("The wsgi server part of cherrypy was split into a new "
2808
+ "project called 'cheroot'. Use the 'cheroot' server "
2809
+ "adapter instead of cherrypy.")
2810
+ from cherrypy import wsgiserver # This will fail for CherryPy >= 9
2811
+
2812
+ self.options['bind_addr'] = (self.host, self.port)
2813
+ self.options['wsgi_app'] = handler
2814
+
2815
+ certfile = self.options.get('certfile')
2816
+ if certfile:
2817
+ del self.options['certfile']
2818
+ keyfile = self.options.get('keyfile')
2819
+ if keyfile:
2820
+ del self.options['keyfile']
2821
+
2822
+ server = wsgiserver.CherryPyWSGIServer(**self.options)
2823
+ if certfile:
2824
+ server.ssl_certificate = certfile
2825
+ if keyfile:
2826
+ server.ssl_private_key = keyfile
2827
+
2828
+ try:
2829
+ server.start()
2830
+ finally:
2831
+ server.stop()
2832
+
2833
+
2834
+ class CherootServer(ServerAdapter):
2835
+ def run(self, handler): # pragma: no cover
2836
+ from cheroot import wsgi
2837
+ from cheroot.ssl import builtin
2838
+ self.options['bind_addr'] = (self.host, self.port)
2839
+ self.options['wsgi_app'] = handler
2840
+ certfile = self.options.pop('certfile', None)
2841
+ keyfile = self.options.pop('keyfile', None)
2842
+ chainfile = self.options.pop('chainfile', None)
2843
+ server = wsgi.Server(**self.options)
2844
+ if certfile and keyfile:
2845
+ server.ssl_adapter = builtin.BuiltinSSLAdapter(
2846
+ certfile, keyfile, chainfile)
2847
+ try:
2848
+ server.start()
2849
+ finally:
2850
+ server.stop()
2851
+
2852
+
2853
+ class WaitressServer(ServerAdapter):
2854
+ def run(self, handler):
2855
+ from waitress import serve
2856
+ serve(handler, host=self.host, port=self.port)
2857
+
2858
+
2859
+ class PasteServer(ServerAdapter):
2860
+ def run(self, handler): # pragma: no cover
2861
+ from paste import httpserver
2862
+ from paste.translogger import TransLogger
2863
+ handler = TransLogger(handler, setup_console_handler=(not self.quiet))
2864
+ httpserver.serve(handler, host=self.host, port=str(self.port),
2865
+ **self.options)
2866
+
2867
+
2868
+ class MeinheldServer(ServerAdapter):
2869
+ def run(self, handler):
2870
+ from meinheld import server
2871
+ server.listen((self.host, self.port))
2872
+ server.run(handler)
2873
+
2874
+
2875
+ class FapwsServer(ServerAdapter):
2876
+ """ Extremely fast webserver using libev. See https://github.com/william-os4y/fapws3 """
2877
+ def run(self, handler): # pragma: no cover
2878
+ import fapws._evwsgi as evwsgi
2879
+ from fapws import base, config
2880
+ port = self.port
2881
+ if float(config.SERVER_IDENT[-2:]) > 0.4:
2882
+ # fapws3 silently changed its API in 0.5
2883
+ port = str(port)
2884
+ evwsgi.start(self.host, port)
2885
+ # fapws3 never releases the GIL. Complain upstream. I tried. No luck.
2886
+ if 'BOTTLE_CHILD' in os.environ and not self.quiet:
2887
+ _stderr("WARNING: Auto-reloading does not work with Fapws3.\n")
2888
+ _stderr(" (Fapws3 breaks python thread support)\n")
2889
+ evwsgi.set_base_module(base)
2890
+ def app(environ, start_response):
2891
+ environ['wsgi.multiprocess'] = False
2892
+ return handler(environ, start_response)
2893
+ evwsgi.wsgi_cb(('', app))
2894
+ evwsgi.run()
2895
+
2896
+
2897
+ class TornadoServer(ServerAdapter):
2898
+ """ The super hyped asynchronous server by facebook. Untested. """
2899
+ def run(self, handler): # pragma: no cover
2900
+ import tornado.wsgi, tornado.httpserver, tornado.ioloop
2901
+ container = tornado.wsgi.WSGIContainer(handler)
2902
+ server = tornado.httpserver.HTTPServer(container)
2903
+ server.listen(port=self.port,address=self.host)
2904
+ tornado.ioloop.IOLoop.instance().start()
2905
+
2906
+
2907
+ class AppEngineServer(ServerAdapter):
2908
+ """ Adapter for Google App Engine. """
2909
+ quiet = True
2910
+ def run(self, handler):
2911
+ from google.appengine.ext.webapp import util
2912
+ # A main() function in the handler script enables 'App Caching'.
2913
+ # Lets makes sure it is there. This _really_ improves performance.
2914
+ module = sys.modules.get('__main__')
2915
+ if module and not hasattr(module, 'main'):
2916
+ module.main = lambda: util.run_wsgi_app(handler)
2917
+ util.run_wsgi_app(handler)
2918
+
2919
+
2920
+ class TwistedServer(ServerAdapter):
2921
+ """ Untested. """
2922
+ def run(self, handler):
2923
+ from twisted.web import server, wsgi
2924
+ from twisted.python.threadpool import ThreadPool
2925
+ from twisted.internet import reactor
2926
+ thread_pool = ThreadPool()
2927
+ thread_pool.start()
2928
+ reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
2929
+ factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
2930
+ reactor.listenTCP(self.port, factory, interface=self.host)
2931
+ reactor.run()
2932
+
2933
+
2934
+ class DieselServer(ServerAdapter):
2935
+ """ Untested. """
2936
+ def run(self, handler):
2937
+ from diesel.protocols.wsgi import WSGIApplication
2938
+ app = WSGIApplication(handler, port=self.port)
2939
+ app.run()
2940
+
2941
+
2942
+ class GeventServer(ServerAdapter):
2943
+ """ Untested. Options:
2944
+
2945
+ * `fast` (default: False) uses libevent's http server, but has some
2946
+ issues: No streaming, no pipelining, no SSL.
2947
+ * See gevent.wsgi.WSGIServer() documentation for more options.
2948
+ """
2949
+ def run(self, handler):
2950
+ from gevent import pywsgi, local
2951
+ if not isinstance(threading.local(), local.local):
2952
+ msg = "Bottle requires gevent.monkey.patch_all() (before import)"
2953
+ raise RuntimeError(msg)
2954
+ if self.options.pop('fast', None):
2955
+ depr('The "fast" option has been deprecated and removed by Gevent.')
2956
+ if self.quiet:
2957
+ self.options['log'] = None
2958
+ address = (self.host, self.port)
2959
+ server = pywsgi.WSGIServer(address, handler, **self.options)
2960
+ if 'BOTTLE_CHILD' in os.environ:
2961
+ import signal
2962
+ signal.signal(signal.SIGINT, lambda s, f: server.stop())
2963
+ server.serve_forever()
2964
+
2965
+
2966
+ class GeventSocketIOServer(ServerAdapter):
2967
+ def run(self,handler):
2968
+ from socketio import server
2969
+ address = (self.host, self.port)
2970
+ server.SocketIOServer(address, handler, **self.options).serve_forever()
2971
+
2972
+
2973
+ class GunicornServer(ServerAdapter):
2974
+ """ Untested. See http://gunicorn.org/configure.html for options. """
2975
+ def run(self, handler):
2976
+ from gunicorn.app.base import Application
2977
+
2978
+ config = {'bind': "%s:%d" % (self.host, int(self.port))}
2979
+ config.update(self.options)
2980
+
2981
+ class GunicornApplication(Application):
2982
+ def init(self, parser, opts, args):
2983
+ return config
2984
+
2985
+ def load(self):
2986
+ return handler
2987
+
2988
+ GunicornApplication().run()
2989
+
2990
+
2991
+ class EventletServer(ServerAdapter):
2992
+ """ Untested """
2993
+ def run(self, handler):
2994
+ from eventlet import wsgi, listen
2995
+ try:
2996
+ wsgi.server(listen((self.host, self.port)), handler,
2997
+ log_output=(not self.quiet))
2998
+ except TypeError:
2999
+ # Fallback, if we have old version of eventlet
3000
+ wsgi.server(listen((self.host, self.port)), handler)
3001
+
3002
+
3003
+ class RocketServer(ServerAdapter):
3004
+ """ Untested. """
3005
+ def run(self, handler):
3006
+ from rocket import Rocket
3007
+ server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
3008
+ server.start()
3009
+
3010
+
3011
+ class BjoernServer(ServerAdapter):
3012
+ """ Fast server written in C: https://github.com/jonashaag/bjoern """
3013
+ def run(self, handler):
3014
+ from bjoern import run
3015
+ run(handler, self.host, self.port)
3016
+
3017
+
3018
+ class AutoServer(ServerAdapter):
3019
+ """ Untested. """
3020
+ adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer,
3021
+ CherootServer, WSGIRefServer]
3022
+
3023
+ def run(self, handler):
3024
+ for sa in self.adapters:
3025
+ try:
3026
+ return sa(self.host, self.port, **self.options).run(handler)
3027
+ except ImportError:
3028
+ pass
3029
+
3030
+ server_names = {
3031
+ 'cgi': CGIServer,
3032
+ 'flup': FlupFCGIServer,
3033
+ 'wsgiref': WSGIRefServer,
3034
+ 'waitress': WaitressServer,
3035
+ 'cherrypy': CherryPyServer,
3036
+ 'cheroot': CherootServer,
3037
+ 'paste': PasteServer,
3038
+ 'fapws3': FapwsServer,
3039
+ 'tornado': TornadoServer,
3040
+ 'gae': AppEngineServer,
3041
+ 'twisted': TwistedServer,
3042
+ 'diesel': DieselServer,
3043
+ 'meinheld': MeinheldServer,
3044
+ 'gunicorn': GunicornServer,
3045
+ 'eventlet': EventletServer,
3046
+ 'gevent': GeventServer,
3047
+ 'geventSocketIO':GeventSocketIOServer,
3048
+ 'rocket': RocketServer,
3049
+ 'bjoern' : BjoernServer,
3050
+ 'auto': AutoServer,
3051
+ }
3052
+
3053
+
3054
+
3055
+
3056
+
3057
+
3058
+ ###############################################################################
3059
+ # Application Control ##########################################################
3060
+ ###############################################################################
3061
+
3062
+
3063
+ def load(target, **namespace):
3064
+ """ Import a module or fetch an object from a module.
3065
+
3066
+ * ``package.module`` returns `module` as a module object.
3067
+ * ``pack.mod:name`` returns the module variable `name` from `pack.mod`.
3068
+ * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.
3069
+
3070
+ The last form accepts not only function calls, but any type of
3071
+ expression. Keyword arguments passed to this function are available as
3072
+ local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
3073
+ """
3074
+ module, target = target.split(":", 1) if ':' in target else (target, None)
3075
+ if module not in sys.modules: __import__(module)
3076
+ if not target: return sys.modules[module]
3077
+ if target.isalnum(): return getattr(sys.modules[module], target)
3078
+ package_name = module.split('.')[0]
3079
+ namespace[package_name] = sys.modules[package_name]
3080
+ return eval('%s.%s' % (module, target), namespace)
3081
+
3082
+
3083
+ def load_app(target):
3084
+ """ Load a bottle application from a module and make sure that the import
3085
+ does not affect the current default application, but returns a separate
3086
+ application object. See :func:`load` for the target parameter. """
3087
+ global NORUN; NORUN, nr_old = True, NORUN
3088
+ try:
3089
+ tmp = default_app.push() # Create a new "default application"
3090
+ rv = load(target) # Import the target module
3091
+ return rv if callable(rv) else tmp
3092
+ finally:
3093
+ default_app.remove(tmp) # Remove the temporary added default application
3094
+ NORUN = nr_old
3095
+
3096
+ _debug = debug
3097
+ def run(app=None, server='wsgiref', host='127.0.0.1', port=8080,
3098
+ interval=1, reloader=False, quiet=False, plugins=None,
3099
+ debug=None, **kargs):
3100
+ """ Start a server instance. This method blocks until the server terminates.
3101
+
3102
+ :param app: WSGI application or target string supported by
3103
+ :func:`load_app`. (default: :func:`default_app`)
3104
+ :param server: Server adapter to use. See :data:`server_names` keys
3105
+ for valid names or pass a :class:`ServerAdapter` subclass.
3106
+ (default: `wsgiref`)
3107
+ :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
3108
+ all interfaces including the external one. (default: 127.0.0.1)
3109
+ :param port: Server port to bind to. Values below 1024 require root
3110
+ privileges. (default: 8080)
3111
+ :param reloader: Start auto-reloading server? (default: False)
3112
+ :param interval: Auto-reloader interval in seconds (default: 1)
3113
+ :param quiet: Suppress output to stdout and stderr? (default: False)
3114
+ :param options: Options passed to the server adapter.
3115
+ """
3116
+ if NORUN: return
3117
+ if reloader and not os.environ.get('BOTTLE_CHILD'):
3118
+ try:
3119
+ lockfile = None
3120
+ fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
3121
+ os.close(fd) # We only need this file to exist. We never write to it
3122
+ while os.path.exists(lockfile):
3123
+ args = [sys.executable] + sys.argv
3124
+ environ = os.environ.copy()
3125
+ environ['BOTTLE_CHILD'] = 'true'
3126
+ environ['BOTTLE_LOCKFILE'] = lockfile
3127
+ p = subprocess.Popen(args, env=environ)
3128
+ while p.poll() is None: # Busy wait...
3129
+ os.utime(lockfile, None) # I am alive!
3130
+ time.sleep(interval)
3131
+ if p.poll() != 3:
3132
+ if os.path.exists(lockfile): os.unlink(lockfile)
3133
+ sys.exit(p.poll())
3134
+ except KeyboardInterrupt:
3135
+ pass
3136
+ finally:
3137
+ if os.path.exists(lockfile):
3138
+ os.unlink(lockfile)
3139
+ return
3140
+
3141
+ try:
3142
+ if debug is not None: _debug(debug)
3143
+ app = app or default_app()
3144
+ if isinstance(app, basestring):
3145
+ app = load_app(app)
3146
+ if not callable(app):
3147
+ raise ValueError("Application is not callable: %r" % app)
3148
+
3149
+ for plugin in plugins or []:
3150
+ app.install(plugin)
3151
+
3152
+ if server in server_names:
3153
+ server = server_names.get(server)
3154
+ if isinstance(server, basestring):
3155
+ server = load(server)
3156
+ if isinstance(server, type):
3157
+ server = server(host=host, port=port, **kargs)
3158
+ if not isinstance(server, ServerAdapter):
3159
+ raise ValueError("Unknown or unsupported server: %r" % server)
3160
+
3161
+ server.quiet = server.quiet or quiet
3162
+ if not server.quiet:
3163
+ _stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server)))
3164
+ _stderr("Listening on http://%s:%d/\n" % (server.host, server.port))
3165
+ _stderr("Hit Ctrl-C to quit.\n\n")
3166
+
3167
+ if reloader:
3168
+ lockfile = os.environ.get('BOTTLE_LOCKFILE')
3169
+ bgcheck = FileCheckerThread(lockfile, interval)
3170
+ with bgcheck:
3171
+ server.run(app)
3172
+ if bgcheck.status == 'reload':
3173
+ sys.exit(3)
3174
+ else:
3175
+ server.run(app)
3176
+ except KeyboardInterrupt:
3177
+ pass
3178
+ except (SystemExit, MemoryError):
3179
+ raise
3180
+ except:
3181
+ if not reloader: raise
3182
+ if not getattr(server, 'quiet', quiet):
3183
+ print_exc()
3184
+ time.sleep(interval)
3185
+ sys.exit(3)
3186
+
3187
+
3188
+
3189
+ class FileCheckerThread(threading.Thread):
3190
+ ''' Interrupt main-thread as soon as a changed module file is detected,
3191
+ the lockfile gets deleted or gets to old. '''
3192
+
3193
+ def __init__(self, lockfile, interval):
3194
+ threading.Thread.__init__(self)
3195
+ self.lockfile, self.interval = lockfile, interval
3196
+ #: Is one of 'reload', 'error' or 'exit'
3197
+ self.status = None
3198
+
3199
+ def run(self):
3200
+ exists = os.path.exists
3201
+ mtime = lambda path: os.stat(path).st_mtime
3202
+ files = dict()
3203
+
3204
+ for module in list(sys.modules.values()):
3205
+ path = getattr(module, '__file__', '') or ''
3206
+ if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
3207
+ if path and exists(path): files[path] = mtime(path)
3208
+
3209
+ while not self.status:
3210
+ if not exists(self.lockfile)\
3211
+ or mtime(self.lockfile) < time.time() - self.interval - 5:
3212
+ self.status = 'error'
3213
+ thread.interrupt_main()
3214
+ for path, lmtime in list(files.items()):
3215
+ if not exists(path) or mtime(path) > lmtime:
3216
+ self.status = 'reload'
3217
+ thread.interrupt_main()
3218
+ break
3219
+ time.sleep(self.interval)
3220
+
3221
+ def __enter__(self):
3222
+ self.start()
3223
+
3224
+ def __exit__(self, exc_type, exc_val, exc_tb):
3225
+ if not self.status: self.status = 'exit' # silent exit
3226
+ self.join()
3227
+ return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
3228
+
3229
+
3230
+
3231
+
3232
+
3233
+ ###############################################################################
3234
+ # Template Adapters ############################################################
3235
+ ###############################################################################
3236
+
3237
+
3238
+ class TemplateError(HTTPError):
3239
+ def __init__(self, message):
3240
+ HTTPError.__init__(self, 500, message)
3241
+
3242
+
3243
+ class BaseTemplate(object):
3244
+ """ Base class and minimal API for template adapters """
3245
+ extensions = ['tpl','html','thtml','stpl']
3246
+ settings = {} #used in prepare()
3247
+ defaults = {} #used in render()
3248
+
3249
+ def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
3250
+ """ Create a new template.
3251
+ If the source parameter (str or buffer) is missing, the name argument
3252
+ is used to guess a template filename. Subclasses can assume that
3253
+ self.source and/or self.filename are set. Both are strings.
3254
+ The lookup, encoding and settings parameters are stored as instance
3255
+ variables.
3256
+ The lookup parameter stores a list containing directory paths.
3257
+ The encoding parameter should be used to decode byte strings or files.
3258
+ The settings parameter contains a dict for engine-specific settings.
3259
+ """
3260
+ self.name = name
3261
+ self.source = source.read() if hasattr(source, 'read') else source
3262
+ self.filename = source.filename if hasattr(source, 'filename') else None
3263
+ self.lookup = [os.path.abspath(x) for x in lookup]
3264
+ self.encoding = encoding
3265
+ self.settings = self.settings.copy() # Copy from class variable
3266
+ self.settings.update(settings) # Apply
3267
+ if not self.source and self.name:
3268
+ self.filename = self.search(self.name, self.lookup)
3269
+ if not self.filename:
3270
+ raise TemplateError('Template %s not found.' % repr(name))
3271
+ if not self.source and not self.filename:
3272
+ raise TemplateError('No template specified.')
3273
+ self.prepare(**self.settings)
3274
+
3275
+ @classmethod
3276
+ def search(cls, name, lookup=[]):
3277
+ """ Search name in all directories specified in lookup.
3278
+ First without, then with common extensions. Return first hit. """
3279
+ if not lookup:
3280
+ depr('The template lookup path list should not be empty.') #0.12
3281
+ lookup = ['.']
3282
+
3283
+ if os.path.isabs(name) and os.path.isfile(name):
3284
+ depr('Absolute template path names are deprecated.') #0.12
3285
+ return os.path.abspath(name)
3286
+
3287
+ for spath in lookup:
3288
+ spath = os.path.abspath(spath) + os.sep
3289
+ fname = os.path.abspath(os.path.join(spath, name))
3290
+ if not fname.startswith(spath): continue
3291
+ if os.path.isfile(fname): return fname
3292
+ for ext in cls.extensions:
3293
+ if os.path.isfile('%s.%s' % (fname, ext)):
3294
+ return '%s.%s' % (fname, ext)
3295
+
3296
+ @classmethod
3297
+ def global_config(cls, key, *args):
3298
+ ''' This reads or sets the global settings stored in class.settings. '''
3299
+ if args:
3300
+ cls.settings = cls.settings.copy() # Make settings local to class
3301
+ cls.settings[key] = args[0]
3302
+ else:
3303
+ return cls.settings[key]
3304
+
3305
+ def prepare(self, **options):
3306
+ """ Run preparations (parsing, caching, ...).
3307
+ It should be possible to call this again to refresh a template or to
3308
+ update settings.
3309
+ """
3310
+ raise NotImplementedError
3311
+
3312
+ def render(self, *args, **kwargs):
3313
+ """ Render the template with the specified local variables and return
3314
+ a single byte or unicode string. If it is a byte string, the encoding
3315
+ must match self.encoding. This method must be thread-safe!
3316
+ Local variables may be provided in dictionaries (args)
3317
+ or directly, as keywords (kwargs).
3318
+ """
3319
+ raise NotImplementedError
3320
+
3321
+
3322
+ class MakoTemplate(BaseTemplate):
3323
+ def prepare(self, **options):
3324
+ from mako.template import Template
3325
+ from mako.lookup import TemplateLookup
3326
+ options.update({'input_encoding':self.encoding})
3327
+ options.setdefault('format_exceptions', bool(DEBUG))
3328
+ lookup = TemplateLookup(directories=self.lookup, **options)
3329
+ if self.source:
3330
+ self.tpl = Template(self.source, lookup=lookup, **options)
3331
+ else:
3332
+ self.tpl = Template(uri=self.name, filename=self.filename, lookup=lookup, **options)
3333
+
3334
+ def render(self, *args, **kwargs):
3335
+ for dictarg in args: kwargs.update(dictarg)
3336
+ _defaults = self.defaults.copy()
3337
+ _defaults.update(kwargs)
3338
+ return self.tpl.render(**_defaults)
3339
+
3340
+
3341
+ class CheetahTemplate(BaseTemplate):
3342
+ def prepare(self, **options):
3343
+ from Cheetah.Template import Template
3344
+ self.context = threading.local()
3345
+ self.context.vars = {}
3346
+ options['searchList'] = [self.context.vars]
3347
+ if self.source:
3348
+ self.tpl = Template(source=self.source, **options)
3349
+ else:
3350
+ self.tpl = Template(file=self.filename, **options)
3351
+
3352
+ def render(self, *args, **kwargs):
3353
+ for dictarg in args: kwargs.update(dictarg)
3354
+ self.context.vars.update(self.defaults)
3355
+ self.context.vars.update(kwargs)
3356
+ out = str(self.tpl)
3357
+ self.context.vars.clear()
3358
+ return out
3359
+
3360
+
3361
+ class Jinja2Template(BaseTemplate):
3362
+ def prepare(self, filters=None, tests=None, globals={}, **kwargs):
3363
+ from jinja2 import Environment, FunctionLoader
3364
+ if 'prefix' in kwargs: # TODO: to be removed after a while
3365
+ raise RuntimeError('The keyword argument `prefix` has been removed. '
3366
+ 'Use the full jinja2 environment name line_statement_prefix instead.')
3367
+ self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
3368
+ if filters: self.env.filters.update(filters)
3369
+ if tests: self.env.tests.update(tests)
3370
+ if globals: self.env.globals.update(globals)
3371
+ if self.source:
3372
+ self.tpl = self.env.from_string(self.source)
3373
+ else:
3374
+ self.tpl = self.env.get_template(self.filename)
3375
+
3376
+ def render(self, *args, **kwargs):
3377
+ for dictarg in args: kwargs.update(dictarg)
3378
+ _defaults = self.defaults.copy()
3379
+ _defaults.update(kwargs)
3380
+ return self.tpl.render(**_defaults)
3381
+
3382
+ def loader(self, name):
3383
+ fname = self.search(name, self.lookup)
3384
+ if not fname: return
3385
+ with open(fname, "rb") as f:
3386
+ return f.read().decode(self.encoding)
3387
+
3388
+
3389
+ class SimpleTemplate(BaseTemplate):
3390
+
3391
+ def prepare(self, escape_func=html_escape, noescape=False, syntax=None, **ka):
3392
+ self.cache = {}
3393
+ enc = self.encoding
3394
+ self._str = lambda x: touni(x, enc)
3395
+ self._escape = lambda x: escape_func(touni(x, enc))
3396
+ self.syntax = syntax
3397
+ if noescape:
3398
+ self._str, self._escape = self._escape, self._str
3399
+
3400
+ @cached_property
3401
+ def co(self):
3402
+ return compile(self.code, self.filename or '<string>', 'exec')
3403
+
3404
+ @cached_property
3405
+ def code(self):
3406
+ source = self.source
3407
+ if not source:
3408
+ with open(self.filename, 'rb') as f:
3409
+ source = f.read()
3410
+ try:
3411
+ source, encoding = touni(source), 'utf8'
3412
+ except UnicodeError:
3413
+ depr('Template encodings other than utf8 are no longer supported.') #0.11
3414
+ source, encoding = touni(source, 'latin1'), 'latin1'
3415
+ parser = StplParser(source, encoding=encoding, syntax=self.syntax)
3416
+ code = parser.translate()
3417
+ self.encoding = parser.encoding
3418
+ return code
3419
+
3420
+ def _rebase(self, _env, _name=None, **kwargs):
3421
+ if _name is None:
3422
+ depr('Rebase function called without arguments.'
3423
+ ' You were probably looking for {{base}}?', True) #0.12
3424
+ _env['_rebase'] = (_name, kwargs)
3425
+
3426
+ def _include(self, _env, _name=None, **kwargs):
3427
+ if _name is None:
3428
+ depr('Rebase function called without arguments.'
3429
+ ' You were probably looking for {{base}}?', True) #0.12
3430
+ env = _env.copy()
3431
+ env.update(kwargs)
3432
+ if _name not in self.cache:
3433
+ self.cache[_name] = self.__class__(name=_name, lookup=self.lookup)
3434
+ return self.cache[_name].execute(env['_stdout'], env)
3435
+
3436
+ def execute(self, _stdout, kwargs):
3437
+ env = self.defaults.copy()
3438
+ env.update(kwargs)
3439
+ env.update({'_stdout': _stdout, '_printlist': _stdout.extend,
3440
+ 'include': functools.partial(self._include, env),
3441
+ 'rebase': functools.partial(self._rebase, env), '_rebase': None,
3442
+ '_str': self._str, '_escape': self._escape, 'get': env.get,
3443
+ 'setdefault': env.setdefault, 'defined': env.__contains__ })
3444
+ eval(self.co, env)
3445
+ if env.get('_rebase'):
3446
+ subtpl, rargs = env.pop('_rebase')
3447
+ rargs['base'] = ''.join(_stdout) #copy stdout
3448
+ del _stdout[:] # clear stdout
3449
+ return self._include(env, subtpl, **rargs)
3450
+ return env
3451
+
3452
+ def render(self, *args, **kwargs):
3453
+ """ Render the template using keyword arguments as local variables. """
3454
+ env = {}; stdout = []
3455
+ for dictarg in args: env.update(dictarg)
3456
+ env.update(kwargs)
3457
+ self.execute(stdout, env)
3458
+ return ''.join(stdout)
3459
+
3460
+
3461
+ class StplSyntaxError(TemplateError): pass
3462
+
3463
+
3464
+ class StplParser(object):
3465
+ ''' Parser for stpl templates. '''
3466
+ _re_cache = {} #: Cache for compiled re patterns
3467
+ # This huge pile of voodoo magic splits python code into 8 different tokens.
3468
+ # 1: All kinds of python strings (trust me, it works)
3469
+ _re_tok = '([urbURB]?(?:\'\'(?!\')|""(?!")|\'{6}|"{6}' \
3470
+ '|\'(?:[^\\\\\']|\\\\.)+?\'|"(?:[^\\\\"]|\\\\.)+?"' \
3471
+ '|\'{3}(?:[^\\\\]|\\\\.|\\n)+?\'{3}' \
3472
+ '|"{3}(?:[^\\\\]|\\\\.|\\n)+?"{3}))'
3473
+ _re_inl = _re_tok.replace('|\\n','') # We re-use this string pattern later
3474
+ # 2: Comments (until end of line, but not the newline itself)
3475
+ _re_tok += '|(#.*)'
3476
+ # 3,4: Open and close grouping tokens
3477
+ _re_tok += '|([\\[\\{\\(])'
3478
+ _re_tok += '|([\\]\\}\\)])'
3479
+ # 5,6: Keywords that start or continue a python block (only start of line)
3480
+ _re_tok += '|^([ \\t]*(?:if|for|while|with|try|def|class)\\b)' \
3481
+ '|^([ \\t]*(?:elif|else|except|finally)\\b)'
3482
+ # 7: Our special 'end' keyword (but only if it stands alone)
3483
+ _re_tok += '|((?:^|;)[ \\t]*end[ \\t]*(?=(?:%(block_close)s[ \\t]*)?\\r?$|;|#))'
3484
+ # 8: A customizable end-of-code-block template token (only end of line)
3485
+ _re_tok += '|(%(block_close)s[ \\t]*(?=\\r?$))'
3486
+ # 9: And finally, a single newline. The 10th token is 'everything else'
3487
+ _re_tok += '|(\\r?\\n)'
3488
+
3489
+ # Match the start tokens of code areas in a template
3490
+ _re_split = '(?m)^[ \t]*(\\\\?)((%(line_start)s)|(%(block_start)s))(%%?)'
3491
+ # Match inline statements (may contain python strings)
3492
+ _re_inl = '(?m)%%(inline_start)s((?:%s|[^\'"\n])*?)%%(inline_end)s' % _re_inl
3493
+ _re_tok = '(?m)' + _re_tok
3494
+
3495
+ default_syntax = '<% %> % {{ }}'
3496
+
3497
+ def __init__(self, source, syntax=None, encoding='utf8'):
3498
+ self.source, self.encoding = touni(source, encoding), encoding
3499
+ self.set_syntax(syntax or self.default_syntax)
3500
+ self.code_buffer, self.text_buffer = [], []
3501
+ self.lineno, self.offset = 1, 0
3502
+ self.indent, self.indent_mod = 0, 0
3503
+ self.paren_depth = 0
3504
+
3505
+ def get_syntax(self):
3506
+ ''' Tokens as a space separated string (default: <% %> % {{ }}) '''
3507
+ return self._syntax
3508
+
3509
+ def set_syntax(self, syntax):
3510
+ self._syntax = syntax
3511
+ self._tokens = syntax.split()
3512
+ if not syntax in self._re_cache:
3513
+ names = 'block_start block_close line_start inline_start inline_end'
3514
+ etokens = map(re.escape, self._tokens)
3515
+ pattern_vars = dict(zip(names.split(), etokens))
3516
+ patterns = (self._re_split, self._re_tok, self._re_inl)
3517
+ patterns = [re.compile(p%pattern_vars) for p in patterns]
3518
+ self._re_cache[syntax] = patterns
3519
+ self.re_split, self.re_tok, self.re_inl = self._re_cache[syntax]
3520
+
3521
+ syntax = property(get_syntax, set_syntax)
3522
+
3523
+ def translate(self):
3524
+ if self.offset: raise RuntimeError('Parser is a one time instance.')
3525
+ while True:
3526
+ m = self.re_split.search(self.source[self.offset:])
3527
+ if m:
3528
+ text = self.source[self.offset:self.offset+m.start()]
3529
+ self.text_buffer.append(text)
3530
+ self.offset += m.end()
3531
+ if m.group(1): # New escape syntax
3532
+ line, sep, _ = self.source[self.offset:].partition('\n')
3533
+ self.text_buffer.append(m.group(2)+m.group(5)+line+sep)
3534
+ self.offset += len(line+sep)+1
3535
+ continue
3536
+ elif m.group(5): # Old escape syntax
3537
+ depr('Escape code lines with a backslash.') #0.12
3538
+ line, sep, _ = self.source[self.offset:].partition('\n')
3539
+ self.text_buffer.append(m.group(2)+line+sep)
3540
+ self.offset += len(line+sep)+1
3541
+ continue
3542
+ self.flush_text()
3543
+ self.read_code(multiline=bool(m.group(4)))
3544
+ else: break
3545
+ self.text_buffer.append(self.source[self.offset:])
3546
+ self.flush_text()
3547
+ return ''.join(self.code_buffer)
3548
+
3549
+ def read_code(self, multiline):
3550
+ code_line, comment = '', ''
3551
+ while True:
3552
+ m = self.re_tok.search(self.source[self.offset:])
3553
+ if not m:
3554
+ code_line += self.source[self.offset:]
3555
+ self.offset = len(self.source)
3556
+ self.write_code(code_line.strip(), comment)
3557
+ return
3558
+ code_line += self.source[self.offset:self.offset+m.start()]
3559
+ self.offset += m.end()
3560
+ _str, _com, _po, _pc, _blk1, _blk2, _end, _cend, _nl = m.groups()
3561
+ if (code_line or self.paren_depth > 0) and (_blk1 or _blk2): # a if b else c
3562
+ code_line += _blk1 or _blk2
3563
+ continue
3564
+ if _str: # Python string
3565
+ code_line += _str
3566
+ elif _com: # Python comment (up to EOL)
3567
+ comment = _com
3568
+ if multiline and _com.strip().endswith(self._tokens[1]):
3569
+ multiline = False # Allow end-of-block in comments
3570
+ elif _po: # open parenthesis
3571
+ self.paren_depth += 1
3572
+ code_line += _po
3573
+ elif _pc: # close parenthesis
3574
+ if self.paren_depth > 0:
3575
+ # we could check for matching parentheses here, but it's
3576
+ # easier to leave that to python - just check counts
3577
+ self.paren_depth -= 1
3578
+ code_line += _pc
3579
+ elif _blk1: # Start-block keyword (if/for/while/def/try/...)
3580
+ code_line, self.indent_mod = _blk1, -1
3581
+ self.indent += 1
3582
+ elif _blk2: # Continue-block keyword (else/elif/except/...)
3583
+ code_line, self.indent_mod = _blk2, -1
3584
+ elif _end: # The non-standard 'end'-keyword (ends a block)
3585
+ self.indent -= 1
3586
+ elif _cend: # The end-code-block template token (usually '%>')
3587
+ if multiline: multiline = False
3588
+ else: code_line += _cend
3589
+ else: # \n
3590
+ self.write_code(code_line.strip(), comment)
3591
+ self.lineno += 1
3592
+ code_line, comment, self.indent_mod = '', '', 0
3593
+ if not multiline:
3594
+ break
3595
+
3596
+ def flush_text(self):
3597
+ text = ''.join(self.text_buffer)
3598
+ del self.text_buffer[:]
3599
+ if not text: return
3600
+ parts, pos, nl = [], 0, '\\\n'+' '*self.indent
3601
+ for m in self.re_inl.finditer(text):
3602
+ prefix, pos = text[pos:m.start()], m.end()
3603
+ if prefix:
3604
+ parts.append(nl.join(map(repr, prefix.splitlines(True))))
3605
+ if prefix.endswith('\n'): parts[-1] += nl
3606
+ parts.append(self.process_inline(m.group(1).strip()))
3607
+ if pos < len(text):
3608
+ prefix = text[pos:]
3609
+ lines = prefix.splitlines(True)
3610
+ if lines[-1].endswith('\\\\\n'): lines[-1] = lines[-1][:-3]
3611
+ elif lines[-1].endswith('\\\\\r\n'): lines[-1] = lines[-1][:-4]
3612
+ parts.append(nl.join(map(repr, lines)))
3613
+ code = '_printlist((%s,))' % ', '.join(parts)
3614
+ self.lineno += code.count('\n')+1
3615
+ self.write_code(code)
3616
+
3617
+ def process_inline(self, chunk):
3618
+ if chunk[0] == '!': return '_str(%s)' % chunk[1:]
3619
+ return '_escape(%s)' % chunk
3620
+
3621
+ def write_code(self, line, comment=''):
3622
+ line, comment = self.fix_backward_compatibility(line, comment)
3623
+ code = ' ' * (self.indent+self.indent_mod)
3624
+ code += line.lstrip() + comment + '\n'
3625
+ self.code_buffer.append(code)
3626
+
3627
+ def fix_backward_compatibility(self, line, comment):
3628
+ parts = line.strip().split(None, 2)
3629
+ if parts and parts[0] in ('include', 'rebase'):
3630
+ depr('The include and rebase keywords are functions now.') #0.12
3631
+ if len(parts) == 1: return "_printlist([base])", comment
3632
+ elif len(parts) == 2: return "_=%s(%r)" % tuple(parts), comment
3633
+ else: return "_=%s(%r, %s)" % tuple(parts), comment
3634
+ if self.lineno <= 2 and not line.strip() and 'coding' in comment:
3635
+ m = re.match(r"#.*coding[:=]\s*([-\w.]+)", comment)
3636
+ if m:
3637
+ depr('PEP263 encoding strings in templates are deprecated.') #0.12
3638
+ enc = m.group(1)
3639
+ self.source = self.source.encode(self.encoding).decode(enc)
3640
+ self.encoding = enc
3641
+ return line, comment.replace('coding','coding*')
3642
+ return line, comment
3643
+
3644
+
3645
+ def template(*args, **kwargs):
3646
+ '''
3647
+ Get a rendered template as a string iterator.
3648
+ You can use a name, a filename or a template string as first parameter.
3649
+ Template rendering arguments can be passed as dictionaries
3650
+ or directly (as keyword arguments).
3651
+ '''
3652
+ tpl = args[0] if args else None
3653
+ adapter = kwargs.pop('template_adapter', SimpleTemplate)
3654
+ lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
3655
+ tplid = (id(lookup), tpl)
3656
+ if tplid not in TEMPLATES or DEBUG:
3657
+ settings = kwargs.pop('template_settings', {})
3658
+ if isinstance(tpl, adapter):
3659
+ TEMPLATES[tplid] = tpl
3660
+ if settings: TEMPLATES[tplid].prepare(**settings)
3661
+ elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
3662
+ TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
3663
+ else:
3664
+ TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
3665
+ if not TEMPLATES[tplid]:
3666
+ abort(500, 'Template (%s) not found' % tpl)
3667
+ for dictarg in args[1:]: kwargs.update(dictarg)
3668
+ return TEMPLATES[tplid].render(kwargs)
3669
+
3670
+ mako_template = functools.partial(template, template_adapter=MakoTemplate)
3671
+ cheetah_template = functools.partial(template, template_adapter=CheetahTemplate)
3672
+ jinja2_template = functools.partial(template, template_adapter=Jinja2Template)
3673
+
3674
+
3675
+ def view(tpl_name, **defaults):
3676
+ ''' Decorator: renders a template for a handler.
3677
+ The handler can control its behavior like that:
3678
+
3679
+ - return a dict of template vars to fill out the template
3680
+ - return something other than a dict and the view decorator will not
3681
+ process the template, but return the handler result as is.
3682
+ This includes returning a HTTPResponse(dict) to get,
3683
+ for instance, JSON with autojson or other castfilters.
3684
+ '''
3685
+ def decorator(func):
3686
+ @functools.wraps(func)
3687
+ def wrapper(*args, **kwargs):
3688
+ result = func(*args, **kwargs)
3689
+ if isinstance(result, (dict, DictMixin)):
3690
+ tplvars = defaults.copy()
3691
+ tplvars.update(result)
3692
+ return template(tpl_name, **tplvars)
3693
+ elif result is None:
3694
+ return template(tpl_name, **defaults)
3695
+ return result
3696
+ return wrapper
3697
+ return decorator
3698
+
3699
+ mako_view = functools.partial(view, template_adapter=MakoTemplate)
3700
+ cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
3701
+ jinja2_view = functools.partial(view, template_adapter=Jinja2Template)
3702
+
3703
+
3704
+
3705
+
3706
+
3707
+
3708
+ ###############################################################################
3709
+ # Constants and Globals ########################################################
3710
+ ###############################################################################
3711
+
3712
+
3713
+ TEMPLATE_PATH = ['./', './views/']
3714
+ TEMPLATES = {}
3715
+ DEBUG = False
3716
+ NORUN = False # If set, run() does nothing. Used by load_app()
3717
+
3718
+ #: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found')
3719
+ HTTP_CODES = httplib.responses
3720
+ HTTP_CODES[418] = "I'm a teapot" # RFC 2324
3721
+ HTTP_CODES[422] = "Unprocessable Entity" # RFC 4918
3722
+ HTTP_CODES[428] = "Precondition Required"
3723
+ HTTP_CODES[429] = "Too Many Requests"
3724
+ HTTP_CODES[431] = "Request Header Fields Too Large"
3725
+ HTTP_CODES[511] = "Network Authentication Required"
3726
+ _HTTP_STATUS_LINES = dict((k, '%d %s'%(k,v)) for (k,v) in HTTP_CODES.items())
3727
+
3728
+ #: The default template used for error pages. Override with @error()
3729
+ ERROR_PAGE_TEMPLATE = """
3730
+ %%try:
3731
+ %%from %s import DEBUG, HTTP_CODES, request, touni
3732
+ <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
3733
+ <html>
3734
+ <head>
3735
+ <title>Error: {{e.status}}</title>
3736
+ <style type="text/css">
3737
+ html {background-color: #eee; font-family: sans;}
3738
+ body {background-color: #fff; border: 1px solid #ddd;
3739
+ padding: 15px; margin: 15px;}
3740
+ pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
3741
+ </style>
3742
+ </head>
3743
+ <body>
3744
+ <h1>Error: {{e.status}}</h1>
3745
+ <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>
3746
+ caused an error:</p>
3747
+ <pre>{{e.body}}</pre>
3748
+ %%if DEBUG and e.exception:
3749
+ <h2>Exception:</h2>
3750
+ <pre>{{repr(e.exception)}}</pre>
3751
+ %%end
3752
+ %%if DEBUG and e.traceback:
3753
+ <h2>Traceback:</h2>
3754
+ <pre>{{e.traceback}}</pre>
3755
+ %%end
3756
+ </body>
3757
+ </html>
3758
+ %%except ImportError:
3759
+ <b>ImportError:</b> Could not generate the error page. Please add bottle to
3760
+ the import path.
3761
+ %%end
3762
+ """ % __name__
3763
+
3764
+ #: A thread-safe instance of :class:`LocalRequest`. If accessed from within a
3765
+ #: request callback, this instance always refers to the *current* request
3766
+ #: (even on a multithreaded server).
3767
+ request = LocalRequest()
3768
+
3769
+ #: A thread-safe instance of :class:`LocalResponse`. It is used to change the
3770
+ #: HTTP response for the *current* request.
3771
+ response = LocalResponse()
3772
+
3773
+ #: A thread-safe namespace. Not used by Bottle.
3774
+ local = threading.local()
3775
+
3776
+ # Initialize app stack (create first empty Bottle app)
3777
+ # BC: 0.6.4 and needed for run()
3778
+ app = default_app = AppStack()
3779
+ app.push()
3780
+
3781
+ #: A virtual package that redirects import statements.
3782
+ #: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`.
3783
+ ext = _ImportRedirect('bottle.ext' if __name__ == '__main__' else __name__+".ext", 'bottle_%s').module
3784
+
3785
+ if __name__ == '__main__':
3786
+ opt, args, parser = _cmd_options, _cmd_args, _cmd_parser
3787
+ if opt.version:
3788
+ _stdout('Bottle %s\n'%__version__)
3789
+ sys.exit(0)
3790
+ if not args:
3791
+ parser.print_help()
3792
+ _stderr('\nError: No application specified.\n')
3793
+ sys.exit(1)
3794
+
3795
+ sys.path.insert(0, '.')
3796
+ sys.modules.setdefault('bottle', sys.modules['__main__'])
3797
+
3798
+ host, port = (opt.bind or 'localhost'), 8080
3799
+ if ':' in host and host.rfind(']') < host.rfind(':'):
3800
+ host, port = host.rsplit(':', 1)
3801
+ host = host.strip('[]')
3802
+
3803
+ run(args[0], host=host, port=int(port), server=opt.server,
3804
+ reloader=opt.reload, plugins=opt.plugin, debug=opt.debug)
3805
+
3806
+
3807
+
3808
+
3809
+ # THE END