h8rt3rmin8r

bottle-0.13-dev.py

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