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