arelle-release 2.36.39__py3-none-any.whl → 2.37.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of arelle-release might be problematic. Click here for more details.

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