Full Code of bottlepy/bottle for AI

master 24e80dc026c0 cached
217 files
2.7 MB
724.1k tokens
882 symbols
1 requests
Download .txt
Showing preview only (2,893K chars total). Download the full file or copy to clipboard to get everything.
Repository: bottlepy/bottle
Branch: master
Commit: 24e80dc026c0
Files: 217
Total size: 2.7 MB

Directory structure:
gitextract_gk165kp2/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── run_tests.yml
├── .gitignore
├── .readthedocs.yaml
├── AUTHORS
├── LICENSE
├── Makefile
├── README.rst
├── bottle.py
├── docs/
│   ├── _locale/
│   │   ├── .tx/
│   │   │   └── config
│   │   ├── README.txt
│   │   ├── _pot/
│   │   │   ├── api.pot
│   │   │   ├── async.pot
│   │   │   ├── changelog.pot
│   │   │   ├── configuration.pot
│   │   │   ├── contact.pot
│   │   │   ├── deployment.pot
│   │   │   ├── development.pot
│   │   │   ├── faq.pot
│   │   │   ├── index.pot
│   │   │   ├── plugindev.pot
│   │   │   ├── plugins/
│   │   │   │   └── index.pot
│   │   │   ├── recipes.pot
│   │   │   ├── routing.pot
│   │   │   ├── stpl.pot
│   │   │   ├── tutorial.pot
│   │   │   └── tutorial_app.pot
│   │   ├── de_DE/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── fr/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── ja_JP/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── pt_BR/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── _pot/
│   │   │       │   ├── api.po
│   │   │       │   ├── async.po
│   │   │       │   ├── changelog.po
│   │   │       │   ├── configuration.po
│   │   │       │   ├── contact.po
│   │   │       │   ├── deployment.po
│   │   │       │   ├── development.po
│   │   │       │   ├── faq.po
│   │   │       │   ├── index.po
│   │   │       │   ├── plugindev.po
│   │   │       │   ├── plugins/
│   │   │       │   │   └── index.po
│   │   │       │   ├── recipes.po
│   │   │       │   ├── routing.po
│   │   │       │   ├── stpl.po
│   │   │       │   ├── tutorial.po
│   │   │       │   └── tutorial_app.po
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── requirements.txt
│   │   ├── ru_RU/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   └── zh_CN/
│   │       └── LC_MESSAGES/
│   │           ├── _pot/
│   │           │   ├── api.po
│   │           │   ├── async.po
│   │           │   ├── changelog.po
│   │           │   ├── configuration.po
│   │           │   ├── contact.po
│   │           │   ├── deployment.po
│   │           │   ├── development.po
│   │           │   ├── faq.po
│   │           │   ├── index.po
│   │           │   ├── plugindev.po
│   │           │   ├── plugins/
│   │           │   │   └── index.po
│   │           │   ├── recipes.po
│   │           │   ├── routing.po
│   │           │   ├── stpl.po
│   │           │   ├── tutorial.po
│   │           │   └── tutorial_app.po
│   │           ├── api.po
│   │           ├── async.po
│   │           ├── changelog.po
│   │           ├── configuration.po
│   │           ├── contact.po
│   │           ├── deployment.po
│   │           ├── development.po
│   │           ├── faq.po
│   │           ├── index.po
│   │           ├── plugindev.po
│   │           ├── plugins/
│   │           │   └── index.po
│   │           ├── recipes.po
│   │           ├── routing.po
│   │           ├── stpl.po
│   │           ├── tutorial.po
│   │           └── tutorial_app.po
│   ├── api.rst
│   ├── async.rst
│   ├── changelog.rst
│   ├── conf.py
│   ├── configuration.rst
│   ├── contributors.rst
│   ├── deployment.rst
│   ├── development.rst
│   ├── faq.rst
│   ├── index.rst
│   ├── plugins/
│   │   ├── dev.rst
│   │   ├── index.rst
│   │   └── list.rst
│   ├── routing.rst
│   ├── stpl.rst
│   ├── tutorial.rst
│   └── tutorial_app.rst
├── pyproject.toml
└── test/
    ├── .coveragerc
    ├── __init__.py
    ├── build_python.sh
    ├── example_settings.py
    ├── test_app.py
    ├── test_auth.py
    ├── test_config.py
    ├── test_contextlocals.py
    ├── test_environ.py
    ├── test_exc.py
    ├── test_fileupload.py
    ├── test_formsdict.py
    ├── test_html_helper.py
    ├── test_importhook.py
    ├── test_jinja2.py
    ├── test_mako.py
    ├── test_mdict.py
    ├── test_mount.py
    ├── test_multipart.py
    ├── test_oorouting.py
    ├── test_outputfilter.py
    ├── test_plugins.py
    ├── test_resources.py
    ├── test_route.py
    ├── test_router.py
    ├── test_securecookies.py
    ├── test_sendfile.py
    ├── test_stpl.py
    ├── test_wsgi.py
    ├── tools.py
    └── views/
        ├── jinja2_base.tpl
        ├── jinja2_inherit.tpl
        ├── jinja2_simple.tpl
        ├── mako_base.tpl
        ├── mako_inherit.tpl
        ├── mako_simple.tpl
        ├── stpl_include.tpl
        ├── stpl_no_vars.tpl
        ├── stpl_simple.tpl
        ├── stpl_t2base.tpl
        ├── stpl_t2inc.tpl
        ├── stpl_t2main.tpl
        └── stpl_unicode.tpl

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
github: [defnull]
liberapay: defnull


================================================
FILE: .github/workflows/run_tests.yml
================================================
name: Run Tests
on: [push, pull_request, workflow_call]

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      max-parallel: 6
      matrix:
        python-version:
          - "3.9"
          - "3.10"
          - "3.11"
          - "3.12"
          - "3.13"
    steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-python@v5
      with:
        python-version: ${{ matrix.python-version }}
        check-latest: true
        cache: pip
    - name: Install dev dependencies
      run: pip install .[dev]
    - name: Run tests
      run: pytest -ra -q --cov=bottle --cov-report=term


================================================
FILE: .gitignore
================================================
*.pyc
*.pyo
*.db
*.log
*.mo
._*
*.*~
__pycache__

dist/
build/
MANIFEST
bottle.egg-info/

.idea/

htmlcov/
.htmlcoverage/
.coverage
.name
.tox/
.pytest_cache

docs/_locale/_pot/.doctrees/


================================================
FILE: .readthedocs.yaml
================================================
# Read the Docs configuration file for Sphinx projects
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Set the OS, Python version and other tools you might need
build:
  os: ubuntu-22.04
  tools:
    python: latest

# Build documentation in the "docs/" directory with Sphinx
sphinx:
  configuration: docs/conf.py

# Optional but recommended, declare the Python requirements required
# to build your documentation
# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
python:
  install:
    - method: pip
      path: .
      extra_requirements:
        - docs

================================================
FILE: AUTHORS
================================================
Bottle is written and maintained by Marcel Hellkamp <marc@bottlepy.org>.

Thanks to all the people who found bugs, sent patches, spread the word, helped each other on the mailing-list and made this project possible. I hope the following (alphabetically sorted) list is complete. If you miss your name on that list (or want your name removed) please file a pull request.

* acasajus
* Adam R. Smith
* Alexey Borzenkov
* Alexis Daboville
* Anton I. Sipos
* Anton Kolechkin
* apexi200sx
* apheage
* BillMa
* Brad Greenlee
* Brandon Gilmore
* Branko Vukelic
* Brian Sierakowski
* Brian Wickman
* Carl Scharenberg
* Damien Degois
* David Buxton
* Duane Johnson
* fcamel
* Frank Murphy
* Frederic Junod
* goldfaber3012
* Greg Milby
* gstein
* Ian Davis
* Itamar Nabriski
* Iuri de Silvio
* Jaimie Murdock
* Jeff Nichols
* Jeremy Kelley
* joegester
* Johannes Krampf
* Jonas Haag
* Joshua Roesslein
* Judson Neer
* Karl
* Kevin Zuber
* Kraken
* Kyle Fritz
* m35
* Marcos Neves
* masklinn
* Michael Labbe
* Michael Soulier
* `reddit <https://reddit.com/r/python>`_
* Nicolas Vanhoren
* Oz N Tiram
* Robert Rollins
* rogererens
* rwxrwx
* Santiago Gala
* Sean M. Collins
* Sebastian Wollrath
* Seth
* Sigurd Høgsbro
* Stuart Rackham
* Sun Ning
* Tomás A. Schertel
* Tristan Zajonc
* voltron
* Wieland Hoffmann
* zombat
* Thiago Avelino


================================================
FILE: LICENSE
================================================
Copyright (c) 2009-2025, Marcel Hellkamp.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


================================================
FILE: Makefile
================================================
VERSION = $(shell ./bottle.py --version)
VENV = build/venv

.PHONY: test
test: venv
	$(VENV)/bin/pytest

.PHONY: coverage
coverage: venv
	$(VENV)/bin/pytest -q --cov=bottle --cov-report=term --cov-report=html:build/htmlcov

.PHONY: build
build: test
	$(VENV)/bin/python -m build

.PHONY: docs
docs: venv
	$(VENV)/bin/sphinx-build -b html docs build/docs/html/;

.PHONY: watchdocs
watchdocs: venv
	-mkdir -p build/docs/watch/
	$(VENV)/bin/sphinx-autobuild -b html docs build/docs/watch/;

.PHONY: version
version:
	@echo $(VERSION)

.PHONY: venv
venv: $(VENV)/.installed
$(VENV)/.installed: Makefile pyproject.toml
	test -d $(VENV) || python3 -m venv $(VENV)
	$(VENV)/bin/python3 -m ensurepip
	$(VENV)/bin/pip install -q -U pip
	$(VENV)/bin/pip install -q -e .[dev,docs]
	touch $(VENV)/.installed

.PHONY: venv
clean:
	rm -rf $(VENV) build/ dist/ MANIFEST .coverage .pytest_cache bottle.egg-info 2>/dev/null || true
	find . -name '__pycache__' -exec rm -rf {} +
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +
	find . -name '._*' -exec rm -f {} +


================================================
FILE: README.rst
================================================
.. image:: https://bottlepy.org/docs/dev/_static/logo_nav.png
  :target: https://bottlepy.org/
  :alt: Bottle Logo
  :align: right

.. image:: https://github.com/bottlepy/bottle/workflows/Tests/badge.svg
    :target: https://github.com/bottlepy/bottle/workflows/Tests
    :alt: Tests Status

.. image:: https://img.shields.io/pypi/v/bottle.svg
    :target: https://pypi.python.org/pypi/bottle/
    :alt: Latest Version

.. image:: https://img.shields.io/pypi/l/bottle.svg
    :target: https://pypi.python.org/pypi/bottle/
    :alt: License

.. _Python: https://python.org/
.. _mako: https://www.makotemplates.org/
.. _cheetah: https://www.cheetahtemplate.org/
.. _jinja2: https://jinja.palletsprojects.com/

.. _WSGI: https://peps.python.org/pep-3333/
.. _gunicorn: https://gunicorn.org/
.. _paste: https://pythonpaste.readthedocs.io/
.. _cheroot: https://cheroot.cherrypy.dev/

============================
Bottle: Python Web Framework
============================

Bottle is a fast, simple and lightweight WSGI_ micro web-framework for Python_. It is distributed as a single file module and has no dependencies other than the `Python Standard Library <https://docs.python.org/library/>`_.

* **Routing:** Requests to function-call mapping with support for clean and dynamic URLs.
* **Templates:** Fast `built-in template engine <https://bottlepy.org/docs/dev/tutorial.html#tutorial-templates>`_ and support for mako_, jinja2_ and cheetah_ templates.
* **Utilities:** Convenient access to form data, file uploads, cookies, headers and other HTTP features.
* **Server:** Built-in development server and ready-to-use adapters for a wide range of WSGI_ capable HTTP server (e.g. gunicorn_, paste_ or cheroot_).


Homepage and documentation: https://bottlepy.org


Example: "Hello World" in a bottle
----------------------------------

.. code-block:: python

  from bottle import route, run, template

  @route('/hello/<name>')
  def index(name):
      return template('<b>Hello {{name}}</b>!', name=name)

  run(host='localhost', port=8080)

Run this script or paste it into a Python console, then point your browser to `<http://localhost:8080/hello/world>`_. That's it.


Download and Install
--------------------

.. __: https://github.com/bottlepy/bottle/raw/master/bottle.py

Install the latest stable release with ``pip install bottle`` or download `bottle.py`__ (unstable) into your project directory. There are no hard dependencies other than the Python standard library.

License
-------

.. __: https://github.com/bottlepy/bottle/raw/master/LICENSE

Code and documentation are available according to the MIT License (see LICENSE__).

The Bottle logo however is *NOT* covered by that license. It is allowed to use the logo as a link to the bottle homepage or in direct context with the unmodified library. In all other cases, please ask first.


================================================
FILE: bottle.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with URL parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file and with no dependencies other than the
Python Standard Library.

Homepage and documentation: https://bottlepy.org/

Copyright (c) 2009-2025, Marcel Hellkamp.
License: MIT (see LICENSE for details)
"""

import sys

__author__ = 'Marcel Hellkamp'
__version__ = '0.14-dev'
__license__ = 'MIT'

###############################################################################
# Command-line interface ######################################################
###############################################################################
# INFO: Some server adapters need to monkey-patch std-lib modules before they
# are imported. This is why some of the command-line handling is done here, but
# the actual call to _main() is at the end of the file.


def _cli_parse(args):  # pragma: no coverage
    from argparse import ArgumentParser

    parser = ArgumentParser(prog=args[0], usage="%(prog)s [options] package.module:app")
    opt = parser.add_argument
    opt("--version", action="store_true", help="show version number.")
    opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.")
    opt("-s", "--server", default='wsgiref', help="use SERVER as backend.")
    opt("-p", "--plugin", action="append", help="install additional plugin/s.")
    opt("-c", "--conf", action="append", metavar="FILE",
        help="load config values from FILE.")
    opt("-C", "--param", action="append", metavar="NAME=VALUE",
        help="override config values.")
    opt("--debug", action="store_true", help="start server in debug mode.")
    opt("--reload", action="store_true", help="auto-reload on file changes.")
    opt('app', help='WSGI app entry point.', nargs='?')

    cli_args = parser.parse_args(args[1:])

    return cli_args, parser


def _cli_patch(cli_args):  # pragma: no coverage
    parsed_args, _ = _cli_parse(cli_args)
    opts = parsed_args
    if opts.server:
        if opts.server.startswith('gevent'):
            import gevent.monkey
            gevent.monkey.patch_all()
        elif opts.server.startswith('eventlet'):
            import eventlet
            eventlet.monkey_patch()


if __name__ == '__main__':
    _cli_patch(sys.argv)

###############################################################################
# Imports and Helpers used everywhere else #####################################
###############################################################################

import base64, calendar, email.utils, functools, hmac, itertools, \
    mimetypes, os, re, tempfile, threading, time, warnings, weakref, hashlib

from types import FunctionType
from datetime import date as datedate, datetime, timedelta
from tempfile import NamedTemporaryFile
from traceback import format_exc, print_exc
from unicodedata import normalize

try:
    from ujson import dumps as json_dumps, loads as json_lds
except ImportError:
    from json import dumps as json_dumps, loads as json_lds

py = sys.version_info

import http.client as httplib
import _thread as thread
from urllib.parse import urljoin, SplitResult as UrlSplitResult
from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote
from http.cookies import SimpleCookie, Morsel, CookieError
from collections.abc import MutableMapping as DictMixin
from types import ModuleType as new_module
import pickle
from io import BytesIO
import configparser
from datetime import timezone
UTC = timezone.utc
import inspect

json_loads = lambda s: json_lds(touni(s))
callable = lambda x: hasattr(x, '__call__')
_UNSET = object()


def _wsgi_recode(src):
    """ Translate a PEP-3333 latin1-string to utf8+surrogateescape """
    if src.isascii():
        return src
    return src.encode('latin1').decode('utf8', 'surrogateescape')


def _raise(*a):
    raise a[0](a[1]).with_traceback(a[2])


# Some helpers for string/byte handling
def tob(s, enc='utf8'):
    if isinstance(s, str):
        return s.encode(enc)
    return b'' if s is None else bytes(s)


def touni(s, enc='utf8', err='strict'):
    if isinstance(s, (bytes, bytearray)):
        return str(s, enc, err)
    return "" if s is None else str(s)


def _stderr(*args):
    try:
        print(*args, file=sys.stderr)
    except (IOError, AttributeError):
        pass  # Some environments do not allow printing (mod_wsgi)


# A bug in functools causes it to break if the wrapper is an instance method
def update_wrapper(wrapper, wrapped, *a, **ka):
    try:
        functools.update_wrapper(wrapper, wrapped, *a, **ka)
    except AttributeError:
        pass


# These helpers are used at module level and need to be defined first.
# And yes, I know PEP-8, but sometimes a lower-case classname makes more sense.


def depr(major, minor, cause, fix, stacklevel=3):
    text = "Use of feature or API deprecated since Bottle-%d.%d\n"\
        "Cause: %s\n"\
        "Fix: %s\n" % (major, minor, cause, fix)
    if DEBUG == 'strict':
        raise DeprecationWarning(text)
    warnings.warn(text, DeprecationWarning, stacklevel=stacklevel)
    return DeprecationWarning(text)


def makelist(data):  # This is just too handy
    if isinstance(data, (tuple, list, set, dict)):
        return list(data)
    elif data:
        return [data]
    else:
        return []


class DictProperty:
    """ Property that maps to a key in a local dict-like attribute. """

    def __init__(self, attr, key=None, read_only=False):
        self.attr, self.key, self.read_only = attr, key, read_only

    def __call__(self, func):
        functools.update_wrapper(self, func, updated=[])
        self.getter, self.key = func, self.key or func.__name__
        return self

    def __get__(self, obj, cls):
        if obj is None: return self
        key, storage = self.key, getattr(obj, self.attr)
        if key not in storage: storage[key] = self.getter(obj)
        return storage[key]

    def __set__(self, obj, value):
        if self.read_only: raise AttributeError("Read-Only property.")
        getattr(obj, self.attr)[self.key] = value

    def __delete__(self, obj):
        if self.read_only: raise AttributeError("Read-Only property.")
        del getattr(obj, self.attr)[self.key]


class cached_property:
    """ A property that is only computed once per instance and then replaces
        itself with an ordinary attribute. Deleting the attribute resets the
        property. """

    def __init__(self, func):
        update_wrapper(self, func)
        self.func = func

    def __get__(self, obj, cls):
        if obj is None: return self
        value = obj.__dict__[self.func.__name__] = self.func(obj)
        return value


class lazy_attribute:
    """ A property that caches itself to the class object. """

    def __init__(self, func):
        functools.update_wrapper(self, func, updated=[])
        self.getter = func

    def __get__(self, obj, cls):
        value = self.getter(cls)
        setattr(cls, self.__name__, value)
        return value


###############################################################################
# Exceptions and Events #######################################################
###############################################################################


class BottleException(Exception):
    """ A base class for exceptions used by bottle. """
    pass

###############################################################################
# Routing ######################################################################
###############################################################################


class RouteError(BottleException):
    """ This is a base class for all routing related exceptions """


class RouterUnknownModeError(RouteError):
    pass


class RouteSyntaxError(RouteError):
    """ The route parser found something not supported by this router. """


class RouteBuildError(RouteError):
    """ The route could not be built. """


def _re_flatten(p):
    """ Turn all capturing groups in a regular expression pattern into
        non-capturing groups. """
    if '(' not in p:
        return p
    return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))', lambda m: m.group(0) if
                  len(m.group(1)) % 2 else m.group(1) + '(?:', p)


class Router:
    """ A Router is an ordered collection of route->target pairs. It is used to
        efficiently match WSGI requests against a number of routes and return
        the first target that satisfies the request. The target may be anything,
        usually a string, ID or callable object. A route consists of a path-rule
        and a HTTP method.

        The path-rule is either a static path (e.g. `/contact`) or a dynamic
        path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax
        and details on the matching order are described in docs:`routing`.
    """

    default_pattern = '[^/]+'
    default_filter = 're'

    #: The current CPython regexp implementation does not allow more
    #: than 99 matching groups per regular expression.
    _MAX_GROUPS_PER_PATTERN = 99

    def __init__(self, strict=False):
        self.rules = []  # All rules in order
        self._groups = {}  # index of regexes to find them in dyna_routes
        self.builder = {}  # Data structure for the url builder
        self.static = {}  # Search structure for static routes
        self.dyna_routes = {}
        self.dyna_regexes = {}  # Search structure for dynamic routes
        #: If true, static routes are no longer checked first.
        self.strict_order = strict
        self.filters = {
            're': lambda conf: (_re_flatten(conf or self.default_pattern),
                                None, None),
            'int': lambda conf: (r'-?\d+', int, lambda x: str(int(x))),
            'float': lambda conf: (r'-?[\d.]+', float, lambda x: str(float(x))),
            'path': lambda conf: (r'.+?', None, None)
        }

    def add_filter(self, name, func):
        """ Add a filter. The provided function is called with the configuration
        string as parameter and must return a (regexp, to_python, to_url) tuple.
        The first element is a string, the last two are callables or None. """
        self.filters[name] = func

    rule_syntax = re.compile('(\\\\*)'
        '(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)'
          '|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)'
            '(?::((?:\\\\.|[^\\\\>])+)?)?)?>))')

    def _itertokens(self, rule):
        offset, prefix = 0, ''
        for match in self.rule_syntax.finditer(rule):
            prefix += rule[offset:match.start()]
            g = match.groups()
            if g[2] is not None:
                depr(0, 13, "Use of old route syntax.",
                            "Use <name> instead of :name in routes.",
                            stacklevel=4)
            if len(g[0]) % 2:  # Escaped wildcard
                prefix += match.group(0)[len(g[0]):]
                offset = match.end()
                continue
            if prefix:
                yield prefix, None, None
            name, filtr, conf = g[4:7] if g[2] is None else g[1:4]
            yield name, filtr or 'default', conf or None
            offset, prefix = match.end(), ''
        if offset <= len(rule) or prefix:
            yield prefix + rule[offset:], None, None

    def add(self, rule, method, target, name=None):
        """ Add a new rule or replace the target for an existing rule. """
        anons = []  # Generated names of anonymous wildcards
        keys = []  # Names of keys
        pattern = ''  # Regular expression pattern with named groups
        filters = []  # Lists of wildcard input filters
        builder = []  # Data structure for the URL builder
        is_static = True

        for key, mode, conf in self._itertokens(rule):
            if mode:
                is_static = False
                if mode == 'default': mode = self.default_filter
                mask, in_filter, out_filter = self.filters[mode](conf)
                if not key:
                    key = 'anon%d' % len(anons)
                    anons.append(key)
                pattern += '(?P<%s>%s)' % (key, mask)
                keys.append(key)
                if in_filter: filters.append((key, in_filter))
                builder.append((key, out_filter or str))
            elif key:
                pattern += re.escape(key)
                builder.append((None, key))

        self.builder[rule] = builder
        if name: self.builder[name] = builder

        if is_static and not self.strict_order:
            self.static.setdefault(method, {})
            self.static[method][self.build(rule)] = (target, None)
            return

        try:
            re_pattern = re.compile('^(%s)$' % pattern)
            re_match = re_pattern.match
        except re.error as e:
            raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, e))

        if filters:

            def getargs(path):
                url_args = re_match(path).groupdict()
                for name, wildcard_filter in filters:
                    try:
                        url_args[name] = wildcard_filter(url_args[name])
                    except ValueError:
                        raise HTTPError(400, 'Path has wrong format.')
                for key in anons:
                    del url_args[key]
                return url_args
        elif re_pattern.groupindex:

            def getargs(path):
                url_args = re_match(path).groupdict()
                for key in anons:
                    del url_args[key]
                return url_args
        else:
            getargs = None

        flatpat = _re_flatten(pattern)
        whole_rule = (rule, flatpat, target, getargs)

        if (flatpat, method) in self._groups:
            if DEBUG:
                msg = 'Route <%s %s> overwrites a previously defined route'
                warnings.warn(msg % (method, rule), RuntimeWarning, stacklevel=3)
            self.dyna_routes[method][
                self._groups[flatpat, method]] = whole_rule
        else:
            self.dyna_routes.setdefault(method, []).append(whole_rule)
            self._groups[flatpat, method] = len(self.dyna_routes[method]) - 1

        self._compile(method)

    def _compile(self, method):
        all_rules = self.dyna_routes[method]
        comborules = self.dyna_regexes[method] = []
        maxgroups = self._MAX_GROUPS_PER_PATTERN
        for x in range(0, len(all_rules), maxgroups):
            some = all_rules[x:x + maxgroups]
            combined = (flatpat for (_, flatpat, _, _) in some)
            combined = '|'.join('(^%s$)' % flatpat for flatpat in combined)
            combined = re.compile(combined).match
            rules = [(target, getargs) for (_, _, target, getargs) in some]
            comborules.append((combined, rules))

    def build(self, _name, *anons, **query):
        """ Build an URL by filling the wildcards in a rule. """
        builder = self.builder.get(_name)
        if not builder:
            raise RouteBuildError("No route with that name.", _name)
        try:
            for i, value in enumerate(anons):
                query['anon%d' % i] = value
            url = ''.join([f(query.pop(n)) if n else f for (n, f) in builder])
            return url if not query else url + '?' + urlencode(query, doseq=True)
        except KeyError as E:
            raise RouteBuildError('Missing URL argument: %r' % E.args[0])

    def match(self, environ):
        """ Return a (target, url_args) tuple or raise HTTPError(400/404/405). """
        verb = environ['REQUEST_METHOD'].upper()
        path = environ['PATH_INFO'] or '/'

        methods = ('PROXY', 'HEAD', 'GET', 'ANY') if verb == 'HEAD' else ('PROXY', verb, 'ANY')

        for method in methods:
            if method in self.static and path in self.static[method]:
                target, getargs = self.static[method][path]
                return target, getargs(path) if getargs else {}
            elif method in self.dyna_regexes:
                for combined, rules in self.dyna_regexes[method]:
                    match = combined(path)
                    if match:
                        target, getargs = rules[match.lastindex - 1]
                        return target, getargs(path) if getargs else {}

        # No matching route found. Collect alternative methods for 405 response
        allowed = set([])
        nocheck = set(methods)
        for method in set(self.static) - nocheck:
            if path in self.static[method]:
                allowed.add(method)
        for method in set(self.dyna_regexes) - allowed - nocheck:
            for combined, rules in self.dyna_regexes[method]:
                match = combined(path)
                if match:
                    allowed.add(method)
        if allowed:
            allow_header = ",".join(sorted(allowed))
            raise HTTPError(405, "Method not allowed.", Allow=allow_header)

        # No matching route and no alternative method found. We give up
        raise HTTPError(404, "Not found: " + repr(path))


class Route:
    """ This class wraps a route callback along with route specific metadata and
        configuration and applies Plugins on demand. It is also responsible for
        turning an URL path rule into a regular expression usable by the Router.
    """

    def __init__(self, app, rule, method, callback,
                 name=None,
                 plugins=None,
                 skiplist=None, **config):
        #: The application this route is installed to.
        self.app = app
        #: The path-rule string (e.g. ``/wiki/<page>``).
        self.rule = rule
        #: The HTTP method as a string (e.g. ``GET``).
        self.method = method
        #: The original callback with no plugins applied. Useful for introspection.
        self.callback = callback
        #: The name of the route (if specified) or ``None``.
        self.name = name or None
        #: A list of route-specific plugins (see :meth:`Bottle.route`).
        self.plugins = plugins or []
        #: A list of plugins to not apply to this route (see :meth:`Bottle.route`).
        self.skiplist = skiplist or []
        #: Additional keyword arguments passed to the :meth:`Bottle.route`
        #: decorator are stored in this dictionary. Used for route-specific
        #: plugin configuration and meta-data.
        self.config = app.config._make_overlay()
        self.config.load_dict(config)

    @cached_property
    def call(self):
        """ The route callback with all plugins applied. This property is
            created on demand and then cached to speed up subsequent requests."""
        return self._make_callback()

    def reset(self):
        """ Forget any cached values. The next time :attr:`call` is accessed,
            all plugins are re-applied. """
        self.__dict__.pop('call', None)

    def prepare(self):
        """ Do all on-demand work immediately (useful for debugging)."""
        self.call

    def all_plugins(self):
        """ Yield all Plugins affecting this route. """
        unique = set()
        for p in reversed(self.app.plugins + self.plugins):
            if True in self.skiplist: break
            name = getattr(p, 'name', False)
            if name and (name in self.skiplist or name in unique): continue
            if p in self.skiplist or type(p) in self.skiplist: continue
            if name: unique.add(name)
            yield p

    def _make_callback(self):
        callback = self.callback
        for plugin in self.all_plugins():
            if hasattr(plugin, 'apply'):
                callback = plugin.apply(callback, self)
            else:
                callback = plugin(callback)
            if callback is not self.callback:
                update_wrapper(callback, self.callback)
        return callback

    def get_undecorated_callback(self):
        """ Return the callback. If the callback is a decorated function, try to
            recover the original function. """
        func = self.callback
        while True:
            if getattr(func, '__wrapped__', False):
                func = func.__wrapped__
            elif getattr(func, '__func__', False):
                func = func.__func__
            elif getattr(func, '__closure__', False):
                depr(0, 14, "Decorated callback without __wrapped__",
                     "When applying decorators to route callbacks, make sure"
                     " the decorator uses @functools.wraps or update_wrapper."
                     " This warning may also trigger if you reference callables"
                     " from a nonlocal scope.")
                cells_values = (cell.cell_contents for cell in func.__closure__)
                isfunc = lambda x: isinstance(x, FunctionType) or hasattr(x, '__call__')
                func = next(filter(isfunc, cells_values), func)
            else:
                return func

    def get_callback_args(self):
        """ Return a list of argument names the callback (most likely) accepts
            as keyword arguments. If the callback is a decorated function, try
            to recover the original function before inspection. """
        sig = inspect.signature(self.get_undecorated_callback())
        return [p.name for p in sig.parameters.values() if p.kind in (
            p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY
        )]

    def get_config(self, key, default=None):
        """ Lookup a config field and return its value, first checking the
            route.config, then route.app.config."""
        depr(0, 13, "Route.get_config() is deprecated.",
                    "The Route.config property already includes values from the"
                    " application config for missing keys. Access it directly.")
        return self.config.get(key, default)

    def __repr__(self):
        cb = self.get_undecorated_callback()
        return '<%s %s -> %s:%s>' % (
            self.method, self.rule, cb.__module__, getattr(cb, '__name__', '?')
        )

###############################################################################
# Application Object ###########################################################
###############################################################################


class Bottle:
    """ Each Bottle object represents a single, distinct web application and
        consists of routes, callbacks, plugins, resources and configuration.
        Instances are callable WSGI applications.

        :param catchall: If true (default), handle all exceptions. Turn off to
                         let debugging middleware handle exceptions.
    """

    @lazy_attribute
    def _global_config(cls):
        cfg = ConfigDict()
        cfg.meta_set('catchall', 'validate', bool)
        return cfg

    def __init__(self, **kwargs):
        #: A :class:`ConfigDict` for app specific configuration.
        self.config = self._global_config._make_overlay()
        self.config._add_change_listener(
            functools.partial(self.trigger_hook, 'config'))

        self.config.update({
            "catchall": True
        })

        if kwargs.get('catchall') is False:
            depr(0, 13, "Bottle(catchall) keyword argument.",
                        "The 'catchall' setting is now part of the app "
                        "configuration. Fix: `app.config['catchall'] = False`")
            self.config['catchall'] = False
        if kwargs.get('autojson') is False:
            depr(0, 13, "Bottle(autojson) keyword argument.",
                 "The 'autojson' setting is now part of the app "
                 "configuration. Fix: `app.config['json.enable'] = False`")
            self.config['json.enable'] = False

        self._mounts = []

        #: A :class:`ResourceManager` for application files
        self.resources = ResourceManager()

        self.routes = []  # List of installed :class:`Route` instances.
        self.router = Router()  # Maps requests to :class:`Route` instances.
        self.error_handler = {}

        # Core plugins
        self.plugins = []  # List of installed plugins.
        self.install(JSONPlugin())
        self.install(TemplatePlugin())

    #: If true, most exceptions are caught and returned as :exc:`HTTPError`
    catchall = DictProperty('config', 'catchall')

    __hook_names = 'before_request', 'after_request', 'app_reset', 'config'
    __hook_reversed = {'after_request'}

    @cached_property
    def _hooks(self):
        return dict((name, []) for name in self.__hook_names)

    def add_hook(self, name, func):
        """ Attach a callback to a hook. Three hooks are currently implemented:

            before_request
                Executed once before each request. The request context is
                available, but no routing has happened yet.
            after_request
                Executed once after each request regardless of its outcome.
            app_reset
                Called whenever :meth:`Bottle.reset` is called.
        """
        if name in self.__hook_reversed:
            self._hooks[name].insert(0, func)
        else:
            self._hooks[name].append(func)

    def remove_hook(self, name, func):
        """ Remove a callback from a hook. """
        if name in self._hooks and func in self._hooks[name]:
            self._hooks[name].remove(func)
            return True

    def trigger_hook(self, __name, *args, **kwargs):
        """ Trigger a hook and return a list of results. """
        return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]

    def hook(self, name):
        """ Return a decorator that attaches a callback to a hook. See
            :meth:`add_hook` for details."""

        def decorator(func):
            self.add_hook(name, func)
            return func

        return decorator

    def _mount_wsgi(self, prefix, app, **options):
        segments = [p for p in prefix.split('/') if p]
        if not segments:
            raise ValueError('WSGI applications cannot be mounted to "/".')
        path_depth = len(segments)

        def mountpoint_wrapper():
            try:
                request.path_shift(path_depth)
                rs = HTTPResponse([])

                def start_response(status, headerlist, exc_info=None):
                    if exc_info:
                        _raise(*exc_info)
                    status = _wsgi_recode(status)
                    headerlist = [(k, _wsgi_recode(v)) for (k, v) in headerlist]
                    rs.status = status
                    for name, value in headerlist:
                        rs.add_header(name, value)
                    return rs.body.append

                body = app(request.environ, start_response)
                rs.body = itertools.chain(rs.body, body) if rs.body else body
                return rs
            finally:
                request.path_shift(-path_depth)

        options.setdefault('skip', True)
        options.setdefault('method', 'PROXY')
        options.setdefault('mountpoint', {'prefix': prefix, 'target': app})
        options['callback'] = mountpoint_wrapper

        self.route('/%s/<:re:.*>' % '/'.join(segments), **options)
        if not prefix.endswith('/'):
            self.route('/' + '/'.join(segments), **options)

    def _mount_app(self, prefix, app, **options):
        if app in self._mounts or '_mount.app' in app.config:
            depr(0, 13, "Application mounted multiple times. Falling back to WSGI mount.",
                 "Clone application before mounting to a different location.")
            return self._mount_wsgi(prefix, app, **options)

        if options:
            depr(0, 13, "Unsupported mount options. Falling back to WSGI mount.",
                 "Do not specify any route options when mounting bottle application.")
            return self._mount_wsgi(prefix, app, **options)

        if not prefix.endswith("/"):
            depr(0, 13, "Prefix must end in '/'. Falling back to WSGI mount.",
                 "Consider adding an explicit redirect from '/prefix' to '/prefix/' in the parent application.")
            return self._mount_wsgi(prefix, app, **options)

        self._mounts.append(app)
        app.config['_mount.prefix'] = prefix
        app.config['_mount.app'] = self
        for route in app.routes:
            route.rule = prefix + route.rule.lstrip('/')
            self.add_route(route)

    def mount(self, prefix, app, **options):
        """ Mount an application (:class:`Bottle` or plain WSGI) to a specific
            URL prefix. Example::

                parent_app.mount('/prefix/', child_app)

            :param prefix: path prefix or `mount-point`.
            :param app: an instance of :class:`Bottle` or a WSGI application.

            Plugins from the parent application are not applied to the routes
            of the mounted child application. If you need plugins in the child
            application, install them separately.

            While it is possible to use path wildcards within the prefix path
            (:class:`Bottle` childs only), it is highly discouraged.

            The prefix path must end with a slash. If you want to access the
            root of the child application via `/prefix` in addition to
            `/prefix/`, consider adding a route with a 307 redirect to the
            parent application.
        """

        if not prefix.startswith('/'):
            raise ValueError("Prefix must start with '/'")

        if isinstance(app, Bottle):
            return self._mount_app(prefix, app, **options)
        else:
            return self._mount_wsgi(prefix, app, **options)

    def merge(self, routes):
        """ Merge the routes of another :class:`Bottle` application or a list of
            :class:`Route` objects into this application. The routes keep their
            'owner', meaning that the :data:`Route.app` attribute is not
            changed. """
        if isinstance(routes, Bottle):
            routes = routes.routes
        for route in routes:
            self.add_route(route)

    def install(self, plugin):
        """ Add a plugin to the list of plugins and prepare it for being
            applied to all routes of this application. A plugin may be a simple
            decorator or an object that implements the :class:`Plugin` API.
        """
        if hasattr(plugin, 'setup'): plugin.setup(self)
        if not callable(plugin) and not hasattr(plugin, 'apply'):
            raise TypeError("Plugins must be callable or implement .apply()")
        self.plugins.append(plugin)
        self.reset()
        return plugin

    def uninstall(self, plugin):
        """ Uninstall plugins. Pass an instance to remove a specific plugin, a type
            object to remove all plugins that match that type, a string to remove
            all plugins with a matching ``name`` attribute or ``True`` to remove all
            plugins. Return the list of removed plugins. """
        removed, remove = [], plugin
        for i, plugin in list(enumerate(self.plugins))[::-1]:
            if remove is True or remove is plugin or remove is type(plugin) \
               or getattr(plugin, 'name', True) == remove:
                removed.append(plugin)
                del self.plugins[i]
                if hasattr(plugin, 'close'): plugin.close()
        if removed: self.reset()
        return removed

    def reset(self, route=None):
        """ Reset all routes (force plugins to be re-applied) and clear all
            caches. If an ID or route object is given, only that specific route
            is affected. """
        if route is None: routes = self.routes
        elif isinstance(route, Route): routes = [route]
        else: routes = [self.routes[route]]
        for route in routes:
            route.reset()
        if DEBUG:
            for route in routes:
                route.prepare()
        self.trigger_hook('app_reset')

    def close(self):
        """ Close the application and all installed plugins. """
        for plugin in self.plugins:
            if hasattr(plugin, 'close'): plugin.close()

    def run(self, **kwargs):
        """ Calls :func:`run` with the same parameters. """
        run(self, **kwargs)

    def match(self, environ):
        """ Search for a matching route and return a (:class:`Route`, urlargs)
            tuple. The second value is a dictionary with parameters extracted
            from the URL. Raise :exc:`HTTPError` (404/405) on a non-match."""
        return self.router.match(environ)

    def get_url(self, routename, **kargs):
        """ Return a string that matches a named route """
        scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
        location = self.router.build(routename, **kargs).lstrip('/')
        return urljoin(urljoin('/', scriptname), location)

    def add_route(self, route):
        """ Add a route object, but do not change the :data:`Route.app`
            attribute."""
        self.routes.append(route)
        self.router.add(route.rule, route.method, route, name=route.name)
        if DEBUG: route.prepare()

    def route(self,
              path=None,
              method='GET',
              callback=None,
              name=None,
              apply=None,
              skip=None, **config):
        """ A decorator to bind a function to a request URL. Example::

                @app.route('/hello/<name>')
                def hello(name):
                    return 'Hello %s' % name

            The ``<name>`` part is a wildcard. See :class:`Router` for syntax
            details.

            :param path: Request path or a list of paths to listen to. If no
              path is specified, it is automatically generated from the
              signature of the function.
            :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
              methods to listen to. (default: `GET`)
            :param callback: An optional shortcut to avoid the decorator
              syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
            :param name: The name for this route. (default: None)
            :param apply: A decorator or plugin or a list of plugins. These are
              applied to the route callback in addition to installed plugins.
            :param skip: A list of plugins, plugin classes or names. Matching
              plugins are not installed to this route. ``True`` skips all.

            Any additional keyword arguments are stored as route-specific
            configuration and passed to plugins (see :meth:`Plugin.apply`).
        """
        if callable(path): path, callback = None, path
        plugins = makelist(apply)
        skiplist = makelist(skip)

        def decorator(callback):
            if isinstance(callback, str):
                callback = load(callback) # type: Callable
            for rule in makelist(path) or yieldroutes(callback):
                for verb in makelist(method):
                    verb = verb.upper()
                    route = Route(self, rule, verb, callback,
                                  name=name,
                                  plugins=plugins,
                                  skiplist=skiplist, **config)
                    self.add_route(route)
            return callback

        return decorator(callback) if callback else decorator

    def get(self, path=None, method='GET', **options):
        """ Equals :meth:`route`. """
        return self.route(path, method, **options)

    def post(self, path=None, method='POST', **options):
        """ Equals :meth:`route` with a ``POST`` method parameter. """
        return self.route(path, method, **options)

    def put(self, path=None, method='PUT', **options):
        """ Equals :meth:`route` with a ``PUT`` method parameter. """
        return self.route(path, method, **options)

    def delete(self, path=None, method='DELETE', **options):
        """ Equals :meth:`route` with a ``DELETE`` method parameter. """
        return self.route(path, method, **options)

    def patch(self, path=None, method='PATCH', **options):
        """ Equals :meth:`route` with a ``PATCH`` method parameter. """
        return self.route(path, method, **options)

    def error(self, code=500, callback=None):
        """ Register an output handler for a HTTP error code. Can
            be used as a decorator or called directly ::

                def error_handler_500(error):
                    return 'error_handler_500'

                app.error(code=500, callback=error_handler_500)

                @app.error(404)
                def error_handler_404(error):
                    return 'error_handler_404'

        """

        def decorator(callback):
            if isinstance(callback, str): callback = load(callback)
            self.error_handler[int(code)] = callback
            return callback

        return decorator(callback) if callback else decorator

    def default_error_handler(self, res):
        return tob(template(ERROR_PAGE_TEMPLATE, e=res, template_settings=dict(name='__ERROR_PAGE_TEMPLATE')))

    def _handle(self, environ):
        path = environ['bottle.raw_path'] = environ['PATH_INFO']
        environ['PATH_INFO'] = _wsgi_recode(path)

        environ['bottle.app'] = self
        request.bind(environ)
        response.bind()
        out = None

        try:
            try:
                self.trigger_hook('before_request')
                route, args = self.router.match(environ)
                environ['route.handle'] = route
                environ['bottle.route'] = route
                environ['route.url_args'] = args
                out = route.call(**args)
            except HTTPResponse as E:
                out = E
            finally:
                if isinstance(out, HTTPResponse):
                    out.apply(response)
                try:
                    self.trigger_hook('after_request')
                except HTTPResponse as E:
                    out = E
                    out.apply(response)
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception as E:
            _try_close(out)
            if not self.catchall: raise
            stacktrace = format_exc()
            environ['wsgi.errors'].write(stacktrace)
            environ['wsgi.errors'].flush()
            environ['bottle.exc_info'] = sys.exc_info()
            out = HTTPError(500, "Internal Server Error", E, stacktrace)
            out.apply(response)

        return out

    def _cast(self, out, peek=None):
        """ Try to convert the parameter into something WSGI compatible and set
            correct HTTP headers when possible.
            Support: False, bytes/bytearray, str, dict, HTTPResponse, HTTPError,
            file-like, iterable of bytes/bytearray or str instances.
        """

        # Empty output is done here
        if not out:
            if 'Content-Length' not in response:
                response['Content-Length'] = 0
            return []
        # Join lists of byte or unicode strings. Mixed lists are NOT supported
        if isinstance(out, (tuple, list)) and isinstance(out[0], (bytes, str)):
            out = out[0][0:0].join(out)  # b'abc'[0:0] -> b''
        # Encode unicode strings
        if isinstance(out, str):
            out = out.encode(response.charset)
        # Byte Strings are just returned
        if isinstance(out, bytes):
            if 'Content-Length' not in response:
                response['Content-Length'] = len(out)
            return [out]
        # HTTPError or HTTPException (recursive, because they may wrap anything)
        # TODO: Handle these explicitly in handle() or make them iterable.
        if isinstance(out, HTTPError):
            out.apply(response)
            out = self.error_handler.get(out.status_code,
                                         self.default_error_handler)(out)
            return self._cast(out)
        if isinstance(out, HTTPResponse):
            out.apply(response)
            return self._cast(out.body)

        # File-like objects.
        if hasattr(out, 'read'):
            if 'wsgi.file_wrapper' in request.environ:
                return request.environ['wsgi.file_wrapper'](out)
            elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
                return WSGIFileWrapper(out)

        # Handle Iterables. We peek into them to detect their inner type.
        try:
            iout = iter(out)
            first = next(iout)
            while not first:
                first = next(iout)
        except StopIteration:
            _try_close(out)
            return self._cast('')
        except HTTPResponse as E:
            first = E
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception as error:
            _try_close(out)
            if not self.catchall: raise
            first = HTTPError(500, 'Unhandled exception', error, format_exc())

        # These are the inner types allowed in iterator or generator objects.
        if isinstance(first, HTTPResponse):
            return self._cast(first)
        elif isinstance(first, bytes):
            new_iter = itertools.chain([first], iout)
        elif isinstance(first, str):
            encoder = lambda x: x.encode(response.charset)
            new_iter = map(encoder, itertools.chain([first], iout))
        else:
            _try_close(out)
            msg = 'Unsupported response type: %s' % type(first)
            return self._cast(HTTPError(500, msg))
        if hasattr(out, 'close'):
            new_iter = _closeiter(new_iter, out.close)
        return new_iter

    def wsgi(self, environ, start_response):
        """ The bottle WSGI-interface. """
        out = None
        try:
            out = self._cast(self._handle(environ))
            # rfc2616 section 4.3
            if response._status_code in (100, 101, 204, 304) \
               or environ['REQUEST_METHOD'] == 'HEAD':
                if hasattr(out, 'close'): out.close()
                out = []
            exc_info = environ.get('bottle.exc_info')
            if exc_info is not None:
                del environ['bottle.exc_info']
            start_response(response._wsgi_status_line(), response.headerlist, exc_info)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception as E:
            _try_close(out)
            if not self.catchall: raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % html_escape(environ.get('PATH_INFO', '/'))
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
                       '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
                       % (html_escape(repr(E)), html_escape(format_exc()))
            environ['wsgi.errors'].write(err)
            environ['wsgi.errors'].flush()
            headers = [('Content-Type', 'text/html; charset=UTF-8')]
            start_response('500 INTERNAL SERVER ERROR', headers, sys.exc_info())
            return [tob(err)]

    def __call__(self, environ, start_response):
        """ Each instance of :class:'Bottle' is a WSGI application. """
        return self.wsgi(environ, start_response)

    def __enter__(self):
        """ Use this application as default for all module-level shortcuts. """
        default_app.push(self)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        default_app.pop()

    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise AttributeError("Attribute %s already defined. Plugin conflict?" % name)
        object.__setattr__(self, name, value)

###############################################################################
# HTTP and WSGI Tools ##########################################################
###############################################################################


class BaseRequest:
    """ A wrapper for WSGI environment dictionaries that adds a lot of
        convenient access methods and properties. Most of them are read-only.

        Adding new attributes to a request actually adds them to the environ
        dictionary (as 'bottle.request.ext.<name>'). This is the recommended
        way to store and access request-specific data.
    """

    __slots__ = ('environ', )

    #: Maximum size of memory buffer for :attr:`body` in bytes.
    MEMFILE_MAX = 102400

    def __init__(self, environ=None):
        """ Wrap a WSGI environ dictionary. """
        #: The wrapped WSGI environ dictionary. This is the only real attribute.
        #: All other attributes actually are read-only properties.
        self.environ = {} if environ is None else environ
        self.environ['bottle.request'] = self

    @DictProperty('environ', 'bottle.app', read_only=True)
    def app(self):
        """ Bottle application handling this request. """
        raise RuntimeError('This request is not connected to an application.')

    @DictProperty('environ', 'bottle.route', read_only=True)
    def route(self):
        """ The bottle :class:`Route` object that matches this request. """
        raise RuntimeError('This request is not connected to a route.')

    @DictProperty('environ', 'route.url_args', read_only=True)
    def url_args(self):
        """ The arguments extracted from the URL. """
        raise RuntimeError('This request is not connected to a route.')

    @property
    def path(self):
        """ The value of ``PATH_INFO`` with exactly one prefixed slash (to fix
            broken clients and avoid the "empty path" edge case). """
        return '/' + self.environ.get('PATH_INFO', '').lstrip('/')

    @property
    def method(self):
        """ The ``REQUEST_METHOD`` value as an uppercase string. """
        return self.environ.get('REQUEST_METHOD', 'GET').upper()

    @DictProperty('environ', 'bottle.request.headers', read_only=True)
    def headers(self):
        """ A :class:`WSGIHeaderDict` that provides case-insensitive access to
            HTTP request headers. """
        return WSGIHeaderDict(self.environ)

    def get_header(self, name, default=None):
        """ Return the value of a request header, or a given default value. """
        return self.headers.get(name, default)

    @DictProperty('environ', 'bottle.request.cookies', read_only=True)
    def cookies(self):
        """ Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
            decoded. Use :meth:`get_cookie` if you expect signed cookies. """
        cookie_header = _wsgi_recode(self.environ.get('HTTP_COOKIE', ''))
        cookies = SimpleCookie(cookie_header).values()
        return FormsDict((c.key, c.value) for c in cookies)

    def get_cookie(self, key, default=None, secret=None, digestmod=hashlib.sha256):
        """ Return the content of a cookie. To read a `Signed Cookie`, the
            `secret` must match the one used to create the cookie (see
            :meth:`Response.set_cookie <BaseResponse.set_cookie>`). If anything goes wrong (missing
            cookie or wrong signature), return a default value. """
        value = self.cookies.get(key)
        if secret:
            # See BaseResponse.set_cookie for details on signed cookies.
            if value and value.startswith('!') and '?' in value:
                sig, msg = map(tob, value[1:].split('?', 1))
                hash = hmac.new(tob(secret), msg, digestmod=digestmod).digest()
                if _lscmp(sig, base64.b64encode(hash)):
                    dst = pickle.loads(base64.b64decode(msg))
                    if dst and dst[0] == key:
                        return dst[1]
            return default
        return value or default

    @DictProperty('environ', 'bottle.request.query', read_only=True)
    def query(self):
        """ The :attr:`query_string` parsed into a :class:`FormsDict`. These
            values are sometimes called "URL arguments" or "GET parameters", but
            not to be confused with "URL wildcards" as they are provided by the
            :class:`Router`. """
        get = self.environ['bottle.get'] = FormsDict()
        pairs = _parse_qsl(self.environ.get('QUERY_STRING', ''), 'utf8')
        for key, value in pairs:
            get[key] = value
        return get

    @DictProperty('environ', 'bottle.request.forms', read_only=True)
    def forms(self):
        """ Form values parsed from an `url-encoded` or `multipart/form-data`
            encoded POST or PUT request body. The result is returned as a
            :class:`FormsDict`. All keys and values are strings. File uploads
            are stored separately in :attr:`files`. """
        forms = FormsDict()
        for name, item in self.POST.allitems():
            if not isinstance(item, FileUpload):
                forms[name] = item
        return forms

    @DictProperty('environ', 'bottle.request.params', read_only=True)
    def params(self):
        """ A :class:`FormsDict` with the combined values of :attr:`query` and
            :attr:`forms`. File uploads are stored in :attr:`files`. """
        params = FormsDict()
        for key, value in self.query.allitems():
            params[key] = value
        for key, value in self.forms.allitems():
            params[key] = value
        return params

    @DictProperty('environ', 'bottle.request.files', read_only=True)
    def files(self):
        """ File uploads parsed from `multipart/form-data` encoded POST or PUT
            request body. The values are instances of :class:`FileUpload`.

        """
        files = FormsDict()
        for name, item in self.POST.allitems():
            if isinstance(item, FileUpload):
                files[name] = item
        return files

    @DictProperty('environ', 'bottle.request.json', read_only=True)
    def json(self):
        """ If the ``Content-Type`` header is ``application/json`` or
            ``application/json-rpc``, this property holds the parsed content
            of the request body. Only requests smaller than :attr:`MEMFILE_MAX`
            are processed to avoid memory exhaustion.
            Invalid JSON raises a 400 error response.
        """
        ctype = self.environ.get('CONTENT_TYPE', '').lower().split(';')[0]
        if ctype in ('application/json', 'application/json-rpc'):
            b = self._get_body_string(self.MEMFILE_MAX)
            if not b:
                return None
            try:
                return json_loads(b)
            except (ValueError, TypeError) as err:
                raise HTTPError(400, 'Invalid JSON', exception=err)
        return None

    def _iter_body(self, read, bufsize):
        maxread = max(0, self.content_length)
        while maxread:
            part = read(min(maxread, bufsize))
            if not part: break
            yield part
            maxread -= len(part)

    @staticmethod
    def _iter_chunked(read, bufsize):
        err = HTTPError(400, 'Error while parsing chunked transfer body.')
        rn, sem, bs = b'\r\n', b';', b''
        while True:
            header = read(1)
            while header[-2:] != rn:
                c = read(1)
                header += c
                if not c: raise err
                if len(header) > bufsize: raise err
            size, _, _ = header.partition(sem)
            try:
                maxread = int(size.strip(), 16)
            except ValueError:
                raise err
            if maxread == 0: break
            buff = bs
            while maxread > 0:
                if not buff:
                    buff = read(min(maxread, bufsize))
                part, buff = buff[:maxread], buff[maxread:]
                if not part: raise err
                yield part
                maxread -= len(part)
            if read(2) != rn:
                raise err

    @DictProperty('environ', 'bottle.request.body', read_only=True)
    def _body(self):
        try:
            read_func = self.environ['wsgi.input'].read
        except KeyError:
            self.environ['wsgi.input'] = BytesIO()
            return self.environ['wsgi.input']
        body_iter = self._iter_chunked if self.chunked else self._iter_body
        body, body_size, is_temp_file = BytesIO(), 0, False
        for part in body_iter(read_func, self.MEMFILE_MAX):
            body.write(part)
            body_size += len(part)
            if not is_temp_file and body_size > self.MEMFILE_MAX:
                body, tmp = NamedTemporaryFile(mode='w+b'), body
                body.write(tmp.getvalue())
                del tmp
                is_temp_file = True
        self.environ['wsgi.input'] = body
        body.seek(0)
        return body

    def _get_body_string(self, maxread):
        """ Read body into a string. Raise HTTPError(413) on requests that are
            too large. """
        if self.content_length > maxread:
            raise HTTPError(413, 'Request entity too large')
        data = self.body.read(maxread + 1)
        if len(data) > maxread:
            raise HTTPError(413, 'Request entity too large')
        return data

    @property
    def body(self):
        """ The HTTP request body as a seek-able file-like object. Depending on
            :attr:`MEMFILE_MAX`, this is either a temporary file or a
            :class:`io.BytesIO` instance. Accessing this property for the first
            time reads and replaces the ``wsgi.input`` environ variable.
            Subsequent accesses just do a `seek(0)` on the file object. """
        self._body.seek(0)
        return self._body

    @property
    def chunked(self):
        """ True if Chunked transfer encoding was. """
        return 'chunked' in self.environ.get(
            'HTTP_TRANSFER_ENCODING', '').lower()

    #: An alias for :attr:`query`.
    GET = query

    @DictProperty('environ', 'bottle.request.post', read_only=True)
    def POST(self):
        """ The values of :attr:`forms` and :attr:`files` combined into a single
            :class:`FormsDict`. Values are either strings (form values) or
            instances of :class:`FileUpload`.
        """
        post = FormsDict()
        content_type = self.environ.get('CONTENT_TYPE', '')
        content_type, options = _parse_http_header(content_type)[0]
        # We default to application/x-www-form-urlencoded for everything that
        # is not multipart and take the fast path (also: 3.1 workaround)
        if not content_type.startswith('multipart/'):
            body = self._get_body_string(self.MEMFILE_MAX).decode('utf8', 'surrogateescape')
            for key, value in _parse_qsl(body, 'utf8'):
                post[key] = value
            return post

        charset = options.get("charset", "utf8")
        boundary = options.get("boundary")
        if not boundary:
            raise MultipartError("Invalid content type header, missing boundary")
        parser = _MultipartParser(self.body, boundary, self.content_length,
            mem_limit=self.MEMFILE_MAX, memfile_limit=self.MEMFILE_MAX,
            charset=charset)

        for part in parser.parse():
            if not part.filename and part.is_buffered():
                post[part.name] = part.value
            else:
                post[part.name] = FileUpload(part.file, part.name,
                                            part.filename, part.headerlist)

        return post

    @property
    def url(self):
        """ The full request URI including hostname and scheme. If your app
            lives behind a reverse proxy or load balancer and you get confusing
            results, make sure that the ``X-Forwarded-Host`` header is set
            correctly. """
        return self.urlparts.geturl()

    @DictProperty('environ', 'bottle.request.urlparts', read_only=True)
    def urlparts(self):
        """ The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
            The tuple contains (scheme, host, path, query_string and fragment),
            but the fragment is always empty because it is not visible to the
            server. """
        env = self.environ
        http = env.get('HTTP_X_FORWARDED_PROTO') or env.get('wsgi.url_scheme', 'http')
        host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')
        if not host:
            # HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients.
            host = env.get('SERVER_NAME', '127.0.0.1')
            port = env.get('SERVER_PORT')
            if port and port != ('80' if http == 'http' else '443'):
                host += ':' + port
        path = urlquote(self.fullpath)
        return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '')

    @property
    def fullpath(self):
        """ Request path including :attr:`script_name` (if present). """
        return urljoin(self.script_name, self.path.lstrip('/'))

    @property
    def query_string(self):
        """ The raw :attr:`query` part of the URL (everything in between ``?``
            and ``#``) as a string. """
        return self.environ.get('QUERY_STRING', '')

    @property
    def script_name(self):
        """ The initial portion of the URL's `path` that was removed by a higher
            level (server or routing middleware) before the application was
            called. This script path is returned with leading and tailing
            slashes. """
        script_name = self.environ.get('SCRIPT_NAME', '').strip('/')
        return '/' + script_name + '/' if script_name else '/'

    def path_shift(self, shift=1):
        """ Shift path segments from :attr:`path` to :attr:`script_name` and
            vice versa.

           :param shift: The number of path segments to shift. May be negative
                         to change the shift direction. (default: 1)
        """
        script, path = path_shift(self.environ.get('SCRIPT_NAME', '/'), self.path, shift)
        self['SCRIPT_NAME'], self['PATH_INFO'] = script, path

    @property
    def content_length(self):
        """ The request body length as an integer. The client is responsible to
            set this header. Otherwise, the real length of the body is unknown
            and -1 is returned. In this case, :attr:`body` will be empty. """
        return int(self.environ.get('CONTENT_LENGTH') or -1)

    @property
    def content_type(self):
        """ The Content-Type header as a lowercase-string (default: empty). """
        return self.environ.get('CONTENT_TYPE', '').lower()

    @property
    def is_xhr(self):
        """ True if the request was triggered by a XMLHttpRequest. This only
            works with JavaScript libraries that support the `X-Requested-With`
            header (most of the popular libraries do). """
        requested_with = self.environ.get('HTTP_X_REQUESTED_WITH', '')
        return requested_with.lower() == 'xmlhttprequest'

    @property
    def is_ajax(self):
        """ Alias for :attr:`is_xhr`. "Ajax" is not the right term. """
        return self.is_xhr

    @property
    def auth(self):
        """ HTTP authentication data as a (user, password) tuple. This
            implementation currently supports basic (not digest) authentication
            only. If the authentication happened at a higher level (e.g. in the
            front web-server or a middleware), the password field is None, but
            the user field is looked up from the ``REMOTE_USER`` environ
            variable. On any errors, None is returned. """
        basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION', ''))
        if basic: return basic
        ruser = self.environ.get('REMOTE_USER')
        if ruser: return (ruser, None)
        return None

    @property
    def remote_route(self):
        """ A list of all IPs that were involved in this request, starting with
            the client IP and followed by zero or more proxies. This does only
            work if all proxies support the ```X-Forwarded-For`` header. Note
            that this information can be forged by malicious clients. """
        proxy = self.environ.get('HTTP_X_FORWARDED_FOR')
        if proxy: return [ip.strip() for ip in proxy.split(',')]
        remote = self.environ.get('REMOTE_ADDR')
        return [remote] if remote else []

    @property
    def remote_addr(self):
        """ The client IP as a string. Note that this information can be forged
            by malicious clients. """
        route = self.remote_route
        return route[0] if route else None

    def copy(self):
        """ Return a new :class:`Request` with a shallow :attr:`environ` copy. """
        return Request(self.environ.copy())

    def get(self, key, default=None):
        return self.environ.get(key, default)

    def __getitem__(self, key):
        return self.environ[key]

    def __delitem__(self, key):
        self[key] = ""
        del (self.environ[key])

    def __iter__(self):
        return iter(self.environ)

    def __len__(self):
        return len(self.environ)

    def keys(self):
        return self.environ.keys()

    def __setitem__(self, key, value):
        """ Change an environ value and clear all caches that depend on it. """

        if self.environ.get('bottle.request.readonly'):
            raise KeyError('The environ dictionary is read-only.')

        self.environ[key] = value
        todelete = ()

        if key == 'wsgi.input':
            todelete = ('body', 'forms', 'files', 'params', 'post', 'json')
        elif key == 'QUERY_STRING':
            todelete = ('query', 'params')
        elif key.startswith('HTTP_'):
            todelete = ('headers', 'cookies')

        for key in todelete:
            self.environ.pop('bottle.request.' + key, None)

    def __repr__(self):
        return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url)

    def __getattr__(self, name):
        """ Search in self.environ for additional user defined attributes. """
        try:
            var = self.environ['bottle.request.ext.%s' % name]
            return var.__get__(self) if hasattr(var, '__get__') else var
        except KeyError:
            raise AttributeError('Attribute %r not defined.' % name)

    def __setattr__(self, name, value):
        """ Define new attributes that are local to the bound request environment. """
        if name == 'environ': return object.__setattr__(self, name, value)
        key = 'bottle.request.ext.%s' % name
        if hasattr(self, name):
            raise AttributeError("Attribute already defined: %s" % name)
        self.environ[key] = value

    def __delattr__(self, name):
        try:
            del self.environ['bottle.request.ext.%s' % name]
        except KeyError:
            raise AttributeError("Attribute not defined: %s" % name)


def _hkey(key):
    key = touni(key)
    if '\n' in key or '\r' in key or '\0' in key:
        raise ValueError("Header names must not contain control characters: %r" % key)
    return key.title().replace('_', '-')


def _hval(value):
    value = touni(value)
    if '\n' in value or '\r' in value or '\0' in value:
        raise ValueError("Header value must not contain control characters: %r" % value)
    return value


class HeaderProperty:
    def __init__(self, name, reader=None, writer=None, default=''):
        self.name, self.default = name, default
        self.reader, self.writer = reader, writer
        self.__doc__ = 'Current value of the %r header.' % name.title()

    def __get__(self, obj, _):
        if obj is None: return self
        value = obj.get_header(self.name, self.default)
        return self.reader(value) if self.reader else value

    def __set__(self, obj, value):
        obj[self.name] = self.writer(value) if self.writer else value

    def __delete__(self, obj):
        del obj[self.name]


class BaseResponse:
    """ Storage class for a response body as well as headers and cookies.

        This class does support dict-like case-insensitive item-access to
        headers, but is NOT a dict. Most notably, iterating over a response
        yields parts of the body and not the headers.
    """

    default_status = 200
    default_content_type = 'text/html; charset=UTF-8'

    # Header denylist for specific response codes
    # (rfc2616 section 10.2.3 and 10.3.5)
    bad_headers = {
        204: frozenset(('Content-Type', 'Content-Length')),
        304: frozenset(('Allow', 'Content-Encoding', 'Content-Language',
                  'Content-Length', 'Content-Range', 'Content-Type',
                  'Content-Md5', 'Last-Modified'))
    }

    def __init__(self, body='', status=None, headers=None, **more_headers):
        """ Create a new response object.

        :param body: The response body as one of the supported types.
        :param status: Either an HTTP status code (e.g. 200) or a status line
                       including the reason phrase (e.g. '200 OK').
        :param headers: A dictionary or a list of name-value pairs.

        Additional keyword arguments are added to the list of headers.
        Underscores in the header name are replaced with dashes.
        """
        self._cookies = None
        self._headers = {}
        self.body = body
        self.status = status or self.default_status
        if headers:
            if isinstance(headers, dict):
                headers = headers.items()
            for name, value in headers:
                self.add_header(name, value)
        if more_headers:
            for name, value in more_headers.items():
                self.add_header(name, value)

    def copy(self, cls=None):
        """ Returns a copy of self. """
        cls = cls or BaseResponse
        assert issubclass(cls, BaseResponse)
        copy = cls()
        copy.status = self.status
        copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
        if self._cookies:
            cookies = copy._cookies = SimpleCookie()
            for k, v in self._cookies.items():
                cookies[k] = v.value
                cookies[k].update(v)  # also copy cookie attributes
        return copy

    def __iter__(self):
        return iter(self.body)

    def close(self):
        if hasattr(self.body, 'close'):
            self.body.close()

    @property
    def status_line(self):
        """ The HTTP status line as a string (e.g. ``404 Not Found``)."""
        return self._status_line

    @property
    def status_code(self):
        """ The HTTP status code as an integer (e.g. 404)."""
        return self._status_code

    def _set_status(self, status):
        if isinstance(status, int):
            code, status = status, _HTTP_STATUS_LINES.get(status)
        elif ' ' in status:
            if '\n' in status or '\r' in status or '\0' in status:
                raise ValueError('Status line must not include control chars.')
            status = status.strip()
            code = int(status.split()[0])
        else:
            raise ValueError('String status line without a reason phrase.')
        if not 100 <= code <= 999:
            raise ValueError('Status code out of range.')
        self._status_code = code
        self._status_line = str(status or ('%d Unknown' % code))

    def _get_status(self):
        return self._status_line

    status = property(
        _get_status, _set_status, None,
        ''' A writeable property to change the HTTP response status. It accepts
            either a numeric code (100-999) or a string with a custom reason
            phrase (e.g. "404 Brain not found"). Both :data:`status_line` and
            :data:`status_code` are updated accordingly. The return value is
            always a status string. ''')
    del _get_status, _set_status

    @property
    def headers(self):
        """ An instance of :class:`HeaderDict`, a case-insensitive dict-like
            view on the response headers. """
        hdict = HeaderDict()
        hdict.dict = self._headers
        return hdict

    def __contains__(self, name):
        return _hkey(name) in self._headers

    def __delitem__(self, name):
        del self._headers[_hkey(name)]

    def __getitem__(self, name):
        return self._headers[_hkey(name)][-1]

    def __setitem__(self, name, value):
        self._headers[_hkey(name)] = [_hval(value)]

    def get_header(self, name, default=None):
        """ Return the value of a previously defined header. If there is no
            header with that name, return a default value. """
        return self._headers.get(_hkey(name), [default])[-1]

    def set_header(self, name, value):
        """ Create a new response header, replacing any previously defined
            headers with the same name. """
        self._headers[_hkey(name)] = [_hval(value)]

    def add_header(self, name, value):
        """ Add an additional response header, not removing duplicates. """
        self._headers.setdefault(_hkey(name), []).append(_hval(value))

    def iter_headers(self):
        """ Yield (header, value) tuples, skipping headers that are not
            allowed with the current response status code. """
        return self.headerlist

    def _wsgi_status_line(self):
        """ WSGI conform status line (latin1-encodeable) """
        return self._status_line.encode('utf8', 'surrogateescape').decode('latin1')

    @property
    def headerlist(self):
        """ WSGI conform list of (header, value) tuples. """
        out = []
        headers = list(self._headers.items())
        if 'Content-Type' not in self._headers:
            headers.append(('Content-Type', [self.default_content_type]))
        if self._status_code in self.bad_headers:
            bad_headers = self.bad_headers[self._status_code]
            headers = [h for h in headers if h[0] not in bad_headers]
        out += [(name, val) for (name, vals) in headers for val in vals]
        if self._cookies:
            for c in self._cookies.values():
                out.append(('Set-Cookie', _hval(c.OutputString())))
        out = [(k, v.encode('utf8', 'surrogateescape').decode('latin1')) for (k, v) in out]
        return out

    content_type = HeaderProperty('Content-Type')
    content_length = HeaderProperty('Content-Length', reader=int, default=-1)
    expires = HeaderProperty(
        'Expires',
        reader=lambda x: datetime.fromtimestamp(parse_date(x), UTC),
        writer=lambda x: http_date(x))

    @property
    def charset(self, default='UTF-8'):
        """ Return the charset specified in the content-type header (default: utf8). """
        if 'charset=' in self.content_type:
            return self.content_type.split('charset=')[-1].split(';')[0].strip()
        return default

    def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha256, **options):
        """ Create a new cookie or replace an old one. If the `secret` parameter is
            set, create a `Signed Cookie` (described below).

            :param name: the name of the cookie.
            :param value: the value of the cookie.
            :param secret: a signature key required for signed cookies.

            Additionally, this method accepts all RFC 2109 attributes that are
            supported by :class:`cookie.Morsel`, including:

            :param maxage: maximum age in seconds. (default: None)
            :param expires: a datetime object or UNIX timestamp. (default: None)
            :param domain: the domain that is allowed to read the cookie.
              (default: current domain)
            :param path: limits the cookie to a given path (default: current path)
            :param secure: limit the cookie to HTTPS connections (default: off).
            :param httponly: prevents client-side javascript to read this cookie
              (default: off, requires Python 2.6 or newer).
            :param samesite: Control or disable third-party use for this cookie.
              Possible values: `lax`, `strict` or `none` (default).

            If neither `expires` nor `maxage` is set (default), the cookie will
            expire at the end of the browser session (as soon as the browser
            window is closed).

            Signed cookies may store any pickle-able object and are
            cryptographically signed to prevent manipulation. Keep in mind that
            cookies are limited to 4kb in most browsers.

            Warning: Pickle is a potentially dangerous format. If an attacker
            gains access to the secret key, he could forge cookies that execute
            code on server side if unpickled. Using pickle is discouraged and
            support for it will be removed in later versions of bottle.

            Warning: Signed cookies are not encrypted (the client can still see
            the content) and not copy-protected (the client can restore an old
            cookie). The main intention is to make pickling and unpickling
            save, not to store secret information at client side.
        """
        if not self._cookies:
            self._cookies = SimpleCookie()

        # Monkey-patch Cookie lib to support 'SameSite' parameter
        # https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1
        if py < (3, 8, 0):
            Morsel._reserved.setdefault('samesite', 'SameSite')

        if secret:
            if not isinstance(value, str):
                depr(0, 13, "Pickling of arbitrary objects into cookies is "
                            "deprecated.", "Only store strings in cookies. "
                            "JSON strings are fine, too.")
            encoded = base64.b64encode(pickle.dumps([name, value], -1))
            sig = base64.b64encode(hmac.new(tob(secret), encoded,
                                            digestmod=digestmod).digest())
            value = touni(b'!' + sig + b'?' + encoded)
        elif not isinstance(value, str):
            raise TypeError('Secret key required for non-string cookies.')

        # Cookie size plus options must not exceed 4kb.
        if len(name) + len(value) > 3800:
            raise ValueError('Content does not fit into a cookie.')

        self._cookies[name] = value

        for key, value in options.items():
            if key in ('max_age', 'maxage'):  # 'maxage' variant added in 0.13
                key = 'max-age'
                if isinstance(value, timedelta):
                    value = value.seconds + value.days * 24 * 3600
            if key == 'expires':
                value = http_date(value)
            if key in ('same_site', 'samesite'):  # 'samesite' variant added in 0.13
                key, value = 'samesite', (value or "none").lower()
                if value not in ('lax', 'strict', 'none'):
                    raise CookieError("Invalid value for SameSite")
            if key in ('secure', 'httponly') and not value:
                continue
            self._cookies[name][key] = value

    def delete_cookie(self, key, **kwargs):
        """ Delete a cookie. Be sure to use the same `domain` and `path`
            settings as used to create the cookie. """
        kwargs['max_age'] = -1
        kwargs['expires'] = 0
        self.set_cookie(key, '', **kwargs)

    def __repr__(self):
        out = ''
        for name, value in self.headerlist:
            out += '%s: %s\n' % (name.title(), value.strip())
        return out


def _local_property():
    ls = threading.local()

    def fget(_):
        try:
            return ls.var
        except AttributeError:
            raise RuntimeError("Request context not initialized.")

    def fset(_, value):
        ls.var = value

    def fdel(_):
        del ls.var

    return property(fget, fset, fdel, 'Thread-local property')


class LocalRequest(BaseRequest):
    """ A thread-local subclass of :class:`BaseRequest` with a different
        set of attributes for each thread. There is usually only one global
        instance of this class (:data:`request`). If accessed during a
        request/response cycle, this instance always refers to the *current*
        request (even on a multithreaded server). """
    bind = BaseRequest.__init__
    environ = _local_property()


class LocalResponse(BaseResponse):
    """ A thread-local subclass of :class:`BaseResponse` with a different
        set of attributes for each thread. There is usually only one global
        instance of this class (:data:`response`). Its attributes are used
        to build the HTTP response at the end of the request/response cycle.
    """
    bind = BaseResponse.__init__
    _status_line = _local_property()
    _status_code = _local_property()
    _cookies = _local_property()
    _headers = _local_property()
    body = _local_property()


Request = BaseRequest
Response = BaseResponse


class HTTPResponse(Response, BottleException):
    """ A subclass of :class:`Response` that can be raised or returned from request
        handlers to short-curcuit request processing and override changes made to the
        global :data:`request` object. This bypasses error handlers, even if the status
        code indicates an error. Return or raise :class:`HTTPError` to trigger error
        handlers.
    """

    def __init__(self, body='', status=None, headers=None, **more_headers):
        super(HTTPResponse, self).__init__(body, status, headers, **more_headers)

    def apply(self, other):
        """ Copy the state of this response to a different :class:`Response` object. """
        other._status_code = self._status_code
        other._status_line = self._status_line
        other._headers = self._headers
        other._cookies = self._cookies
        other.body = self.body


class HTTPError(HTTPResponse):
    """ A subclass of :class:`HTTPResponse` that triggers error handlers. """

    default_status = 500

    def __init__(self,
                 status=None,
                 body=None,
                 exception=None,
                 traceback=None, **more_headers):
        self.exception = exception
        self.traceback = traceback
        super(HTTPError, self).__init__(body, status, **more_headers)

###############################################################################
# Plugins ######################################################################
###############################################################################


class PluginError(BottleException):
    pass


class JSONPlugin:
    name = 'json'
    api = 2

    def __init__(self, json_dumps=json_dumps):
        self.json_dumps = json_dumps

    def setup(self, app):
        app.config._define('json.enable', default=True, validate=bool,
                          help="Enable or disable automatic dict->json filter.")
        app.config._define('json.ascii', default=False, validate=bool,
                          help="Use only 7-bit ASCII characters in output.")
        app.config._define('json.indent', default=True, validate=bool,
                          help="Add whitespace to make json more readable.")
        app.config._define('json.dump_func', default=None,
                          help="If defined, use this function to transform"
                               " dict into json. The other options no longer"
                               " apply.")

    def apply(self, callback, route):
        dumps = self.json_dumps
        if not self.json_dumps: return callback

        @functools.wraps(callback)
        def wrapper(*a, **ka):
            try:
                rv = callback(*a, **ka)
            except HTTPResponse as resp:
                rv = resp

            if isinstance(rv, dict):
                # Attempt to serialize, raises exception on failure
                json_response = dumps(rv)
                # Set content type only if serialization successful
                response.content_type = 'application/json'
                return json_response
            elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
                rv.body = dumps(rv.body)
                rv.content_type = 'application/json'
            return rv

        return wrapper


class TemplatePlugin:
    """ This plugin applies the :func:`view` decorator to all routes with a
        `template` config parameter. If the parameter is a tuple, the second
        element must be a dict with additional options (e.g. `template_engine`)
        or default variables for the template. """
    name = 'template'
    api = 2

    def setup(self, app):
        app.tpl = self

    def apply(self, callback, route):
        conf = route.config.get('template')
        if isinstance(conf, (tuple, list)) and len(conf) == 2:
            return view(conf[0], **conf[1])(callback)
        elif isinstance(conf, str):
            return view(conf)(callback)
        else:
            return callback


#: Not a plugin, but part of the plugin API. TODO: Find a better place.
class _ImportRedirect:
    def __init__(self, name, impmask):
        """ Create a virtual package that redirects imports (see PEP 302). """
        self.name = name
        self.impmask = impmask
        self.module = sys.modules.setdefault(name, new_module(name))
        self.module.__dict__.update({
            '__file__': __file__,
            '__path__': [],
            '__all__': [],
            '__loader__': self
        })
        sys.meta_path.append(self)

    def find_spec(self, fullname, path, target=None):
        if '.' not in fullname: return
        if fullname.rsplit('.', 1)[0] != self.name: return
        from importlib.util import spec_from_loader
        return spec_from_loader(fullname, self)

    def find_module(self, fullname, path=None):
        if '.' not in fullname: return
        if fullname.rsplit('.', 1)[0] != self.name: return
        return self

    def create_module(self, spec):
        return self.load_module(spec.name)

    def exec_module(self, module):
        pass  # This probably breaks importlib.reload() :/

    def load_module(self, fullname):
        if fullname in sys.modules: return sys.modules[fullname]
        modname = fullname.rsplit('.', 1)[1]
        realname = self.impmask % modname
        __import__(realname)
        module = sys.modules[fullname] = sys.modules[realname]
        setattr(self.module, modname, module)
        module.__loader__ = self
        return module

###############################################################################
# Common Utilities #############################################################
###############################################################################


class MultiDict(DictMixin):
    """ This dict stores multiple values per key, but behaves exactly like a
        normal dict in that it returns only the newest value for any given key.
        There are special methods available to access the full list of values.
    """

    def __init__(self, *a, **k):
        self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items())

    def __len__(self):
        return len(self.dict)

    def __iter__(self):
        return iter(self.dict)

    def __contains__(self, key):
        return key in self.dict

    def __delitem__(self, key):
        del self.dict[key]

    def __getitem__(self, key):
        return self.dict[key][-1]

    def __setitem__(self, key, value):
        self.append(key, value)

    def keys(self):
        return self.dict.keys()

    def values(self):
        return (v[-1] for v in self.dict.values())

    def items(self):
        return ((k, v[-1]) for k, v in self.dict.items())

    def allitems(self):
        return ((k, v) for k, vl in self.dict.items() for v in vl)

    iterkeys = keys
    itervalues = values
    iteritems = items
    iterallitems = allitems

    def get(self, key, default=None, index=-1, type=None):
        """ Return the most recent value for a key.

            :param default: The default value to be returned if the key is not
                   present or the type conversion fails.
            :param index: An index for the list of available values.
            :param type: If defined, this callable is used to cast the value
                    into a specific type. Exception are suppressed and result in
                    the default value to be returned.
        """
        try:
            val = self.dict[key][index]
            return type(val) if type else val
        except Exception:
            pass
        return default

    def append(self, key, value):
        """ Add a new value to the list of values for this key. """
        self.dict.setdefault(key, []).append(value)

    def replace(self, key, value):
        """ Replace the list of values with a single value. """
        self.dict[key] = [value]

    def getall(self, key):
        """ Return a (possibly empty) list of values for a key. """
        return self.dict.get(key) or []

    #: Aliases for WTForms to mimic other multi-dict APIs (Django)
    getone = get
    getlist = getall


class FormsDict(MultiDict):
    """ This :class:`MultiDict` subclass is used to store request form data.
        Additionally to the normal dict-like item access methods, this container
        also supports attribute-like access to its values. Missing attributes
        default to an empty string.

        .. versionchanged:: 0.14
            All keys and values are now decoded as utf8 by default, item and
            attribute access will return the same string.
    """

    def decode(self, encoding=None):
        """ (deprecated) Starting with 0.13 all keys and values are already
            correctly decoded. """
        copy = FormsDict()
        for key, value in self.allitems():
            copy[key] = value
        return copy

    def getunicode(self, name, default=None, encoding=None):
        """ (deprecated) Return the value as a unicode string, or the default. """
        return self.get(name, default)

    def __getattr__(self, name, default=str()):
        # Without this guard, pickle generates a cryptic TypeError:
        if name.startswith('__') and name.endswith('__'):
            return super(FormsDict, self).__getattr__(name)
        return self.get(name, default=default)


class HeaderDict(MultiDict):
    """ A case-insensitive version of :class:`MultiDict` that defaults to
        replace the old value instead of appending it. """

    def __init__(self, *a, **ka):
        self.dict = {}
        if a or ka: self.update(*a, **ka)

    def __contains__(self, key):
        return _hkey(key) in self.dict

    def __delitem__(self, key):
        del self.dict[_hkey(key)]

    def __getitem__(self, key):
        return self.dict[_hkey(key)][-1]

    def __setitem__(self, key, value):
        self.dict[_hkey(key)] = [_hval(value)]

    def append(self, key, value):
        self.dict.setdefault(_hkey(key), []).append(_hval(value))

    def replace(self, key, value):
        self.dict[_hkey(key)] = [_hval(value)]

    def getall(self, key):
        return self.dict.get(_hkey(key)) or []

    def get(self, key, default=None, index=-1):
        return MultiDict.get(self, _hkey(key), default, index)

    def filter(self, names):
        for name in (_hkey(n) for n in names):
            if name in self.dict:
                del self.dict[name]


class WSGIHeaderDict(DictMixin):
    """ This dict-like class wraps a WSGI environ dict and provides convenient
        access to HTTP_* fields. Header names are case-insensitive and titled by default.
    """
    #: List of keys that do not have a ``HTTP_`` prefix.
    cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH')

    def __init__(self, environ):
        self.environ = environ

    def _ekey(self, key):
        """ Translate header field name to CGI/WSGI environ key. """
        key = key.replace('-', '_').upper()
        if key in self.cgikeys:
            return key
        return 'HTTP_' + key

    def raw(self, key, default=None):
        """ Return the header value as is (not utf8-translated). """
        return self.environ.get(self._ekey(key), default)

    def __getitem__(self, key):
        return _wsgi_recode(self.environ[self._ekey(key)])

    def __setitem__(self, key, value):
        raise TypeError("%s is read-only." % self.__class__)

    def __delitem__(self, key):
        raise TypeError("%s is read-only." % self.__class__)

    def __iter__(self):
        for key in self.environ:
            if key[:5] == 'HTTP_':
                yield _hkey(key[5:])
            elif key in self.cgikeys:
                yield _hkey(key)

    def keys(self):
        return [x for x in self]

    def __len__(self):
        return len(self.keys())

    def __contains__(self, key):
        return self._ekey(key) in self.environ


class ConfigDict(dict):
    """ A dict-like configuration storage with additional support for
        namespaces, validators, meta-data and overlays.

        This dict-like class is heavily optimized for read access.
        Read-only methods and item access should be as fast as a native dict.
    """

    __slots__ = ('_meta', '_change_listener', '_overlays', '_virtual_keys', '_source', '__weakref__')

    def __init__(self):
        self._meta = {}
        self._change_listener = []
        #: Weak references of overlays that need to be kept in sync.
        self._overlays = []
        #: Config that is the source for this overlay.
        self._source = None
        #: Keys of values copied from the source (values we do not own)
        self._virtual_keys = set()

    def load_module(self, name, squash=True):
        """Load values from a Python module.

           Import a python module by name and add all upper-case module-level
           variables to this config dict.

           :param name: Module name to import and load.
           :param squash: If true (default), nested dicts are assumed to
              represent namespaces and flattened (see :meth:`load_dict`).
        """
        config_obj = load(name)
        obj = {key: getattr(config_obj, key)
               for key in dir(config_obj) if key.isupper()}

        if squash:
            self.load_dict(obj)
        else:
            self.update(obj)
        return self

    def load_config(self, filename, **options):
        """ Load values from ``*.ini`` style config files using configparser.

            INI style sections (e.g. ``[section]``) are used as namespace for
            all keys within that section. Both section and key names may contain
            dots as namespace separators and are converted to lower-case.

            The special sections ``[bottle]`` and ``[ROOT]`` refer to the root
            namespace and the ``[DEFAULT]`` section defines default values for all
            other sections.

            :param filename: The path of a config file, or a list of paths.
            :param options: All keyword parameters are passed to the underlying
                :class:`python:configparser.ConfigParser` constructor call.

        """
        options.setdefault('allow_no_value', True)
        options.setdefault('interpolation', configparser.ExtendedInterpolation())
        conf = configparser.ConfigParser(**options)
        conf.read(filename)
        for section in conf.sections():
            for key in conf.options(section):
                value = conf.get(section, key)
                if section not in ('bottle', 'ROOT'):
                    key = section + '.' + key
                self[key.lower()] = value
        return self

    def load_dict(self, source, namespace=''):
        """ Load values from a dictionary structure. Nesting can be used to
            represent namespaces.

            >>> c = ConfigDict()
            >>> c.load_dict({'some': {'namespace': {'key': 'value'} } })
            {'some.namespace.key': 'value'}
        """
        for key, value in source.items():
            if isinstance(key, str):
                nskey = (namespace + '.' + key).strip('.')
                if isinstance(value, dict):
                    self.load_dict(value, namespace=nskey)
                else:
                    self[nskey] = value
            else:
                raise TypeError('Key has type %r (not a string)' % type(key))
        return self

    def update(self, *a, **ka):
        """ If the first parameter is a string, all keys are prefixed with this
            namespace. Apart from that it works just as the usual dict.update().

            >>> c = ConfigDict()
            >>> c.update('some.namespace', key='value')
        """
        prefix = ''
        if a and isinstance(a[0], str):
            prefix = a[0].strip('.') + '.'
            a = a[1:]
        for key, value in dict(*a, **ka).items():
            self[prefix + key] = value

    def setdefault(self, key, value=None):
        if key not in self:
            self[key] = value
        return self[key]

    def __setitem__(self, key, value):
        if not isinstance(key, str):
            raise TypeError('Key has type %r (not a string)' % type(key))

        self._virtual_keys.discard(key)

        value = self.meta_get(key, 'filter', lambda x: x)(value)
        if key in self and self[key] is value:
            return

        self._on_change(key, value)
        dict.__setitem__(self, key, value)

        for overlay in self._iter_overlays():
            overlay._set_virtual(key, value)

    def __delitem__(self, key):
        if key not in self:
            raise KeyError(key)
        if key in self._virtual_keys:
            raise KeyError("Virtual keys cannot be deleted: %s" % key)

        if self._source and key in self._source:
            # Not virtual, but present in source -> Restore virtual value
            dict.__delitem__(self, key)
            self._set_virtual(key, self._source[key])
        else:  # not virtual, not present in source. This is OUR value
            self._on_change(key, None)
            dict.__delitem__(self, key)
            for overlay in self._iter_overlays():
                overlay._delete_virtual(key)

    def _set_virtual(self, key, value):
        """ Recursively set or update virtual keys. """
        if key in self and key not in self._virtual_keys:
            return  # Do nothing for non-virtual keys.

        self._virtual_keys.add(key)
        if key in self and self[key] is not value:
            self._on_change(key, value)
        dict.__setitem__(self, key, value)
        for overlay in self._iter_overlays():
            overlay._set_virtual(key, value)

    def _delete_virtual(self, key):
        """ Recursively delete virtual entry. """
        if key not in self._virtual_keys:
            return  # Do nothing for non-virtual keys.

        if key in self:
            self._on_change(key, None)
        dict.__delitem__(self, key)
        self._virtual_keys.discard(key)
        for overlay in self._iter_overlays():
            overlay._delete_virtual(key)

    def _on_change(self, key, value):
        for cb in self._change_listener:
            if cb(self, key, value):
                return True

    def _add_change_listener(self, func):
        self._change_listener.append(func)
        return func

    def meta_get(self, key, metafield, default=None):
        """ Return the value of a meta field for a key. """
        return self._meta.get(key, {}).get(metafield, default)

    def meta_set(self, key, metafield, value):
        """ Set the meta field for a key to a new value.

            Meta-fields are shared between all members of an overlay tree.
        """
        self._meta.setdefault(key, {})[metafield] = value

    def meta_list(self, key):
        """ Return an iterable of meta field names defined for a key. """
        return self._meta.get(key, {}).keys()

    def _define(self, key, default=_UNSET, help=_UNSET, validate=_UNSET):
        """ (Unstable) Shortcut for plugins to define own config parameters. """
        if default is not _UNSET:
            self.setdefault(key, default)
        if help is not _UNSET:
            self.meta_set(key, 'help', help)
        if validate is not _UNSET:
            self.meta_set(key, 'validate', validate)

    def _iter_overlays(self):
        for ref in self._overlays:
            overlay = ref()
            if overlay is not None:
                yield overlay

    def _make_overlay(self):
        """ (Unstable) Create a new overlay that acts like a chained map: Values
            missing in the overlay are copied from the source map. Both maps
            share the same meta entries.

            Entries that were copied from the source are called 'virtual'. You
            can not delete virtual keys, but overwrite them, which turns them
            into non-virtual entries. Setting keys on an overlay never affects
            its source, but may affect any number of child overlays.

            Other than collections.ChainMap or most other implementations, this
            approach does not resolve missing keys on demand, but instead
            actively copies all values from the source to the overlay and keeps
            track of virtual and non-virtual keys internally. This removes any
            lookup-overhead. Read-access is as fast as a build-in dict for both
            virtual and non-virtual keys.

            Changes are propagated recursively and depth-first. A failing
            on-change handler in an overlay stops the propagation of virtual
            values and may result in an partly updated tree. Take extra care
            here and make sure that on-change handlers never fail.

            Used by Route.config
        """
        # Cleanup dead references
        self._overlays[:] = [ref for ref in self._overlays if ref() is not None]

        overlay = ConfigDict()
        overlay._meta = self._meta
        overlay._source = self
        self._overlays.append(weakref.ref(overlay))
        for key in self:
            overlay._set_virtual(key, self[key])
        return overlay


class AppStack(list):
    """ A stack-like list. Calling it returns the head of the stack. """

    def __call__(self):
        """ Return the current default application. """
        return self.default

    def push(self, value=None):
        """ Add a new :class:`Bottle` instance to the stack """
        if not isinstance(value, Bottle):
            value = Bottle()
        self.append(value)
        return value
    new_app = push

    @property
    def default(self):
        try:
            return self[-1]
        except IndexError:
            return self.push()


class WSGIFileWrapper:
    def __init__(self, fp, buffer_size=1024 * 64):
        self.fp, self.buffer_size = fp, buffer_size
        for attr in 'fileno', 'close', 'read', 'readlines', 'tell', 'seek':
            if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))

    def __iter__(self):
        buff, read = self.buffer_size, self.read
        part = read(buff)
        while part:
            yield part
            part = read(buff)


class _closeiter:
    """ This only exists to be able to attach a .close method to iterators that
        do not support attribute assignment (most of itertools). """

    def __init__(self, iterator, close=None):
        self.iterator = iterator
        self.close_callbacks = makelist(close)

    def __iter__(self):
        return iter(self.iterator)

    def close(self):
        for func in self.close_callbacks:
            func()


def _try_close(obj):
    """ Call obj.close() if present and ignore exceptions """
    try:
        if hasattr(obj, 'close'):
            obj.close()
    except Exception:
        pass


class ResourceManager:
    """ This class manages a list of search paths and helps to find and open
        application-bound resources (files).

        :param base: default value for :meth:`add_path` calls.
        :param opener: callable used to open resources.
        :param cachemode: controls which lookups are cached. One of 'all',
                         'found' or 'none'.
    """

    def __init__(self, base='./', opener=open, cachemode='all'):
        self.opener = opener
        self.base = base
        self.cachemode = cachemode

        #: A list of search paths. See :meth:`add_path` for details.
        self.path = []
        #: A cache for resolved paths. ``res.cache.clear()`` clears the cache.
        self.cache = {}

    def add_path(self, path, base=None, index=None, create=False):
        """ Add a new path to the list of search paths. Return False if the
            path does not exist.

            :param path: The new search path. Relative paths are turned into
                an absolute and normalized form. If the path looks like a file
                (not ending in `/`), the filename is stripped off.
            :param base: Path used to absolutize relative search paths.
                Defaults to :attr:`base` which defaults to ``os.getcwd()``.
            :param index: Position within the list of search paths. Defaults
                to last index (appends to the list).

            The `base` parameter makes it easy to reference files installed
            along with a python module or package::

                res.add_path('./resources/', __file__)
        """
        base = os.path.abspath(os.path.dirname(base or self.base))
        path = os.path.abspath(os.path.join(base, os.path.dirname(path)))
        path += os.sep
        if path in self.path:
            self.path.remove(path)
        if create and not os.path.isdir(path):
            os.makedirs(path)
        if index is None:
            self.path.append(path)
        else:
            self.path.insert(index, path)
        self.cache.clear()
        return os.path.exists(path)

    def __iter__(self):
        """ Iterate over all existing files in all registered paths. """
        search = self.path[:]
        while search:
            path = search.pop()
            if not os.path.isdir(path): continue
            for name in os.listdir(path):
                full = os.path.join(path, name)
                if os.path.isdir(full): search.append(full)
                else: yield full

    def lookup(self, name):
        """ Search for a resource and return an absolute file path, or `None`.

            The :attr:`path` list is searched in order. The first match is
            returned. Symlinks are followed. The result is cached to speed up
            future lookups. """
        if name not in self.cache or DEBUG:
            for path in self.path:
                fpath = os.path.join(path, name)
                if os.path.isfile(fpath):
                    if self.cachemode in ('all', 'found'):
                        self.cache[name] = fpath
                    return fpath
            if self.cachemode == 'all':
                self.cache[name] = None
        return self.cache[name]

    def open(self, name, mode='r', *args, **kwargs):
        """ Find a resource and return a file object, or raise IOError. """
        fname = self.lookup(name)
        if not fname: raise IOError("Resource %r not found." % name)
        return self.opener(fname, mode=mode, *args, **kwargs)


class FileUpload:
    def __init__(self, fileobj, name, filename, headers=None):
        """ Wrapper for a single file uploaded via ``multipart/form-data``. """
        #: Open file(-like) object (BytesIO buffer or temporary file)
        self.file = fileobj
        #: Name of the upload form field
        self.name = name
        #: Raw filename as sent by the client (may contain unsafe characters)
        self.raw_filename = filename
        #: A :class:`HeaderDict` with additional headers (e.g. content-type)
        self.headers = HeaderDict(headers) if headers else HeaderDict()

    content_type = HeaderProperty('Content-Type')
    content_length = HeaderProperty('Content-Length', reader=int, default=-1)

    def get_header(self, name, default=None):
        """ Return the value of a header within the multipart part. """
        return self.headers.get(name, default)

    @cached_property
    def filename(self):
        """ Name of the file on the client file system, but normalized to ensure
            file system compatibility. An empty filename is returned as 'empty'.

            Only ASCII letters, digits, dashes, underscores and dots are
            allowed in the final filename. Accents are removed, if possible.
            Whitespace is replaced by a single dash. Leading or tailing dots
            or dashes are removed. The filename is limited to 255 characters.
        """
        fname = self.raw_filename
        fname = normalize('NFKD', fname)
        fname = fname.encode('ASCII', 'ignore').decode('ASCII')
        fname = os.path.basename(fname.replace('\\', os.path.sep))
        fname = re.sub(r'[^a-zA-Z0-9-_.\s]', '', fname).strip()
        fname = re.sub(r'[-\s]+', '-', fname).strip('.-')
        return fname[:255] or 'empty'

    def _copy_file(self, fp, chunk_size=2 ** 16):
        read, write, offset = self.file.read, fp.write, self.file.tell()
        while 1:
            buf = read(chunk_size)
            if not buf: break
            write(buf)
        self.file.seek(offset)

    def save(self, destination, overwrite=False, chunk_size=2 ** 16):
        """ Save file to disk or copy its content to an open file(-like) object.
            If *destination* is a directory, :attr:`filename` is added to the
            path. Existing files are not overwritten by default (IOError).

            :param destination: File path, directory or file(-like) object.
            :param overwrite: If True, replace existing files. (default: False)
            :param chunk_size: Bytes to read at a time. (default: 64kb)
        """
        if isinstance(destination, str):  # Except file-likes here
            if os.path.isdir(destination):
                destination = os.path.join(destination, self.filename)
            if not overwrite and os.path.exists(destination):
                raise IOError('File exists.')
            with open(destination, 'wb') as fp:
                self._copy_file(fp, chunk_size)
        else:
            self._copy_file(destination, chunk_size)

###############################################################################
# Application Helper ###########################################################
###############################################################################


def abort(code=500, text='Unknown Error.'):
    """ Aborts execution and causes a HTTP error. """
    raise HTTPError(code, text)


def redirect(url, code=None):
    """ Aborts execution and causes a 303 or 302 redirect, depending on
        the HTTP protocol version. """
    if not code:
        code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
    res = response.copy(cls=HTTPResponse)
    res.status = code
    res.body = ""
    res.set_header('Location', urljoin(request.url, url))
    raise res


def _rangeiter(fp, offset, limit, bufsize=1024 * 1024):
    """ Yield chunks from a range in a file. """
    fp.seek(offset)
    while limit > 0:
        part = fp.read(min(limit, bufsize))
        if not part:
            break
        limit -= len(part)
        yield part


def static_file(filename, root,
                mimetype=True,
                download=False,
                charset='UTF-8',
                etag=None,
                headers=None):
    """ Open a file in a safe way and return an instance of :exc:`HTTPResponse`
        that can be sent back to the client.

        :param filename: Name or path of the file to send, relative to ``root``.
        :param root: Root path for file lookups. Should be an absolute directory
            path.
        :param mimetype: Provide the content-type header (default: guess from
            file extension)
        :param download: If True, ask the browser to open a `Save as...` dialog
            instead of opening the file with the associated program. You can
            specify a custom filename as a string. If not specified, the
            original filename is used (default: False).
        :param charset: The charset for files with a ``text/*`` mime-type.
            (default: UTF-8)
        :param etag: Provide a pre-computed ETag header. If set to ``False``,
            ETag handling is disabled. (default: auto-generate ETag header)
        :param headers: Additional headers dict to add to the response.

        While checking user input is always a good idea, this function provides
        additional protection against malicious ``filename`` parameters from
        breaking out of the ``root`` directory and leaking sensitive information
        to an attacker.

        Read-protected files or files outside of the ``root`` directory are
        answered with ``403 Access Denied``. Missing files result in a
        ``404 Not Found`` response. Conditional requests (``If-Modified-Since``,
        ``If-None-Match``) are answered with ``304 Not Modified`` whenever
        possible. ``HEAD`` and ``Range`` requests (used by download managers to
        check or continue partial downloads) are also handled automatically.
    """

    root = os.path.join(os.path.abspath(root), '')
    filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
    headers = headers.copy() if headers else {}
    getenv = request.environ.get

    if not filename.startswith(root):
        return HTTPError(403, "Access denied.")
    if not os.path.isfile(filename):
        return HTTPError(404, "File does not exist.")
    if not os.access(filename, os.R_OK):
        return HTTPError(403, "You do not have permission to access this file.")

    if mimetype is True:
        name = download if isinstance(download, str) else filename
        mimetype, encoding = mimetypes.guess_type(name)
        if encoding == 'gzip':
            mimetype = 'application/gzip'
        elif encoding:  # e.g. bzip2 -> application/x-bzip2
            mimetype = 'application/x-' + encoding

    if charset and mimetype and 'charset=' not in mimetype \
       and (mimetype[:5] == 'text/' or mimetype == 'application/javascript'):
        mimetype += '; charset=%s' % charset

    if mimetype:
        headers['Content-Type'] = mimetype

    if download is True:
        download = os.path.basename(filename)

    if download:
        download = download.replace('"', '')
        headers['Content-Disposition'] = 'attachment; filename="%s"' % download

    stats = os.stat(filename)
    headers['Content-Length'] = clen = stats.st_size
    headers['Last-Modified'] = email.utils.formatdate(stats.st_mtime, usegmt=True)
    headers['Date'] = email.utils.formatdate(time.time(), usegmt=True)

    if etag is None:
        etag = '%d:%d:%d:%d:%s' % (stats.st_dev, stats.st_ino, stats.st_mtime,
                                   clen, filename)
        etag = hashlib.sha1(tob(etag)).hexdigest()

    if etag:
        headers['ETag'] = etag
        check = getenv('HTTP_IF_NONE_MATCH')
        if check and check == etag:
            return HTTPResponse(status=304, **headers)

    ims = getenv('HTTP_IF_MODIFIED_SINCE')
    if ims:
        ims = parse_date(ims.split(";")[0].strip())
        if ims is not None and ims >= int(stats.st_mtime):
            return HTTPResponse(status=304, **headers)

    body = '' if request.method == 'HEAD' else open(filename, 'rb')

    headers["Accept-Ranges"] = "bytes"
    range_header = getenv('HTTP_RANGE')
    if range_header:
        ranges = list(parse_range_header(range_header, clen))
        if not ranges:
            return HTTPError(416, "Requested Range Not Satisfiable")
        offset, end = ranges[0]
        rlen = end - offset
        headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end - 1, clen)
        headers["Content-Length"] = str(rlen)
        if body: body = _closeiter(_rangeiter(body, offset, rlen), body.close)
        return HTTPResponse(body, status=206, **headers)
    return HTTPResponse(body, **headers)

###############################################################################
# HTTP Utilities and MISC (TODO) ###############################################
###############################################################################


def debug(mode=True):
    """ Change the debug level.
    There is only one debug level supported at the moment."""
    global DEBUG
    if mode: warnings.simplefilter('default')
    DEBUG = bool(mode)


def http_date(value):
    if isinstance(value, str):
        return value
    if isinstance(value, datetime):
        # aware datetime.datetime is converted to UTC time
        # naive datetime.datetime is treated as UTC time
        value = value.utctimetuple()
    elif isinstance(value, datedate):
        # datetime.date is naive, and is treated as UTC time
        value = value.timetuple()
    if not isinstance(value, (int, float)):
        # convert struct_time in UTC to UNIX timestamp
        value = calendar.timegm(value)
    return email.utils.formatdate(value, usegmt=True)


def parse_date(ims):
    """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
    try:
        ts = email.utils.parsedate_tz(ims)
        return calendar.timegm(ts[:8] + (0, )) - (ts[9] or 0)
    except (TypeError, ValueError, IndexError, OverflowError):
        return None


def parse_auth(header):
    """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
    try:
        method, data = header.split(None, 1)
        if method.lower() == 'basic':
            user, pwd = touni(base64.b64decode(tob(data))).split(':', 1)
            return user, pwd
    except (KeyError, ValueError):
        return None


def parse_range_header(header, maxlen=0):
    """ Yield (start, end) ranges parsed from a HTTP Range header. Skip
        unsatisfiable ranges. The end index is non-inclusive."""
    if not header or header[:6] != 'bytes=': return
    ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
    for start, end in ranges:
        try:
            if not start:  # bytes=-100    -> last 100 bytes
                start, end = max(0, maxlen - int(end)), maxlen
            elif not end:  # bytes=100-    -> all but the first 99 bytes
                start, end = int(start), maxlen
            else:  # bytes=100-200 -> bytes 100-200 (inclusive)
                start, end = int(start), min(int(end) + 1, maxlen)
            if 0 <= start < end <= maxlen:
                yield start, end
        except ValueError:
            pass


#: Header tokenizer used by _parse_http_header()
_hsplit = re.compile('(?:(?:"((?:[^"\\\\]|\\\\.)*)")|([^;,=]+))([;,=]?)').findall


def _parse_http_header(h):
    """ Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values
        and parameters. For non-standard or broken input, this implementation may return partial results.
    :param h: A header string (e.g. ``text/html,text/plain;q=0.9,*/*;q=0.8``)
    :return: List of (value, params) tuples. The second element is a (possibly empty) dict.
    """
    values = []
    if '"' not in h:  # INFO: Fast path without regexp (~2x faster)
        for value in h.split(','):
            parts = value.split(';')
            values.append((parts[0].strip(), {}))
            for attr in parts[1:]:
                name, value = attr.split('=', 1)
                values[-1][1][name.strip().lower()] = value.strip()
    else:
        lop, key, attrs = ',', None, {}
        for quoted, plain, tok in _hsplit(h):
            value = plain.strip() if plain else quoted.replace('\\"', '"')
            if lop == ',':
                attrs = {}
                values.append((value, attrs))
            elif lop == ';':
                if tok == '=':
                    key = value
                else:
                    attrs[value.strip().lower()] = ''
            elif lop == '=' and key:
                attrs[key.strip().lower()] = value
                key = None
            lop = tok
    return values


def _parse_qsl(qs, encoding="utf8"):
    r = []
    for pair in qs.split('&'):
        if not pair: continue
        nv = pair.split('=', 1)
        if len(nv) != 2: nv.append('')
        key = urlunquote(nv[0].replace('+', ' '), encoding)
        value = urlunquote(nv[1].replace('+', ' '), encoding)
        r.append((key, value))
    return r


def _lscmp(a, b):
    """ Compares two strings in a cryptographically safe way:
        Runtime is not affected by length of common prefix. """
    return not sum(0 if x == y else 1
                   for x, y in zip(a, b)) and len(a) == len(b)


def cookie_encode(data, key, digestmod=None):
    """ Encode and sign a pickle-able object. Return a (byte) string """
    depr(0, 13, "cookie_encode() will be removed soon.",
                "Do not use this API directly.")
    digestmod = digestmod or hashlib.sha256
    msg = base64.b64encode(pickle.dumps(data, -1))
    sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=digestmod).digest())
    return b'!' + sig + b'?' + msg


def cookie_decode(data, key, digestmod=None):
    """ Verify and decode an encoded string. Return an object or None."""
    depr(0, 13, "cookie_decode() will be removed soon.",
                "Do not use this API directly.")
    data = tob(data)
    if cookie_is_encoded(data):
        sig, msg = data.split(b'?', 1)
        digestmod = digestmod or hashlib.sha256
        hashed = hmac.new(tob(key), msg, digestmod=digestmod).digest()
        if _lscmp(sig[1:], base64.b64encode(hashed)):
            return pickle.loads(base64.b64decode(msg))
    return None


def cookie_is_encoded(data):
    """ Return True if the argument looks like a encoded cookie."""
    depr(0, 13, "cookie_is_encoded() will be removed soon.",
                "Do not use this API directly.")
    return bool(data.startswith(b'!') and b'?' in data)


def html_escape(string):
    """ Escape HTML special characters ``&<>`` and quotes ``'"``. """
    return string.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')\
                 .replace('"', '&quot;').replace("'", '&#039;')


def html_quote(string):
    """ Escape and quote a string to be used as an HTTP attribute."""
    return '"%s"' % html_escape(string).replace('\n', '&#10;') \
        .replace('\r', '&#13;').replace('\t', '&#9;')


def yieldroutes(func):
    """ Return a generator for routes that match the signature (name, args)
    of the func parameter. This may yield more than one route if the function
    takes optional keyword arguments. The output is best described by example::

        a()         -> '/a'
        b(x, y)     -> '/b/<x>/<y>'
        c(x, y=5)   -> '/c/<x>' and '/c/<x>/<y>'
        d(x=5, y=6) -> '/d' and '/d/<x>' and '/d/<x>/<y>'
    """
    path = '/' + func.__name__.replace('__', '/').lstrip('/')
    sig = inspect.signature(func, follow_wrapped=False)
    for p in sig.parameters.values():
        if p.kind == p.POSITIONAL_ONLY:
            raise ValueError("Invalid signature for yieldroutes: %s" % sig)
        if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY):
            if p.default != p.empty:
                yield path  # Yield path without this (optional) parameter.
            path += "/<%s>" % p.name
    yield path


def path_shift(script_name, path_info, shift=1):
    """ Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.

        :return: The modified paths.
        :param script_name: The SCRIPT_NAME path.
        :param script_name: The PATH_INFO path.
        :param shift: The number of path fragments to shift. May be negative to
          change the shift direction. (default: 1)
    """
    if shift == 0: return script_name, path_info
    pathlist = path_info.strip('/').split('/')
    scriptlist = script_name.strip('/').split('/')
    if pathlist and pathlist[0] == '': pathlist = []
    if scriptlist and scriptlist[0] == '': scriptlist = []
    if 0 < shift <= len(pathlist):
        moved = pathlist[:shift]
        scriptlist = scriptlist + moved
        pathlist = pathlist[shift:]
    elif 0 > shift >= -len(scriptlist):
        moved = scriptlist[shift:]
        pathlist = moved + pathlist
        scriptlist = scriptlist[:shift]
    else:
        empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
        raise AssertionError("Cannot shift. Nothing left from %s" % empty)
    new_script_name = '/' + '/'.join(scriptlist)
    new_path_info = '/' + '/'.join(pathlist)
    if path_info.endswith('/') and pathlist: new_path_info += '/'
    return new_script_name, new_path_info


def auth_basic(check, realm="private", text="Access denied"):
    """ Callback decorator to require HTTP auth (basic).
        TODO: Add route(check_auth=...) parameter. """

    def decorator(func):

        @functools.wraps(func)
        def wrapper(*a, **ka):
            user, password = request.auth or (None, None)
            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)

        return wrapper

    return decorator

# Shortcuts for common Bottle methods.
# They all refer to the current default application.


def make_default_app_wrapper(name):
    """ Return a callable that relays calls to the current default app. """

    @functools.wraps(getattr(Bottle, name))
    def wrapper(*a, **ka):
        return getattr(app(), name)(*a, **ka)

    return wrapper


route = make_default_app_wrapper('route')
get = make_default_app_wrapper('get')
post = make_default_app_wrapper('post')
put = make_default_app_wrapper('put')
delete = make_default_app_wrapper('delete')
patch = make_default_app_wrapper('patch')
error = make_default_app_wrapper('error')
mount = make_default_app_wrapper('mount')
hook = make_default_app_wrapper('hook')
install = make_default_app_wrapper('install')
uninstall = make_default_app_wrapper('uninstall')
url = make_default_app_wrapper('get_url')


###############################################################################
# Multipart Handling ###########################################################
###############################################################################
# cgi.FieldStorage was deprecated in Python 3.11 and removed in 3.13
# This implementation is based on https://github.com/defnull/multipart/


class MultipartError(HTTPError):
    def __init__(self, msg):
        HTTPError.__init__(self, 400, "MultipartError: " + msg)


class _MultipartParser:
    def __init__(
        self,
        stream,
        boundary,
        content_length=-1,
        disk_limit=2 ** 30,
        mem_limit=2 ** 20,
        memfile_limit=2 ** 18,
        buffer_size=2 ** 16,
        charset="latin1",
    ):
        self.stream = stream
        self.boundary = boundary
        self.content_length = content_length
        self.disk_limit = disk_limit
        self.memfile_limit = memfile_limit
        self.mem_limit = min(mem_limit, self.disk_limit)
        self.buffer_size = min(buffer_size, self.mem_limit)
        self.charset = charset

        if not boundary:
            raise MultipartError("No boundary.")

        if self.buffer_size - 6 < len(boundary):  # "--boundary--\r\n"
            raise MultipartError("Boundary does not fit into buffer_size.")

    def _lineiter(self):
        """ Iterate over a binary file-like object (crlf terminated) line by
            line. Each line is returned as a (line, crlf) tuple. Lines larger
            than buffer_size are split into chunks where all but the last chunk
            has an empty string instead of crlf. Maximum chunk size is twice the
            buffer size.
        """

        read = self.stream.read
        maxread, maxbuf = self.content_length, self.buffer_size
        partial = b""  # Contains the last (partial) line

        while True:
            chunk = read(maxbuf if maxread < 0 else min(maxbuf, maxread))
            maxread -= len(chunk)
            if not chunk:
                if partial:
                    yield partial, b''
                break

            if partial:
                chunk = partial + chunk

            scanpos = 0
            while True:
                i = chunk.find(b'\r\n', scanpos)
                if i >= 0:
                    yield chunk[scanpos:i], b'\r\n'
                    scanpos = i + 2
                else:  # CRLF not found
                    partial = chunk[scanpos:] if scanpos else chunk
                    break

            if len(partial) > maxbuf:
                yield partial[:-1], b""
                partial = partial[-1:]

    def parse(self):
        """ Return a MultiPart iterator. Can only be called once. """

        lines, line = self._lineiter(), ""
        separator = b"--" + tob(self.boundary)
        terminator = separator + b"--"
        mem_used, disk_used = 0, 0  # Track used resources to prevent DoS
        is_tail = False  # True if the last line was incomplete (cutted)

        # Consume first boundary. Ignore any preamble, as required by RFC
        # 2046, section 5.1.1.
        for line, nl in lines:
            if line in (separator, terminator):
                break
        else:
            raise MultipartError("Stream does not contain boundary")

        # First line is termainating boundary -> empty multipart stream
        if line == terminator:
            for _ in lines:
                raise MultipartError("Found data after empty multipart stream")
            return

        part_options = {
            "buffer_size": self.buffer_size,
            "memfile_limit": self.memfile_limit,
            "charset": self.charset,
        }
        part = _MultipartPart(**part_options)

        for line, nl in lines:
            if not is_tail and (line == separator or line == terminator):
                part.finish()
                if part.is_buffered():
                    mem_used += part.size
                else:
                    disk_used += part.size
                yield part
                if line == terminator:
                    break
                part = _MultipartPart(**part_options)
            else:
                is_tail = not nl  # The next line continues this one
                try:
                    part.feed(line, nl)
                    if part.is_buffered():
                        if part.size + mem_used > self.mem_limit:
                            raise MultipartError("Memory limit reached.")
                    elif part.size + disk_used > self.disk_limit:
                        raise MultipartError("Disk limit reached.")
                except MultipartError:
                    part.close()
                    raise
        else:
            part.close()

        if line != terminator:
            raise MultipartError("Unexpected end of multipart stream.")


class _MultipartPart:
    def __init__(self, buffer_size=2 ** 16, memfile_limit=2 ** 18, charset="latin1"):
        self.headerlist = []
        self.headers = None
        self.file = False
        self.size = 0
        self._buf = b""
        self.disposition = None
        self.name = None
        self.filename = None
        self.content_type = None
        self.charset = charset
        self.memfile_limit = memfile_limit
        self.buffer_size = buffer_size

    def feed(self, line, nl=""):
        if self.file:
            return self.write_body(line, nl)
        return self.write_header(line, nl)

    def write_header(self, line, nl):
        line = str(line, self.charset)

        if not nl:
            raise MultipartError("Unexpected end of line in header.")

        if not line.strip():  # blank line -> end of header segment
            self.finish_header()
        elif line[0] in " \t" and self.headerlist:
            name, value = self.headerlist.pop()
            self.headerlist.append((name, value + line.strip()))
        else:
            if ":" not in line:
                raise MultipartError("Syntax error in header: No colon.")

            name, value = line.split(":", 1)
            self.headerlist.append((name.strip(), value.strip()))

    def write_body(self, line, nl):
        if not line and not nl:
            return  # This does not even flush the buffer

        self.size += len(line) + len(self._buf)
        self.file.write(self._buf + line)
        self._buf = nl

        if self.content_length > 0 and self.size > self.content_length:
            raise MultipartError("Size of body exceeds Content-Length header.")

        if self.size > self.memfile_limit and isinstance(self.file, BytesIO):
            self.file, old = NamedTemporaryFile(mode="w+b"), self.file
            old.seek(0)

            copied, maxcopy, chunksize = 0, self.size, self.buffer_size
            read, write = old.read, self.file.write
            while copied < maxcopy:
                chunk = read(min(chunksize, maxcopy - copied))
                write(chunk)
                copied += len(chunk)

    def finish_header(self):
        self.file = BytesIO()
        self.headers = HeaderDict(self.headerlist)
        content_disposition = self.headers.get("Content-Disposition")
        content_type = self.headers.get("Content-Type")

        if not content_disposition:
            raise MultipartError("Content-Disposition header is missing.")

        self.disposition, self.options = _parse_http_header(content_disposition)[0]
        self.name = self.options.get("name")
        if "filename" in self.options:
            self.filename = self.options.get("filename")
            if self.filename[1:3] == ":\\" or self.filename[:2] == "\\\\":
                self.filename = self.filename.split("\\")[-1]  # ie6 bug

        self.content_type, options = _parse_http_header(content_type)[0] if content_type else (None, {})
        self.charset = options.get("charset") or self.charset

        self.content_length = int(self.headers.get("Content-Length", "-1"))

    def finish(self):
        if not self.file:
            raise MultipartError("Incomplete part: Header section not closed.")
        self.file.seek(0)

    def is_buffered(self):
        """ Return true if the data is fully buffered in memory."""
        return isinstance(self.file, BytesIO)

    @property
    def value(self):
        """ Data decoded with the specified charset """
        return str(self.raw, self.charset)

    @property
    def raw(self):
        """ Data without decoding """
        pos = self.file.tell()
        self.file.seek(0)

        try:
            return self.file.read()
        finally:
            self.file.seek(pos)

    def close(self):
        if self.file:
            self.file.close()
            self.file = False

###############################################################################
# Server Adapter ###############################################################
###############################################################################

# Before you edit or add a server adapter, please read:
# - https://github.com/bottlepy/bottle/pull/647#issuecomment-60152870
# - https://github.com/bottlepy/bottle/pull/865#issuecomment-242795341


class ServerAdapter:
    quiet = False

    def __init__(self, host='127.0.0.1', port=8080, **options):
        self.options = options
        self.host = host
        self.port = int(port)

    def run(self, handler):  # pragma: no cover
        pass

    @property
    def _listen_url(self):
        if self.host.startswith("unix:"):
            return self.host
        elif ':' in self.host:
            return "http://[%s]:%d/" % (self.host, self.port)
        else:
            return "http://%s:%d/" % (self.host, self.port)

    def __repr__(self):
        args = ', '.join('%s=%r' % kv for kv in self.options.items())
        return "%s(%s)" % (self.__class__.__name__, args)


class CGIServer(ServerAdapter):
    quiet = True

    def run(self, handler):  # pragma: no cover
        from wsgiref.handlers import CGIHandler

        def fixed_environ(environ, start_response):
            environ.setdefault('PATH_INFO', '')
            return handler(environ, start_response)

        CGIHandler().run(fixed_environ)


class FlupFCGIServer(ServerAdapter):
    def run(self, handler):  # pragma: no cover
        import flup.server.fcgi
        self.options.setdefault('bindAddress', (self.host, self.port))
        flup.server.fcgi.WSGIServer(handler, **self.options).run()


class WSGIRefServer(ServerAdapter):
    def run(self, app):  # pragma: no cover
        from wsgiref.simple_server import make_server
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        import socket

        class FixedHandler(WSGIRequestHandler):
            def log_message(other, format, *args):
                if not self.quiet:
                    return WSGIRequestHandler.log_message(other, format, *args)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls = self.options.get('server_class', WSGIServer)

        if ':' in self.host:  # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:

                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        self.srv = make_server(self.host, self.port, app, server_cls,
                               handler_cls)
        self.port = self.srv.server_port  # update port actual port (0 means random)
        try:
            self.srv.serve_forever()
        except KeyboardInterrupt:
            self.srv.server_close()  # Prevent ResourceWarning: unclosed socket
            raise


class CherryPyServer(ServerAdapter):
    def run(self, handler):  # pragma: no cover
        depr(0, 13, "The wsgi server part of cherrypy was split into a new "
                    "project called 'cheroot'.", "Use the 'cheroot' server "
                    "adapter instead of cherrypy.")
        from cherrypy import wsgiserver  # This will fail for CherryPy >= 9

        self.options['bind_addr'] = (self.host, self.port)
        self.options['wsgi_app'] = handler

        certfile = self.options.get('certfile')
        if certfile:
            del self.options['certfile']
        keyfile = self.options.get('keyfile')
        if keyfile:
            del self.options['keyfile']

        server = wsgiserver.CherryPyWSGIServer(**self.options)
        if certfile:
            server.ssl_certificate = certfile
        if keyfile:
            server.ssl_private_key = keyfile

        try:
            server.start()
        finally:
            server.stop()


class CherootServer(ServerAdapter):
    def run(self, handler):  # pragma: no cover
        from cheroot import wsgi
        from cheroot.ssl import builtin
        self.options['bind_addr'] = (self.host, self.port)
        self.options['wsgi_app'] = handler
        certfile = self.options.pop('certfile', None)
        keyfile = self.options.pop('keyfile', None)
        chainfile = self.options.pop('chainfile', None)
        server = wsgi.Server(**self.options)
        if certfile and keyfile:
            server.ssl_adapter = builtin.BuiltinSSLAdapter(
                certfile, keyfile, chainfile)
        try:
            server.start()
        finally:
            server.stop()


class WaitressServer(ServerAdapter):
    def run(self, handler):
        from waitress import serve
        serve(handler, host=self.host, port=self.port, _quiet=self.quiet, **self.options)


class PasteServer(ServerAdapter):
    def run(self, handler):  # pragma: no cover
        from paste import httpserver
        from paste.translogger import TransLogger
        handler = TransLogger(handler, setup_console_handler=(not self.quiet))
        httpserver.serve(handler,
                         host=self.host,
                         port=str(self.port), **self.options)


class MeinheldServer(ServerAdapter):
    def run(self, handler):
        from meinheld import server
        server.listen((self.host, self.port))
        server.run(handler)


class FapwsServer(ServerAdapter):
    """ Extremely fast webserver using libev. See https://github.com/william-os4y/fapws3 """

    def run(self, handler):  # pragma: no cover
        depr(0, 13, "fapws3 is not maintained and support will be dropped.")
        import fapws._evwsgi as evwsgi
        from fapws import base, config
        port = self.port
        if float(config.SERVER_IDENT[-2:]) > 0.4:
            # fapws3 silently changed its API in 0.5
            port = str(port)
        evwsgi.start(self.host, port)
        # fapws3 never releases the GIL. Complain upstream. I tried. No luck.
        if 'BOTTLE_CHILD' in os.environ and not self.quiet:
            _stderr("WARNING: Auto-reloading does not work with Fapws3.")
            _stderr("         (Fapws3 breaks python thread support)")
        evwsgi.set_base_module(base)

        def app(environ, start_response):
            environ['wsgi.multiprocess'] = False
            return handler(environ, start_response)

        evwsgi.wsgi_cb(('', app))
        evwsgi.run()


class TornadoServer(ServerAdapter):
    """ The super hyped asynchronous server by facebook. Untested. """

    def run(self, handler):  # pragma: no cover
        import tornado.wsgi, tornado.httpserver, tornado.ioloop
        container = tornado.wsgi.WSGIContainer(handler)
        server = tornado.httpserver.HTTPServer(container)
        server.listen(port=self.port, address=self.host)
        tornado.ioloop.IOLoop.instance().start()


class AppEngineServer(ServerAdapter):
    """ Adapter for Google App Engine. """
    quiet = True

    def run(self, handler):
        depr(0, 13, "AppEngineServer no longer required",
             "Configure your application directly in your app.yaml")
        from google.appengine.ext.webapp import util
        # A main() function in the handler script enables 'App Caching'.
        # Lets makes sure it is there. This _really_ improves performance.
        module = sys.modules.get('__main__')
        if module and not hasattr(module, 'main'):
            module.main = lambda: util.run_wsgi_app(handler)
        util.run_wsgi_app(handler)


class TwistedServer(ServerAdapter):
    """ Untested. """

    def run(self, handler):
        from twisted.web import server, wsgi
        from twisted.python.threadpool import ThreadPool
        from twisted.internet import reactor
        thread_pool = ThreadPool()
        thread_pool.start()
        reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
        factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
        reactor.listenTCP(self.port, factory, interface=self.host)
        if not reactor.running:
            reactor.run()


class DieselServer(ServerAdapter):
    """ Untested. """

    def run(self, handler):
        depr(0, 13, "Diesel is not tested or supported and will be removed.")
        from diesel.protocols.wsgi import WSGIApplication
        app = WSGIApplication(handler, port=self.port)
        app.run()


class GeventServer(ServerAdapter):
    """ Untested. Options:

        * See gevent.wsgi.WSGIServer() documentation for more options.
    """

    def run(self, handler):
        from gevent import pywsgi, local
        if not isinstance(threading.local(), local.local):
            msg = "Bottle requires gevent.monkey.patch_all() (before import)"
            raise RuntimeError(msg)
        if self.quiet:
            self.options['log'] = None
        address = (self.host, self.port)
        server = pywsgi.WSGIServer(address, handler, **self.options)
        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: server.stop())
        server.serve_forever()


class GunicornServer(ServerAdapter):
    """ Untested. See https://gunicorn.org/configure.html for options. """

    def run(self, handler):
        from gunicorn.app.base import BaseApplication

        if self.host.startswith("unix:"):
            config = {'bind': self.host}
        else:
            config = {'bind': "%s:%d" % (self.host, self.port)}

        config.update(self.options)

        class GunicornApplication(BaseApplication):
            def load_config(self):
                for key, value in config.items():
                    self.cfg.set(key, value)

            def load(self):
                return handler

        GunicornApplication().run()


class EventletServer(ServerAdapter):
    """ Untested. Options:

        * `backlog` adjust the eventlet backlog parameter which is the maximum
          number of queued connections. Should be at least 1; the maximum
          value is system-dependent.
        * `family`: (default is 2) socket family, optional. See socket
          documentation for available families.
    """

    def run(self, handler):
        from eventlet import wsgi, listen, patcher
        if not patcher.is_monkey_patched(os):
            msg = "Bottle requires eventlet.monkey_patch() (before import)"
            raise RuntimeError(msg)
        socket_args = {}
        for arg in ('backlog', 'family'):
            try:
                socket_args[arg] = self.options.pop(arg)
            except KeyError:
                pass
        address = (self.host, self.port)
        try:
            wsgi.server(listen(address, **socket_args), handler,
                        log_output=(not self.quiet))
        except TypeError:
            # Fallback, if we have old version of eventlet
            wsgi.server(listen(address), handler)


class BjoernServer(ServerAdapter):
    """ Fast server written in C: https://github.com/jonashaag/bjoern """

    def run(self, handler):
        from bjoern import run
        run(handler, self.host, self.port, reuse_port=True)


class AsyncioServerAdapter(ServerAdapter):
    """ Extend ServerAdapter for adding custom event loop """
    def get_event_loop(self):
        pass


class AiohttpServer(AsyncioServerAdapter):
    """ Asynchronous HTTP client/server framework for asyncio
        https://pypi.python.org/pypi/aiohttp/
        https://pypi.org/project/aiohttp-wsgi/
    """

    def get_event_loop(self):
        import asyncio
        return asyncio.new_event_loop()

    def run(self, handler):
        import asyncio
        from aiohttp_wsgi.wsgi import serve
        self.loop = self.get_event_loop()
        asyncio.set_event_loop(self.loop)

        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: self.loop.stop())

        serve(handler, host=self.host, port=self.port)


class AiohttpUVLoopServer(AiohttpServer):
    """uvloop
       https://github.com/MagicStack/uvloop
    """
    def get_event_loop(self):
        import uvloop
        return uvloop.new_event_loop()


class AutoServer(ServerAdapter):
    """ Untested. """
    adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer,
                CherootServer, WSGIRefServer]

    def run(self, handler):
        for sa in self.adapters:
            try:
                return sa(self.host, self.port, **self.options).run(handler)
            except ImportError:
                pass


server_names = {
    'cgi': CGIServer,
    'flup': FlupFCGIServer,
    'wsgiref': WSGIRefServer,
    'waitress': WaitressServer,
    'cherrypy': CherryPyServer,
    'cheroot': CherootServer,
    'paste': PasteServer,
    'fapws3': FapwsServer,
    'tornado': TornadoServer,
    'gae': AppEngineServer,
    'twisted': TwistedServer,
    'diesel': DieselServer,
    'meinheld': MeinheldServer,
    'gunicorn': GunicornServer,
    'eventlet': EventletServer,
    'gevent': GeventServer,
    'bjoern': BjoernServer,
    'aiohttp': AiohttpServer,
    'uvloop': AiohttpUVLoopServer,
    'auto': AutoServer,
}

###############################################################################
# Application Control ##########################################################
###############################################################################


def load(target, **namespace):
    """ Import a module or fetch an object from a module.

        * ``package.module`` returns `module` as a module object.
        * ``pack.mod:name`` returns the module variable `name` from `pack.mod`.
        * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.

        The last form accepts not only function calls, but any type of
        expression. Keyword arguments passed to this function are available as
        local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
    """
    module, target = target.split(":", 1) if ':' in target else (target, None)
    if module not in sys.modules: __import__(module)
    if not target: return sys.modules[module]
    if target.isalnum(): return getattr(sys.modules[module], target)
    package_name = module.split('.')[0]
    namespace[package_name] = sys.modules[package_name]
    return eval('%s.%s' % (module, target), namespace)


def load_app(target):
    """ Load a bottle application from a module and make sure that the import
        does not affect the current default application, but returns a separate
        application object. See :func:`load` for the target parameter. """
    global NORUN
    NORUN, nr_old = True, NORUN
    tmp = default_app.push()  # Create a new "default application"
    try:
        rv = load(target)  # Import the target module
        return rv if callable(rv) else tmp
    finally:
        default_app.remove(tmp)  # Remove the temporary added default application
        NORUN = nr_old


_debug = debug


def run(app=None,
        server='wsgiref',
        host='127.0.0.1',
        port=8080,
        interval=1,
        reloader=False,
        quiet=False,
        plugins=None,
        debug=None,
        config=None, **kargs):
    """ Start a server instance. This method blocks until the server terminates.

        :param app: WSGI application or target string supported by
               :func:`load_app`. (default: :func:`default_app`)
        :param server: Server adapter to use. See :data:`server_names` keys
               for valid names or pass a :class:`ServerAdapter` subclass.
               (default: `wsgiref`)
        :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
               all interfaces including the external one. (default: 127.0.0.1)
        :param port: Server port to bind to. Values below 1024 require root
               privileges. (default: 8080)
        :param reloader: Start auto-reloading server? (default: False)
        :param interval: Auto-reloader interval in seconds (default: 1)
        :param quiet: Suppress output to stdout and stderr? (default: False)
        :param options: Options passed to the server adapter.
     """
    if NORUN: return
    if reloader and not os.environ.get('BOTTLE_CHILD'):
        import subprocess
        fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
        environ = os.environ.copy()
        environ['BOTTLE_CHILD'] = 'true'
        environ['BOTTLE_LOCKFILE'] = lockfile
        args = [sys.executable] + sys.argv
        # If a package was loaded with `python -m`, then `sys.argv` needs to be
        # restored to the original value, or imports might break. See #1336
        if getattr(sys.modules.get('__main__'), '__package__', None):
            args[1:1] = ["-m", sys.modules['__main__'].__package__]

        try:
            os.close(fd)  # We never write to this file
            while os.path.exists(lockfile):
                p = subprocess.Popen(args, env=environ)
                while p.poll() is None:
                    os.utime(lockfile, None)  # Tell child we are still alive
                    time.sleep(interval)
                if p.returncode == 3:  # Child wants to be restarted
                    continue
                sys.exit(p.returncode)
        except KeyboardInterrupt:
            pass
        finally:
            if os.path.exists(lockfile):
                os.unlink(lockfile)
        return

    try:
        if debug is not None: _debug(debug)
        app = app or default_app()
        if isinstance(app, str):
            app = load_app(app)
        if not callable(app):
            raise ValueError("Application is not callable: %r" % app)

        for plugin in plugins or []:
            if isinstance(plugin, str):
                plugin = load(plugin)
            app.install(plugin)

        if config:
            app.config.update(config)

        if server in server_names:
            server = server_names.get(server)
        if isinstance(server, str):
            server = load(server)
        if isinstance(server, type):
            server = server(host=host, port=port, **kargs)
        if not isinstance(server, ServerAdapter):
            raise ValueError("Unknown or unsupported server: %r" % server)

        server.quiet = server.quiet or quiet
        if not server.quiet:
            _stderr("Bottle v%s server starting up (using %s)..." %
                    (__version__, repr(server)))
            _stderr("Listening on %s" % server._listen_url)
            _stderr("Hit Ctrl-C to quit.\n")

        if reloader:
            lockfile = os.environ.get('BOTTLE_LOCKFILE')
            bgcheck = FileCheckerThread(lockfile, interval)
            with bgcheck:
                server.run(app)
            if bgcheck.status == 'reload':
                sys.exit(3)
        else:
            server.run(app)
    except KeyboardInterrupt:
        pass
    except (SystemExit, MemoryError):
        raise
    except:  # noqa: E722
        if not reloader: raise
        if not getattr(server, 'quiet', quiet):
            print_exc()
        time.sleep(interval)
        sys.exit(3)


class FileCheckerThread(threading.Thread):
    """ Interrupt main-thread as soon as a changed module file is detected,
        the lockfile gets deleted or gets too old. """

    def __init__(self, lockfile, interval):
        threading.Thread.__init__(self)
        self.daemon = True
        self.lockfile, self.interval = lockfile, interval
        #: Is one of 'reload', 'error' or 'exit'
        self.status = None

    def run(self):
        exists = os.path.exists
        mtime = lambda p: os.stat(p).st_mtime
        files = {}

        for module in list(sys.modules.values()):
            path = getattr(module, '__file__', '') or ''
            if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
            if path and exists(path): files[path] = mtime(path)

        while not self.status:
            if not exists(self.lockfile)\
               or mtime(self.lockfile) < time.time() - self.interval - 5:
                self.status = 'error'
                thread.interrupt_main()
            for path, lmtime in list(files.items()):
                if not exists(path) or mtime(path) > lmtime:
                    self.status = 'reload'
                    thread.interrupt_main()
                    break
            time.sleep(self.interval)

    def __enter__(self):
        self.start()

    def __exit__(self, exc_type, *_):
        if not self.status: self.status = 'exit'  # silent exit
        self.join()
        return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)

###############################################################################
# Template Adapters ############################################################
###############################################################################


class TemplateError(BottleException):
    pass


class BaseTemplate:
    """ Base class and minimal API for template adapters """
    extensions = ['tpl', 'html', 'thtml', 'stpl']
    settings = {}  # used in prepare()
    defaults = {}  # used in render()

    def __init__(self,
                 source=None,
                 name=None,
                 lookup=None,
                 encoding='utf8', **settings):
        """ Create a new template.
        If the source parameter (str or buffer) is missing, the name argument
        is used to guess a template filename. Subclasses can assume that
        self.source and/or self.filename are set. Both are strings.
        The lookup, encoding and settings parameters are stored as instance
        variables.
        The lookup parameter stores a list containing directory paths.
        The encoding parameter should be used to decode byte strings or files.
        The settings parameter contains a dict for engine-specific settings.
        """
        self.name = name
        self.source = source.read() if hasattr(source, 'read') else source
        self.filename = source.filename if hasattr(source, 'filename') else None
        self.lookup = [os.path.abspath(x) for x in lookup] if lookup else []
        self.encoding = encoding
        self.settings = self.settings.copy()  # Copy from class variable
        self.settings.update(settings)  # Apply
        if not self.source and self.name:
            self.filename = self.search(self.name, self.lookup)
            if not self.filename:
                raise TemplateError('Template %s not found.' % repr(name))
        if not self.source and not self.filename:
            raise TemplateError('No template specified.')
        self.prepare(**self.settings)

    @classmethod
    def search(cls, name, lookup=None):
        """ Search name in all directories specified in lookup.
        First without, then with common extensions. Return first hit. """
        if not lookup:
            raise depr(0, 12, "Empty template lookup path.", "Configure a template lookup path.")

        if os.path.isabs(name):
            raise depr(0, 12, "Use of absolute path for template name.",
                       "Refer to templates with names or paths relative to the lookup path.")

        for spath in lookup:
            spath = os.path.abspath(spath) + os.sep
            fname = os.path.abspath(os.path.join(spath, name))
            if not fname.startswith(spath): continue
            if os.path.isfile(fname): return fname
            for ext in cls.extensions:
                if os.path.isfile('%s.%s' % (fname, ext)):
                    return '%s.%s' % (fname, ext)

    @classmethod
    def global_config(cls, key, *args):
        """ This reads or sets the global settings stored in class.settings. """
        if args:
            cls.settings = cls.settings.copy()  # Make settings local to class
            cls.settings[key] = args[0]
        else:
            return cls.settings[key]

    def prepare(self, **options):
        """ Run preparations (parsing, caching, ...).
        It should be possible to call this again to refresh a template or to
        update settings.
        """
        raise NotImplementedError

    def render(self, *args, **kwargs):
        """ Render the template with the specified local variables and return
        a single byte or unicode string. If it is a byte string, the encoding
        must match self.encoding. This method must be thread-safe!
        Local variables may be provided in dictionaries (args)
        or directly, as keywords (kwargs).
        """
        raise NotImplementedError


class MakoTemplate(BaseTemplate):
    def prepare(self, **options):
        from mako.template import Template
        from mako.lookup import TemplateLookup
        options.update({'input_encoding': self.encoding})
        options.setdefault('format_exceptions', bool(DEBUG))
        lookup = TemplateLookup(directories=self.lookup, **options)
        if self.source:
            self.tpl = Template(self.source, lookup=lookup, **options)
        else:
            self.tpl = Template(uri=self.name,
                                filename=self.filename,
                                lookup=lookup, **options)

    def render(self, *args, **kwargs):
        for dictarg in args:
            kwargs.update(dictarg)
        _defaults = self.defaults.copy()
        _defaults.update(kwargs)
        return self.tpl.render(**_defaults)


class CheetahTemplate(BaseTemplate):
    def prepare(self, **options):
        from Cheetah.Template import Template
        self.context = threading.local()
        self.context.vars = {}
        options['searchList'] = [self.context.vars]
        if self.source:
            self.tpl = Template(source=self.source, **options)
        else:
            self.tpl = Template(file=self.filename, **options)

    def render(self, *args, **kwargs):
        for dictarg in args:
            kwargs.update(dictarg)
        self.context.vars.update(self.defaults)
        self.context.vars.update(kwargs)
        out = str(self.tpl)
        self.context.vars.clear()
        return out


class Jinja2Template(BaseTemplate):
    def prepare(self, filters=None, tests=None, globals={}, **kwargs):
        from jinja2 import Environment, FunctionLoader
        self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
        if filters: self.env.filters.update(filters)
        if tests: self.env.tests.update(tests)
        if globals: self.env.globals.update(globals)
        if self.source:
            self.tpl = self.env.from_string(self.source)
        else:
            self.tpl = self.env.get_template(self.name)

    def render(self, *args, **kwargs):
        for dictarg in args:
            kwargs.update(dictarg)
        _defaults = self.defaults.copy()
        _defaults.update(kwargs)
        return self.tpl.render(**_defaults)

    def loader(self, name):
        if name == self.filename:
            fname = name
        else:
            fname = self.search(name, self.lookup)
        if not fname: return
        with open(fname, "rb") as f:
            return (f.read().decode(self.encoding), fname, lambda: False)


class SimpleTemplate(BaseTemplate):
    def prepare(self,
                escape_func=html_escape,
                noescape=False,
                syntax=None, **ka):
        self.cache = {}
        enc = self.encoding
        self._str = lambda x: touni(x, enc)
        self._escape = lambda x: escape_func(touni(x, enc))
        self.syntax = syntax
        if noescape:
            self._str, self._escape = self._escape, self._str

    @cached_property
    def co(self):
        return compile(self.code, self.filename or '<string>', 'exec')

    @cached_property
    def code(self):
        source = self.source
        if not source:
            with open(self.filename, 'rb') as f:
                source = f.read()
        try:
            source, encoding = touni(source), 'utf8'
        except UnicodeError:
            raise depr(0, 11, 'Unsupported template encodings.', 'Use utf-8 for templates.')
        parser = StplParser(source, encoding=encoding, syntax=self.syntax)
        code = parser.translate()
        self.encoding = parser.encoding
        return code

    def _rebase(self, _env, _name=None, **kwargs):
        _env['_rebase'] = (_name, kwargs)

    def _include(self, _env, _name=None, **kwargs):
        env = _env.copy()
        env.update(kwargs)
        if _name not in self.cache:
            self.cache[_name] = self.__class__(name=_name, lookup=self.lookup, syntax=self.syntax)
        return self.cache[_name].execute(env['_stdout'], env)

    def execute(self, _stdout, kwargs):
        env = self.defaults.copy()
        env.update(kwargs)
        env.update({
            '_stdout': _stdout,
            '_printlist': _stdout.extend,
            'include': functools.partial(self._include, env),
            'rebase': functools.partial(self._rebase, env),
            '_rebase': None,
            '_str': self._str,
            '_escape': self._escape,
            'get': env.get,
            'setdefault': env.setdefault,
            'defined': env.__contains__
        })
        exec(self.co, env)
        if env.get('_rebase'):
            subtpl, rargs = env.pop('_rebase')
            rargs['base'] = ''.join(_stdout)  # copy stdout
            del _stdout[:]  # clear stdout
            return self._include(env, subtpl, **rargs)
        return env

    def render(self, *args, **kwargs):
        """ Render the template using keyword arguments as local variables. """
        env = {}
        stdout = []
        for dictarg in args:
            env.update(dictarg)
        env.update(kwargs)
        self.execute(stdout, env)
        return ''.join(stdout)


class StplSyntaxError(TemplateError):
    pass


class StplParser:
    """ Parser for stpl templates. """
    _re_cache = {}  #: Cache for compiled re patterns

    # This huge pile of voodoo magic splits python code into 8 different tokens.
    # We use the verbose (?x) regex mode to make this more manageable

    _re_tok = r'''(
        [urbURB]*
        (?:  ''(?!')
            |""(?!")
            |'{6}
            |"{6}
            |'(?:[^\\']|\\.)+?'
            |"(?:[^\\"]|\\.)+?"
            |'{3}(?:[^\\]|\\.|\n)+?'{3}
            |"{3}(?:[^\\]|\\.|\n)+?"{3}
        )
    )'''

    _re_inl = _re_tok.replace(r'|\n', '')  # We re-use this string pattern later
    _re_tok += r'''
        # 2: Comments (until end of line, but not the newline itself)
        |(\#.*)
        # 3: Open and close (4) grouping tokens
        |([\[\{\(])
        |([\]\}\)])
        # 5,6: Keywords that start or continue a python block (only start of line)
        |^([\ \t]*(?:if|for|while|with|try|def|class)\b)
        |^([\ \t]*(?:elif|else|except|finally)\b)
        # 7: Our special 'end' keyword (but only if it stands alone)
        |((?:^|;)[\ \t]*end[\ \t]*(?=(?:%(block_close)s[\ \t]*)?\r?$|;|\#))
        # 8: A customizable end-of-code-block template token (only end of line)
        |(%(block_close)s[\ \t]*(?=\r?$))
        # 9: And finally, a single newline. The 10th token is 'everything else'
        |(\r?\n)
    '''

    # Match the start tokens of code areas in a template
    _re_split = r'''(?m)^[ \t]*(\\?)((%(line_start)s)|(%(block_start)s))'''
    # Match inline statements (may contain python strings)
    _re_inl = r'''%%(inline_start)s((?:%s|[^'"\n])*?)%%(inline_end)s''' % _re_inl
    # add the flag in front of the regexp to avoid Deprecation warning (see Issue #949)
    # verbose and dot-matches-newline mode
    _re_tok = '(?mx)' + _re_tok
    _re_inl = '(?mx)' + _re_inl

    default_syntax = '<% %> % {{ }}'

    def __init__(self, source, syntax=None, encoding='utf8'):
        self.source, self.encoding = touni(source, encoding), encoding
        self.set_syntax(syntax or self.default_syntax)
        self.code_buffer, self.text_buffer = [], []
        self.lineno, self.offset = 1, 0
        self.indent, self.indent_mod = 0, 0
        self.paren_depth = 0

    def get_syntax(self):
        """ Tokens as a space separated string (default: <% %> % {{ }}) """
        return self._syntax

    def set_syntax(self, syntax):
        self._syntax = syntax
        self._tokens = syntax.split()
        if syntax not in self._re_cache:
            names = 'block_start block_close line_start inline_start inline_end'
            etokens = map(re.escape, self._tokens)
            pattern_vars = dict(zip(names.split(), etokens))
            patterns = (self._re_split, self._re_tok, self._re_inl)
            patterns = [re.compile(p % pattern_vars) for p in patterns]
            self._re_cache[syntax] = patterns
        self.re_split, self.re_tok, self.re_inl = self._re_cache[syntax]

    syntax = property(get_syntax, set_syntax)

    def translate(self):
        if self.offset: raise RuntimeError('Parser is a one time instance.')
        while True:
            m = self.re_split.search(self.source, pos=self.offset)
            if m:
                text = self.source[self.offset:m.start()]
                self.text_buffer.append(text)
                self.offset = m.end()
                if m.group(1):  # Escape syntax
                    line, sep, _ = self.source[self.offset:].partition('\n')
                    self.text_buffer.append(
                        self.source[m.start():m.start(1)] + m.group(2) + line + sep)
                    self.offset += len(line + sep)
                    continue
                self.flush_text()
                self.offset += self.read_code(self.source[self.offset:],
                                              multiline=bool(m.group(4)))
            else:
                break
        self.text_buffer.append(self.source[self.offset:])
        self.flush_text()
        return ''.join(self.code_buffer)

    def read_code(self, pysource, multiline):
        code_line, comment = '', ''
        offset = 0
        while True:
            m = self.re_tok.search(pysource, pos=offset)
            if not m:
                code_line += pysource[offset:]
                offset = len(pysource)
                self.write_code(code_line.strip(), comment)
                break
            code_line += pysource[offset:m.start()]
            offset = m.end()
            _str, _com, _po, _pc, _blk1, _blk2, _end, _cend, _nl = m.groups()
            if self.paren_depth > 0 and (_blk1 or _blk2):  # a if b else c
                code_line += _blk1 or _blk2
                continue
            if _str:  # Python string
                code_line += _str
            elif _com:  # Python comment (up to EOL)
                comment = _com
                if multiline and _com.strip().endswith(self._tokens[1]):
                    multiline = False  # Allow end-of-block in comments
            elif _po:  # open parenthesis
                self.paren_depth += 1
                code_line += _po
            elif _pc:  # close parenthesis
                if self.paren_depth > 0:
                    # we could check for matching parentheses here, but it's
                    # easier to leave that to python - just check counts
                    self.paren_depth -= 1
                code_line += _pc
            elif _blk1:  # Start-block keyword (if/for/while/def/try/...)
                code_line = _blk1
                self.indent += 1
                self.indent_mod -= 1
            elif _blk2:  # Continue-block keyword (else/elif/except/...)
                code_line = _blk2
                self.indent_mod -= 1
            elif _cend:  # The end-code-block template token (usually '%>')
                if multiline: multiline = False
                else: code_line += _cend
            elif _end:
                self.indent -= 1
                self.indent_mod += 1
            else:  # \n
                self.write_code(code_line.strip(), comment)
                self.lineno += 1
                code_line, comment, self.indent_mod = '', '', 0
                if not multiline:
                    break

        return offset

    def flush_text(self):
        text = ''.join(self.text_buffer)
        del self.text_buffer[:]
        if not text: return
        parts, pos, nl = [], 0, '\\\n' + '  ' * self.indent
        for m in self.re_inl.finditer(text):
            prefix, pos = text[pos:m.start()], m.end()
            if prefix:
                parts.append(nl.join(map(repr, prefix.splitlines(True))))
            if prefix.endswith('\n'): parts[-1] += nl
            parts.append(self.process_inline(m.group(1).strip()))
        if pos < len(text):
            prefix = text[pos:]
            lines = prefix.splitlines(True)
            if lines[-1].endswith('\\\\\n'): lines[-1] = lines[-1][:-3]
            elif lines[-1].endswith('\\\\\r\n'): lines[-1] = lines[-1][:-4]
            parts.append(nl.join(map(repr, lines)))
        code = '_printlist((%s,))' % ', '.join(parts)
        self.lineno += code.count('\n') + 1
        self.write_code(code)

    @staticmethod
    def process_inline(chunk):
        if chunk[0] == '!': return '_str(%s)' % chunk[1:]
        return '_escape(%s)' % chunk

    def write_code(self, line, comment=''):
        code = '  ' * (self.indent + self.indent_mod)
        code += line.lstrip() + comment + '\n'
        self.code_buffer.append(code)


def template(*args, **kwargs):
    """
    Get a rendered template as a string iterator.
    You can use a name, a filename or a template string as first parameter.
    Template rendering arguments can be passed as dictionaries
    or directly (as keyword arguments).
    """
    tpl = args[0] if args else None
    for dictarg in args[1:]:
        kwargs.update(dictarg)
    adapter = kwargs.pop('template_adapter', SimpleTemplate)
    lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
    tplid = (id(lookup), tpl)
    if tplid not in TEMPLATES or DEBUG:
        settings = kwargs.pop('template_settings', {})
        if isinstance(tpl, adapter):
            TEMPLATES[tplid] = tpl
            if settings: TEMPLATES[tplid].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tplid]:
        abort(500, 'Template (%s) not found' % tpl)
    return TEMPLATES[tplid].render(kwargs)


mako_template = functools.partial(template, template_adapter=MakoTemplate)
cheetah_template = functools.partial(template,
                                     template_adapter=CheetahTemplate)
jinja2_template = functools.partial(template, template_adapter=Jinja2Template)


def view(tpl_name, **defaults):
    """ Decorator: renders a template for a handler.
        The handler can control its behavior like that:

          - return a dict of template vars to fill out the template
          - return something other than a dict and the view decorator will not
            process the template, but return the handler result as is.
            This includes returning a HTTPResponse(dict) to get,
            for instance, JSON with autojson or other castfilters.
    """

    def decorator(func):

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            if isinstance(result, (dict, DictMixin)):
                tplvars = defaults.copy()
                tplvars.update(result)
                return template(tpl_name, **tplvars)
            elif result is None:
                return template(tpl_name, **defaults)
            return result

        return wrapper

    return decorator


mako_view = functools.partial(view, template_adapter=MakoTemplate)
cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
jinja2_view = functools.partial(view, template_adapter=Jinja2Template)

###############################################################################
# Constants and Globals ########################################################
###############################################################################

TEMPLATE_PATH = ['./', './views/']
TEMPLATES = {}
DEBUG = False
NORUN = False  # If set, run() does nothing. Used by load_app()

#: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found')
HTTP_CODES = httplib.responses.copy()
HTTP_CODES[418] = "I'm a teapot"  # RFC 2324
HTTP_CODES[428] = "Precondition Required"
HTTP_CODES[429] = "Too Many Requests"
HTTP_CODES[431] = "Request Header Fields Too Large"
HTTP_CODES[451] = "Unavailable For Legal Reasons"  # RFC 7725
HTTP_CODES[511] = "Network Authentication Required"
_HTTP_STATUS_LINES = dict((k, '%d %s' % (k, v))
                          for (k, v) in HTTP_CODES.items())

#: The default template used for error pages. Override with @error()
ERROR_PAGE_TEMPLATE = """
%%try:
    %%from %s import DEBUG, request
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html>
        <head>
            <title>Error: {{e.status}}</title>
            <style type="text/css">
              html {background-color: #eee; font-family: sans-serif;}
              body {background-color: #fff; border: 1px solid #ddd;
                    padding: 15px; margin: 15px;}
              pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
            </style>
        </head>
        <body>
            <h1>Error: {{e.status}}</h1>
            <p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>
               caused an error:</p>
            <pre>{{e.body}}</pre>
            %%if DEBUG and e.exception:
              <h2>Exception:</h2>
              %%try:
                %%exc = repr(e.exception)
              %%except:
                %%exc = '<unprintable %%s object>' %% type(e.exception).__name__
              %%end
              <pre>{{exc}}</pre>
            %%end
            %%if DEBUG and e.traceback:
              <h2>Traceback:</h2>
              <pre>{{e.traceback}}</pre>
            %%end
        </body>
    </html>
%%except ImportError:
    <b>ImportError:</b> Could not generate the error page. Please add bottle to
    the import path.
%%end
""" % __name__

#: A thread-safe instance of :class:`LocalRequest`. If accessed from within a
#: request callback, this instance always refers to the *current* request
#: (even on a multi-threaded server).
request = LocalRequest()

#: A thread-safe instance of :class:`LocalResponse`. It is used to change the
#: HTTP response for the *current* request.
response = LocalResponse()

#: A thread-safe namespace. Not used by Bottle.
local = threading.local()

# Initialize app stack (create first empty Bottle app now deferred until needed)
# BC: 0.6.4 and needed for run()
apps = app = default_app = AppStack()

#: A virtual package that redirects import statements.
#: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`.
ext = _ImportRedirect('bottle.ext' if __name__ == '__main__' else
                      __name__ + ".ext", 'bottle_%s').module


def _main(argv):  # pragma: no coverage
    args, parser = _cli_parse(argv)

    def _cli_error(cli_msg):
        parser.print_help()
        _stderr('\nError: %s\n' % cli_msg)
        sys.exit(1)

    if args.version:
        print(__version__)
        sys.exit(0)
    if not args.app:
        _cli_error("No application entry point specified.")

    sys.path.insert(0, '.')
    sys.modules.setdefault('bottle', sys.modules['__main__'])

    host, port = (args.bind or 'localhost'), 8080
    if ':' in host and host.rfind(']') < host.rfind(':'):
        host, port = host.rsplit(':', 1)
    host = host.strip('[]')

    config = ConfigDict()

    for cfile in args.conf or []:
        try:
            if cfile.endswith('.json'):
                with open(cfile, 'rb') as fp:
                    config.load_dict(json_loads(fp.read()))
            else:
                config.load_config(cfile)
        except configparser.Error as parse_error:
            _cli_error(parse_error)
        except IOError:
            _cli_error("Unable to read config file %r" % cfile)
        except (UnicodeError, TypeError, ValueError) as error:
            _cli_error("Unable to parse config file %r: %s" % (cfile, error))

    for cval in args.param or []:
        if '=' in cval:
            config.update((cval.split('=', 1),))
        else:
            config[cval] = True

    run(args.app,
        host=host,
        port=int(port),
        server=args.server,
        reloader=args.reload,
        plugins=args.plugin,
        debug=args.debug,
        config=config)


def main():
    _main(sys.argv)


if __name__ == '__main__':  # pragma: no coverage
    main()


================================================
FILE: docs/_locale/.tx/config
================================================
[main]
host = https://www.transifex.com
type = PO

[bottle.development]
file_filter = <lang>/LC_MESSAGES/development.po
source_file = _pot/development.pot
source_lang = en
type = PO

[bottle.index]
file_filter = <lang>/LC_MESSAGES/index.po
source_file = _pot/index.pot
source_lang = en
type = PO

[bottle.configuration]
file_filter = <lang>/LC_MESSAGES/configuration.po
source_file = _pot/configuration.pot
source_lang = en
type = PO

[bottle.changelog]
file_filter = <lang>/LC_MESSAGES/changelog.po
source_file = _pot/changelog.pot
source_lang = en
type = PO

[bottle.stpl]
file_filter = <lang>/LC_MESSAGES/stpl.po
source_file = _pot/stpl.pot
source_lang = en
type = PO

[bottle.async]
file_filter = <lang>/LC_MESSAGES/async.po
source_file = _pot/async.pot
source_lang = en
type = PO

[bottle.recipes]
file_filter = <lang>/LC_MESSAGES/recipes.po
source_file = _pot/recipes.pot
source_lang = en
type = PO

[bottle.tutorial]
file_filter = <lang>/LC_MESSAGES/tutorial.po
source_file = _pot/tutorial.pot
source_lang = en
type = PO

[bottle.deployment]
file_filter = <lang>/LC_MESSAGES/deployment.po
source_file = _pot/deployment.pot
source_lang = en
type = PO

[bottle.routing]
file_filter = <lang>/LC_MESSAGES/routing.po
source_file = _pot/routing.pot
source_lang = en
type = PO

[bottle.api]
file_filter = <lang>/LC_MESSAGES/api.po
source_file = _pot/api.pot
source_lang = en
type = PO

[bottle.tutorial_app]
file_filter = <lang>/LC_MESSAGES/tutorial_app.po
source_file = _pot/tutorial_app.pot
source_lang = en
type = PO

[bottle.plugins]
file_filter = <lang>/LC_MESSAGES/plugins.po
source_file = _pot/plugins.pot
source_lang = en
type = PO

[bottle.contact]
file_filter = <lang>/LC_MESSAGES/contact.po
source_file = _pot/contact.pot
source_lang = en
type = PO

[bottle.faq]
file_filter = <lang>/LC_MESSAGES/faq.po
source_file = _pot/faq.pot
source_lang = en
type = PO

[bottle.plugins--index]
file_filter = <lang>/LC_MESSAGES/plugins/index.po
source_file = _pot/plugins/index.pot
source_lang = en
type = PO



================================================
FILE: docs/_locale/README.txt
================================================
Translation Workflow
====================

If documentation changed, run `make push` to push new messages to transiflex (manager account required).

To update the local translation files, call `make pull` and commit the changes from time to time  (manager account required).

Go to https://www.transifex.com/bottle for actually translating stuff. You can du that with a normal user account at transiflex.


================================================
FILE: docs/_locale/_pot/api.pot
================================================
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2009-2020, Marcel Hellkamp
# This file is distributed under the same license as the Bottle package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Bottle 0.13-dev\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-12-31 18:35+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: ../../api.rst:3
msgid "API Reference"
msgstr ""

#: ../../api.rst:10
msgid "This is a mostly auto-generated API. If you are new to bottle, you might find the narrative :doc:`tutorial` more helpful."
msgstr ""

#: ../../api.rst:17
msgid "Module Contents"
msgstr ""

#: ../../api.rst:19
msgid "The module defines several functions, constants, and an exception."
msgstr ""

#: ../../../bottle.py:docstring of bottle.debug:1
msgid "Change the debug level. There is only one debug level supported at the moment."
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:1
msgid "Start a server instance. This method blocks until the server terminates."
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:0
#: ../../../bottle.py:docstring of bottle.path_shift:0
#: ../../../bottle.py:docstring of bottle.MultiDict.get:0
#: ../../../bottle.py:docstring of bottle.HeaderDict.get:0
#: ../../../bottle.py:docstring of bottle.ResourceManager:0
#: ../../../bottle.py:docstring of bottle.ResourceManager.add_path:0
#: ../../../bottle.py:docstring of bottle.FileUpload.save:0
#: ../../../bottle.py:docstring of bottle.Bottle:0
#: ../../../bottle.py:docstring of bottle.Bottle.mount:0
#: ../../../bottle.py:docstring of bottle.Bottle.route:0
#: ../../../bottle.py:docstring of bottle.BaseRequest.path_shift:0
#: ../../../bottle.py:docstring of bottle.BaseResponse:0
#: ../../../bottle.py:docstring of bottle.BaseResponse.set_cookie:0
#: ../../../bottle.py:docstring of bottle.BaseResponse.set_cookie:0
msgid "Parameters"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:3
msgid "WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:5
msgid "Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:8
msgid "Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:10
msgid "Server port to bind to. Values below 1024 require root privileges. (default: 8080)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:12
msgid "Start auto-reloading server? (default: False)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:13
msgid "Auto-reloader interval in seconds (default: 1)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:14
msgid "Suppress output to stdout and stderr? (default: False)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.run:15
msgid "Options passed to the server adapter."
msgstr ""

#: ../../../bottle.py:docstring of bottle.load:1
msgid "Import a module or fetch an object from a module."
msgstr ""

#: ../../../bottle.py:docstring of bottle.load:3
msgid "``package.module`` returns `module` as a module object."
msgstr ""

#: ../../../bottle.py:docstring of bottle.load:4
msgid "``pack.mod:name`` returns the module variable `name` from `pack.mod`."
msgstr ""

#: ../../../bottle.py:docstring of bottle.load:5
msgid "``pack.mod:func()`` calls `pack.mod.func()` and returns the result."
msgstr ""

#: ../../../bottle.py:docstring of bottle.load:7
msgid "The last form accepts not only function calls, but any type of expression. Keyword arguments passed to this function are available as local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``"
msgstr ""

#: ../../../bottle.py:docstring of bottle.load_app:1
msgid "Load a bottle application from a module and make sure that the import does not affect the current default application, but returns a separate application object. See :func:`load` for the target parameter."
msgstr ""

#: ../../../bottle.py:docstring of bottle.request:1
#: ../../../bottle.py:docstring of bottle.request:1
msgid "A thread-safe instance of :class:`LocalRequest`. If accessed from within a request callback, this instance always refers to the *current* request (even on a multi-threaded server)."
msgstr ""

#: ../../../bottle.py:docstring of bottle.response:1
msgid "A thread-safe instance of :class:`LocalResponse`. It is used to change the HTTP response for the *current* request."
msgstr ""

#: ../../../bottle.py:docstring of bottle.HTTP_CODES:1
msgid "A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found')"
msgstr ""

#: ../../api.rst:38
msgid "Return the current :ref:`default-app`. Actually, these are callable instances of :class:`AppStack` and implement a stack-like API."
msgstr ""

#: ../../api.rst:42
msgid "Routing"
msgstr ""

#: ../../api.rst:44
msgid "Bottle maintains a stack of :class:`Bottle` instances (see :func:`app` and :class:`AppStack`) and uses the top of the stack as a *default application* for some of the module-level functions and decorators."
msgstr ""

#: ../../api.rst:54
msgid "Decorator to install a route to the current default application. See :meth:`Bottle.route` for details."
msgstr ""

#: ../../api.rst:59
msgid "Decorator to install an error handler to the current default application. See :meth:`Bottle.error` for details."
msgstr ""

#: ../../api.rst:63
msgid "WSGI and HTTP Utilities"
msgstr ""

#: ../../../bottle.py:docstring of bottle.parse_date:1
msgid "Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch."
msgstr ""

#: ../../../bottle.py:docstring of bottle.parse_auth:1
msgid "Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"
msgstr ""

#: ../../../bottle.py:docstring of bottle.cookie_encode:1
msgid "Encode and sign a pickle-able object. Return a (byte) string"
msgstr ""

#: ../../../bottle.py:docstring of bottle.cookie_decode:1
msgid "Verify and decode an encoded string. Return an object or None."
msgstr ""

#: ../../../bottle.py:docstring of bottle.cookie_is_encoded:1
msgid "Return True if the argument looks like a encoded cookie."
msgstr ""

#: ../../../bottle.py:docstring of bottle.yieldroutes:1
msgid "Return a generator for routes that match the signature (name, args) of the func parameter. This may yield more than one route if the function takes optional keyword arguments. The output is best described by example::"
msgstr ""

#: ../../../bottle.py:docstring of bottle.path_shift:1
msgid "Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa."
msgstr ""

#: ../../../bottle.py:docstring of bottle.path_shift:0
msgid "Returns"
msgstr ""

#: ../../../bottle.py:docstring of bottle.path_shift:3
msgid "The modified paths."
msgstr ""

#: ../../../bottle.py:docstring of bottle.path_shift:4
msgid "The SCRIPT_NAME path."
msgstr ""

#: ../../../bottle.py:docstring of bottle.path_shift:5
msgid "The PATH_INFO path."
msgstr ""

#: ../../../bottle.py:docstring of bottle.path_shift:6
msgid "The number of path fragments to shift. May be negative to change the shift direction. (default: 1)"
msgstr ""

#: ../../api.rst:81
msgid "Data Structures"
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict:1
msgid "This dict stores multiple values per key, but behaves exactly like a normal dict in that it returns only the newest value for any given key. There are special methods available to access the full list of values."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.keys:1
msgid "D.keys() -> a set-like object providing a view on D's keys"
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.values:1
msgid "D.values() -> an object providing a view on D's values"
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.items:1
msgid "D.items() -> a set-like object providing a view on D's items"
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.get:1
#: ../../../bottle.py:docstring of bottle.HeaderDict.get:1
msgid "Return the most recent value for a key."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.get:3
#: ../../../bottle.py:docstring of bottle.HeaderDict.get:3
msgid "The default value to be returned if the key is not present or the type conversion fails."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.get:5
#: ../../../bottle.py:docstring of bottle.HeaderDict.get:5
msgid "An index for the list of available values."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.get:6
#: ../../../bottle.py:docstring of bottle.HeaderDict.get:6
msgid "If defined, this callable is used to cast the value into a specific type. Exception are suppressed and result in the default value to be returned."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.append:1
#: ../../../bottle.py:docstring of bottle.HeaderDict.append:1
msgid "Add a new value to the list of values for this key."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.replace:1
#: ../../../bottle.py:docstring of bottle.HeaderDict.replace:1
msgid "Replace the list of values with a single value."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.getall:1
#: ../../../bottle.py:docstring of bottle.MultiDict.getall:1
#: ../../../bottle.py:docstring of bottle.HeaderDict.getall:1
msgid "Return a (possibly empty) list of values for a key."
msgstr ""

#: ../../../bottle.py:docstring of bottle.MultiDict.get:1
msgid "Aliases for WTForms to mimic other multi-dict APIs (Django)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.HeaderDict:1
msgid "A case-insensitive version of :class:`MultiDict` that defaults to replace the old value instead of appending it."
msgstr ""

#: ../../../bottle.py:docstring of bottle.FormsDict:1
msgid "This :class:`MultiDict` subclass is used to store request form data. Additionally to the normal dict-like item access methods (which return unmodified data as native strings), this container also supports attribute-like access to its values. Attributes are automatically de- or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing attributes default to an empty string."
msgstr ""

#: ../../../bottle.py:docstring of bottle.FormsDict.input_encoding:1
msgid "Encoding used for attribute values."
msgstr ""

#: ../../../bottle.py:docstring of bottle.FormsDict.recode_unicode:1
msgid "If true (default), unicode strings are first encoded with `latin1` and then decoded to match :attr:`input_encoding`."
msgstr ""

#: ../../../bottle.py:docstring of bottle.FormsDict.decode:1
msgid "Returns a copy with all keys and values de- or recoded to match :attr:`input_encoding`. Some libraries (e.g. WTForms) want a unicode dictionary."
msgstr ""

#: ../../../bottle.py:docstring of bottle.FormsDict.getunicode:1
msgid "Return the value as a unicode string, or the default."
msgstr ""

#: ../../../bottle.py:docstring of bottle.WSGIHeaderDict:1
msgid "This dict-like class wraps a WSGI environ dict and provides convenient access to HTTP_* fields. Keys and values are native strings (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI environment contains non-native string values, these are de- or encoded using a lossless 'latin1' character set."
msgstr ""

#: ../../../bottle.py:docstring of bottle.WSGIHeaderDict:7
msgid "The API will remain stable even on changes to the relevant PEPs. Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one that uses non-native strings.)"
msgstr ""

#: ../../../bottle.py:docstring of bottle.WSGIHeaderDict.cgikeys:1
msgid "List of keys that do not have a ``HTTP_`` prefix."
msgstr ""

#: ../../../bottle.py:docstring of bottle.WSGIHeaderDict.raw:1
msgid "Return the header value as is (may be bytes or unicode)."
msgstr ""

#: ../../../bottle.py:docstring of bottle.AppStack:1
msgid "A stack-like list. Calling it returns the head of the stack."
msgstr ""

#: ../../api.rst:100
msgid "Return the current default application and remove it from the stack."
msgstr ""

#: ../../../bot
Download .txt
gitextract_gk165kp2/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── run_tests.yml
├── .gitignore
├── .readthedocs.yaml
├── AUTHORS
├── LICENSE
├── Makefile
├── README.rst
├── bottle.py
├── docs/
│   ├── _locale/
│   │   ├── .tx/
│   │   │   └── config
│   │   ├── README.txt
│   │   ├── _pot/
│   │   │   ├── api.pot
│   │   │   ├── async.pot
│   │   │   ├── changelog.pot
│   │   │   ├── configuration.pot
│   │   │   ├── contact.pot
│   │   │   ├── deployment.pot
│   │   │   ├── development.pot
│   │   │   ├── faq.pot
│   │   │   ├── index.pot
│   │   │   ├── plugindev.pot
│   │   │   ├── plugins/
│   │   │   │   └── index.pot
│   │   │   ├── recipes.pot
│   │   │   ├── routing.pot
│   │   │   ├── stpl.pot
│   │   │   ├── tutorial.pot
│   │   │   └── tutorial_app.pot
│   │   ├── de_DE/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── fr/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── ja_JP/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── pt_BR/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── _pot/
│   │   │       │   ├── api.po
│   │   │       │   ├── async.po
│   │   │       │   ├── changelog.po
│   │   │       │   ├── configuration.po
│   │   │       │   ├── contact.po
│   │   │       │   ├── deployment.po
│   │   │       │   ├── development.po
│   │   │       │   ├── faq.po
│   │   │       │   ├── index.po
│   │   │       │   ├── plugindev.po
│   │   │       │   ├── plugins/
│   │   │       │   │   └── index.po
│   │   │       │   ├── recipes.po
│   │   │       │   ├── routing.po
│   │   │       │   ├── stpl.po
│   │   │       │   ├── tutorial.po
│   │   │       │   └── tutorial_app.po
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   ├── requirements.txt
│   │   ├── ru_RU/
│   │   │   └── LC_MESSAGES/
│   │   │       ├── api.po
│   │   │       ├── async.po
│   │   │       ├── changelog.po
│   │   │       ├── configuration.po
│   │   │       ├── contact.po
│   │   │       ├── deployment.po
│   │   │       ├── development.po
│   │   │       ├── faq.po
│   │   │       ├── index.po
│   │   │       ├── plugindev.po
│   │   │       ├── plugins/
│   │   │       │   └── index.po
│   │   │       ├── recipes.po
│   │   │       ├── routing.po
│   │   │       ├── stpl.po
│   │   │       ├── tutorial.po
│   │   │       └── tutorial_app.po
│   │   └── zh_CN/
│   │       └── LC_MESSAGES/
│   │           ├── _pot/
│   │           │   ├── api.po
│   │           │   ├── async.po
│   │           │   ├── changelog.po
│   │           │   ├── configuration.po
│   │           │   ├── contact.po
│   │           │   ├── deployment.po
│   │           │   ├── development.po
│   │           │   ├── faq.po
│   │           │   ├── index.po
│   │           │   ├── plugindev.po
│   │           │   ├── plugins/
│   │           │   │   └── index.po
│   │           │   ├── recipes.po
│   │           │   ├── routing.po
│   │           │   ├── stpl.po
│   │           │   ├── tutorial.po
│   │           │   └── tutorial_app.po
│   │           ├── api.po
│   │           ├── async.po
│   │           ├── changelog.po
│   │           ├── configuration.po
│   │           ├── contact.po
│   │           ├── deployment.po
│   │           ├── development.po
│   │           ├── faq.po
│   │           ├── index.po
│   │           ├── plugindev.po
│   │           ├── plugins/
│   │           │   └── index.po
│   │           ├── recipes.po
│   │           ├── routing.po
│   │           ├── stpl.po
│   │           ├── tutorial.po
│   │           └── tutorial_app.po
│   ├── api.rst
│   ├── async.rst
│   ├── changelog.rst
│   ├── conf.py
│   ├── configuration.rst
│   ├── contributors.rst
│   ├── deployment.rst
│   ├── development.rst
│   ├── faq.rst
│   ├── index.rst
│   ├── plugins/
│   │   ├── dev.rst
│   │   ├── index.rst
│   │   └── list.rst
│   ├── routing.rst
│   ├── stpl.rst
│   ├── tutorial.rst
│   └── tutorial_app.rst
├── pyproject.toml
└── test/
    ├── .coveragerc
    ├── __init__.py
    ├── build_python.sh
    ├── example_settings.py
    ├── test_app.py
    ├── test_auth.py
    ├── test_config.py
    ├── test_contextlocals.py
    ├── test_environ.py
    ├── test_exc.py
    ├── test_fileupload.py
    ├── test_formsdict.py
    ├── test_html_helper.py
    ├── test_importhook.py
    ├── test_jinja2.py
    ├── test_mako.py
    ├── test_mdict.py
    ├── test_mount.py
    ├── test_multipart.py
    ├── test_oorouting.py
    ├── test_outputfilter.py
    ├── test_plugins.py
    ├── test_resources.py
    ├── test_route.py
    ├── test_router.py
    ├── test_securecookies.py
    ├── test_sendfile.py
    ├── test_stpl.py
    ├── test_wsgi.py
    ├── tools.py
    └── views/
        ├── jinja2_base.tpl
        ├── jinja2_inherit.tpl
        ├── jinja2_simple.tpl
        ├── mako_base.tpl
        ├── mako_inherit.tpl
        ├── mako_simple.tpl
        ├── stpl_include.tpl
        ├── stpl_no_vars.tpl
        ├── stpl_simple.tpl
        ├── stpl_t2base.tpl
        ├── stpl_t2inc.tpl
        ├── stpl_t2main.tpl
        └── stpl_unicode.tpl
Download .txt
SYMBOL INDEX (882 symbols across 27 files)

FILE: bottle.py
  function _cli_parse (line 30) | def _cli_parse(args):  # pragma: no coverage
  function _cli_patch (line 52) | def _cli_patch(cli_args):  # pragma: no coverage
  function _wsgi_recode (line 106) | def _wsgi_recode(src):
  function _raise (line 113) | def _raise(*a):
  function tob (line 118) | def tob(s, enc='utf8'):
  function touni (line 124) | def touni(s, enc='utf8', err='strict'):
  function _stderr (line 130) | def _stderr(*args):
  function update_wrapper (line 138) | def update_wrapper(wrapper, wrapped, *a, **ka):
  function depr (line 149) | def depr(major, minor, cause, fix, stacklevel=3):
  function makelist (line 159) | def makelist(data):  # This is just too handy
  class DictProperty (line 168) | class DictProperty:
    method __init__ (line 171) | def __init__(self, attr, key=None, read_only=False):
    method __call__ (line 174) | def __call__(self, func):
    method __get__ (line 179) | def __get__(self, obj, cls):
    method __set__ (line 185) | def __set__(self, obj, value):
    method __delete__ (line 189) | def __delete__(self, obj):
  class cached_property (line 194) | class cached_property:
    method __init__ (line 199) | def __init__(self, func):
    method __get__ (line 203) | def __get__(self, obj, cls):
  class lazy_attribute (line 209) | class lazy_attribute:
    method __init__ (line 212) | def __init__(self, func):
    method __get__ (line 216) | def __get__(self, obj, cls):
  class BottleException (line 227) | class BottleException(Exception):
  class RouteError (line 236) | class RouteError(BottleException):
  class RouterUnknownModeError (line 240) | class RouterUnknownModeError(RouteError):
  class RouteSyntaxError (line 244) | class RouteSyntaxError(RouteError):
  class RouteBuildError (line 248) | class RouteBuildError(RouteError):
  function _re_flatten (line 252) | def _re_flatten(p):
  class Router (line 261) | class Router:
    method __init__ (line 280) | def __init__(self, strict=False):
    method add_filter (line 297) | def add_filter(self, name, func):
    method _itertokens (line 308) | def _itertokens(self, rule):
    method add (line 329) | def add(self, rule, method, target, name=None):
    method _compile (line 405) | def _compile(self, method):
    method build (line 417) | def build(self, _name, *anons, **query):
    method match (line 430) | def match(self, environ):
  class Route (line 467) | class Route:
    method __init__ (line 473) | def __init__(self, app, rule, method, callback,
    method call (line 498) | def call(self):
    method reset (line 503) | def reset(self):
    method prepare (line 508) | def prepare(self):
    method all_plugins (line 512) | def all_plugins(self):
    method _make_callback (line 523) | def _make_callback(self):
    method get_undecorated_callback (line 534) | def get_undecorated_callback(self):
    method get_callback_args (line 555) | def get_callback_args(self):
    method get_config (line 564) | def get_config(self, key, default=None):
    method __repr__ (line 572) | def __repr__(self):
  class Bottle (line 583) | class Bottle:
    method _global_config (line 593) | def _global_config(cls):
    method __init__ (line 598) | def __init__(self, **kwargs):
    method _hooks (line 640) | def _hooks(self):
    method add_hook (line 643) | def add_hook(self, name, func):
    method remove_hook (line 659) | def remove_hook(self, name, func):
    method trigger_hook (line 665) | def trigger_hook(self, __name, *args, **kwargs):
    method hook (line 669) | def hook(self, name):
    method _mount_wsgi (line 679) | def _mount_wsgi(self, prefix, app, **options):
    method _mount_app (line 715) | def _mount_app(self, prefix, app, **options):
    method mount (line 738) | def mount(self, prefix, app, **options):
    method merge (line 768) | def merge(self, routes):
    method install (line 778) | def install(self, plugin):
    method uninstall (line 790) | def uninstall(self, plugin):
    method reset (line 805) | def reset(self, route=None):
    method close (line 819) | def close(self):
    method run (line 824) | def run(self, **kwargs):
    method match (line 828) | def match(self, environ):
    method get_url (line 834) | def get_url(self, routename, **kargs):
    method add_route (line 840) | def add_route(self, route):
    method route (line 847) | def route(self,
    method get (line 898) | def get(self, path=None, method='GET', **options):
    method post (line 902) | def post(self, path=None, method='POST', **options):
    method put (line 906) | def put(self, path=None, method='PUT', **options):
    method delete (line 910) | def delete(self, path=None, method='DELETE', **options):
    method patch (line 914) | def patch(self, path=None, method='PATCH', **options):
    method error (line 918) | def error(self, code=500, callback=None):
    method default_error_handler (line 940) | def default_error_handler(self, res):
    method _handle (line 943) | def _handle(self, environ):
    method _cast (line 984) | def _cast(self, out, peek=None):
    method wsgi (line 1059) | def wsgi(self, environ, start_response):
    method __call__ (line 1091) | def __call__(self, environ, start_response):
    method __enter__ (line 1095) | def __enter__(self):
    method __exit__ (line 1100) | def __exit__(self, exc_type, exc_value, traceback):
    method __setattr__ (line 1103) | def __setattr__(self, name, value):
  class BaseRequest (line 1113) | class BaseRequest:
    method __init__ (line 1127) | def __init__(self, environ=None):
    method app (line 1135) | def app(self):
    method route (line 1140) | def route(self):
    method url_args (line 1145) | def url_args(self):
    method path (line 1150) | def path(self):
    method method (line 1156) | def method(self):
    method headers (line 1161) | def headers(self):
    method get_header (line 1166) | def get_header(self, name, default=None):
    method cookies (line 1171) | def cookies(self):
    method get_cookie (line 1178) | def get_cookie(self, key, default=None, secret=None, digestmod=hashlib...
    method query (line 1197) | def query(self):
    method forms (line 1209) | def forms(self):
    method params (line 1221) | def params(self):
    method files (line 1232) | def files(self):
    method json (line 1244) | def json(self):
    method _iter_body (line 1262) | def _iter_body(self, read, bufsize):
    method _iter_chunked (line 1271) | def _iter_chunked(read, bufsize):
    method _body (line 1299) | def _body(self):
    method _get_body_string (line 1319) | def _get_body_string(self, maxread):
    method body (line 1330) | def body(self):
    method chunked (line 1340) | def chunked(self):
    method POST (line 1349) | def POST(self):
    method url (line 1383) | def url(self):
    method urlparts (line 1391) | def urlparts(self):
    method fullpath (line 1409) | def fullpath(self):
    method query_string (line 1414) | def query_string(self):
    method script_name (line 1420) | def script_name(self):
    method path_shift (line 1428) | def path_shift(self, shift=1):
    method content_length (line 1439) | def content_length(self):
    method content_type (line 1446) | def content_type(self):
    method is_xhr (line 1451) | def is_xhr(self):
    method is_ajax (line 1459) | def is_ajax(self):
    method auth (line 1464) | def auth(self):
    method remote_route (line 1478) | def remote_route(self):
    method remote_addr (line 1489) | def remote_addr(self):
    method copy (line 1495) | def copy(self):
    method get (line 1499) | def get(self, key, default=None):
    method __getitem__ (line 1502) | def __getitem__(self, key):
    method __delitem__ (line 1505) | def __delitem__(self, key):
    method __iter__ (line 1509) | def __iter__(self):
    method __len__ (line 1512) | def __len__(self):
    method keys (line 1515) | def keys(self):
    method __setitem__ (line 1518) | def __setitem__(self, key, value):
    method __repr__ (line 1537) | def __repr__(self):
    method __getattr__ (line 1540) | def __getattr__(self, name):
    method __setattr__ (line 1548) | def __setattr__(self, name, value):
    method __delattr__ (line 1556) | def __delattr__(self, name):
  function _hkey (line 1563) | def _hkey(key):
  function _hval (line 1570) | def _hval(value):
  class HeaderProperty (line 1577) | class HeaderProperty:
    method __init__ (line 1578) | def __init__(self, name, reader=None, writer=None, default=''):
    method __get__ (line 1583) | def __get__(self, obj, _):
    method __set__ (line 1588) | def __set__(self, obj, value):
    method __delete__ (line 1591) | def __delete__(self, obj):
  class BaseResponse (line 1595) | class BaseResponse:
    method __init__ (line 1615) | def __init__(self, body='', status=None, headers=None, **more_headers):
    method copy (line 1639) | def copy(self, cls=None):
    method __iter__ (line 1653) | def __iter__(self):
    method close (line 1656) | def close(self):
    method status_line (line 1661) | def status_line(self):
    method status_code (line 1666) | def status_code(self):
    method _set_status (line 1670) | def _set_status(self, status):
    method _get_status (line 1685) | def _get_status(self):
    method headers (line 1698) | def headers(self):
    method __contains__ (line 1705) | def __contains__(self, name):
    method __delitem__ (line 1708) | def __delitem__(self, name):
    method __getitem__ (line 1711) | def __getitem__(self, name):
    method __setitem__ (line 1714) | def __setitem__(self, name, value):
    method get_header (line 1717) | def get_header(self, name, default=None):
    method set_header (line 1722) | def set_header(self, name, value):
    method add_header (line 1727) | def add_header(self, name, value):
    method iter_headers (line 1731) | def iter_headers(self):
    method _wsgi_status_line (line 1736) | def _wsgi_status_line(self):
    method headerlist (line 1741) | def headerlist(self):
    method charset (line 1765) | def charset(self, default='UTF-8'):
    method set_cookie (line 1771) | def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha25...
    method delete_cookie (line 1852) | def delete_cookie(self, key, **kwargs):
    method __repr__ (line 1859) | def __repr__(self):
  function _local_property (line 1866) | def _local_property():
  class LocalRequest (line 1884) | class LocalRequest(BaseRequest):
  class LocalResponse (line 1894) | class LocalResponse(BaseResponse):
  class HTTPResponse (line 1912) | class HTTPResponse(Response, BottleException):
    method __init__ (line 1920) | def __init__(self, body='', status=None, headers=None, **more_headers):
    method apply (line 1923) | def apply(self, other):
  class HTTPError (line 1932) | class HTTPError(HTTPResponse):
    method __init__ (line 1937) | def __init__(self,
  class PluginError (line 1951) | class PluginError(BottleException):
  class JSONPlugin (line 1955) | class JSONPlugin:
    method __init__ (line 1959) | def __init__(self, json_dumps=json_dumps):
    method setup (line 1962) | def setup(self, app):
    method apply (line 1974) | def apply(self, callback, route):
  class TemplatePlugin (line 1999) | class TemplatePlugin:
    method setup (line 2007) | def setup(self, app):
    method apply (line 2010) | def apply(self, callback, route):
  class _ImportRedirect (line 2021) | class _ImportRedirect:
    method __init__ (line 2022) | def __init__(self, name, impmask):
    method find_spec (line 2035) | def find_spec(self, fullname, path, target=None):
    method find_module (line 2041) | def find_module(self, fullname, path=None):
    method create_module (line 2046) | def create_module(self, spec):
    method exec_module (line 2049) | def exec_module(self, module):
    method load_module (line 2052) | def load_module(self, fullname):
  class MultiDict (line 2067) | class MultiDict(DictMixin):
    method __init__ (line 2073) | def __init__(self, *a, **k):
    method __len__ (line 2076) | def __len__(self):
    method __iter__ (line 2079) | def __iter__(self):
    method __contains__ (line 2082) | def __contains__(self, key):
    method __delitem__ (line 2085) | def __delitem__(self, key):
    method __getitem__ (line 2088) | def __getitem__(self, key):
    method __setitem__ (line 2091) | def __setitem__(self, key, value):
    method keys (line 2094) | def keys(self):
    method values (line 2097) | def values(self):
    method items (line 2100) | def items(self):
    method allitems (line 2103) | def allitems(self):
    method get (line 2111) | def get(self, key, default=None, index=-1, type=None):
    method append (line 2128) | def append(self, key, value):
    method replace (line 2132) | def replace(self, key, value):
    method getall (line 2136) | def getall(self, key):
  class FormsDict (line 2145) | class FormsDict(MultiDict):
    method decode (line 2156) | def decode(self, encoding=None):
    method getunicode (line 2164) | def getunicode(self, name, default=None, encoding=None):
    method __getattr__ (line 2168) | def __getattr__(self, name, default=str()):
  class HeaderDict (line 2175) | class HeaderDict(MultiDict):
    method __init__ (line 2179) | def __init__(self, *a, **ka):
    method __contains__ (line 2183) | def __contains__(self, key):
    method __delitem__ (line 2186) | def __delitem__(self, key):
    method __getitem__ (line 2189) | def __getitem__(self, key):
    method __setitem__ (line 2192) | def __setitem__(self, key, value):
    method append (line 2195) | def append(self, key, value):
    method replace (line 2198) | def replace(self, key, value):
    method getall (line 2201) | def getall(self, key):
    method get (line 2204) | def get(self, key, default=None, index=-1):
    method filter (line 2207) | def filter(self, names):
  class WSGIHeaderDict (line 2213) | class WSGIHeaderDict(DictMixin):
    method __init__ (line 2220) | def __init__(self, environ):
    method _ekey (line 2223) | def _ekey(self, key):
    method raw (line 2230) | def raw(self, key, default=None):
    method __getitem__ (line 2234) | def __getitem__(self, key):
    method __setitem__ (line 2237) | def __setitem__(self, key, value):
    method __delitem__ (line 2240) | def __delitem__(self, key):
    method __iter__ (line 2243) | def __iter__(self):
    method keys (line 2250) | def keys(self):
    method __len__ (line 2253) | def __len__(self):
    method __contains__ (line 2256) | def __contains__(self, key):
  class ConfigDict (line 2260) | class ConfigDict(dict):
    method __init__ (line 2270) | def __init__(self):
    method load_module (line 2280) | def load_module(self, name, squash=True):
    method load_config (line 2300) | def load_config(self, filename, **options):
    method load_dict (line 2328) | def load_dict(self, source, namespace=''):
    method update (line 2347) | def update(self, *a, **ka):
    method setdefault (line 2361) | def setdefault(self, key, value=None):
    method __setitem__ (line 2366) | def __setitem__(self, key, value):
    method __delitem__ (line 2382) | def __delitem__(self, key):
    method _set_virtual (line 2398) | def _set_virtual(self, key, value):
    method _delete_virtual (line 2410) | def _delete_virtual(self, key):
    method _on_change (line 2422) | def _on_change(self, key, value):
    method _add_change_listener (line 2427) | def _add_change_listener(self, func):
    method meta_get (line 2431) | def meta_get(self, key, metafield, default=None):
    method meta_set (line 2435) | def meta_set(self, key, metafield, value):
    method meta_list (line 2442) | def meta_list(self, key):
    method _define (line 2446) | def _define(self, key, default=_UNSET, help=_UNSET, validate=_UNSET):
    method _iter_overlays (line 2455) | def _iter_overlays(self):
    method _make_overlay (line 2461) | def _make_overlay(self):
  class AppStack (line 2497) | class AppStack(list):
    method __call__ (line 2500) | def __call__(self):
    method push (line 2504) | def push(self, value=None):
    method default (line 2513) | def default(self):
  class WSGIFileWrapper (line 2520) | class WSGIFileWrapper:
    method __init__ (line 2521) | def __init__(self, fp, buffer_size=1024 * 64):
    method __iter__ (line 2526) | def __iter__(self):
  class _closeiter (line 2534) | class _closeiter:
    method __init__ (line 2538) | def __init__(self, iterator, close=None):
    method __iter__ (line 2542) | def __iter__(self):
    method close (line 2545) | def close(self):
  function _try_close (line 2550) | def _try_close(obj):
  class ResourceManager (line 2559) | class ResourceManager:
    method __init__ (line 2569) | def __init__(self, base='./', opener=open, cachemode='all'):
    method add_path (line 2579) | def add_path(self, path, base=None, index=None, create=False):
    method __iter__ (line 2610) | def __iter__(self):
    method lookup (line 2621) | def lookup(self, name):
    method open (line 2638) | def open(self, name, mode='r', *args, **kwargs):
  class FileUpload (line 2645) | class FileUpload:
    method __init__ (line 2646) | def __init__(self, fileobj, name, filename, headers=None):
    method get_header (line 2660) | def get_header(self, name, default=None):
    method filename (line 2665) | def filename(self):
    method _copy_file (line 2682) | def _copy_file(self, fp, chunk_size=2 ** 16):
    method save (line 2690) | def save(self, destination, overwrite=False, chunk_size=2 ** 16):
  function abort (line 2714) | def abort(code=500, text='Unknown Error.'):
  function redirect (line 2719) | def redirect(url, code=None):
  function _rangeiter (line 2731) | def _rangeiter(fp, offset, limit, bufsize=1024 * 1024):
  function static_file (line 2742) | def static_file(filename, root,
  function debug (line 2856) | def debug(mode=True):
  function http_date (line 2864) | def http_date(value):
  function parse_date (line 2880) | def parse_date(ims):
  function parse_auth (line 2889) | def parse_auth(header):
  function parse_range_header (line 2900) | def parse_range_header(header, maxlen=0):
  function _parse_http_header (line 2923) | def _parse_http_header(h):
  function _parse_qsl (line 2956) | def _parse_qsl(qs, encoding="utf8"):
  function _lscmp (line 2968) | def _lscmp(a, b):
  function cookie_encode (line 2975) | def cookie_encode(data, key, digestmod=None):
  function cookie_decode (line 2985) | def cookie_decode(data, key, digestmod=None):
  function cookie_is_encoded (line 2999) | def cookie_is_encoded(data):
  function html_escape (line 3006) | def html_escape(string):
  function html_quote (line 3012) | def html_quote(string):
  function yieldroutes (line 3018) | def yieldroutes(func):
  function path_shift (line 3040) | def path_shift(script_name, path_info, shift=1):
  function auth_basic (line 3071) | def auth_basic(check, realm="private", text="Access denied"):
  function make_default_app_wrapper (line 3094) | def make_default_app_wrapper(name):
  class MultipartError (line 3125) | class MultipartError(HTTPError):
    method __init__ (line 3126) | def __init__(self, msg):
  class _MultipartParser (line 3130) | class _MultipartParser:
    method __init__ (line 3131) | def __init__(
    method _lineiter (line 3157) | def _lineiter(self):
    method parse (line 3194) | def parse(self):
  class _MultipartPart (line 3254) | class _MultipartPart:
    method __init__ (line 3255) | def __init__(self, buffer_size=2 ** 16, memfile_limit=2 ** 18, charset...
    method feed (line 3269) | def feed(self, line, nl=""):
    method write_header (line 3274) | def write_header(self, line, nl):
    method write_body (line 3292) | def write_body(self, line, nl):
    method finish_header (line 3314) | def finish_header(self):
    method finish (line 3335) | def finish(self):
    method is_buffered (line 3340) | def is_buffered(self):
    method value (line 3345) | def value(self):
    method raw (line 3350) | def raw(self):
    method close (line 3360) | def close(self):
  class ServerAdapter (line 3374) | class ServerAdapter:
    method __init__ (line 3377) | def __init__(self, host='127.0.0.1', port=8080, **options):
    method run (line 3382) | def run(self, handler):  # pragma: no cover
    method _listen_url (line 3386) | def _listen_url(self):
    method __repr__ (line 3394) | def __repr__(self):
  class CGIServer (line 3399) | class CGIServer(ServerAdapter):
    method run (line 3402) | def run(self, handler):  # pragma: no cover
  class FlupFCGIServer (line 3412) | class FlupFCGIServer(ServerAdapter):
    method run (line 3413) | def run(self, handler):  # pragma: no cover
  class WSGIRefServer (line 3419) | class WSGIRefServer(ServerAdapter):
    method run (line 3420) | def run(self, app):  # pragma: no cover
  class CherryPyServer (line 3449) | class CherryPyServer(ServerAdapter):
    method run (line 3450) | def run(self, handler):  # pragma: no cover
  class CherootServer (line 3478) | class CherootServer(ServerAdapter):
    method run (line 3479) | def run(self, handler):  # pragma: no cover
  class WaitressServer (line 3497) | class WaitressServer(ServerAdapter):
    method run (line 3498) | def run(self, handler):
  class PasteServer (line 3503) | class PasteServer(ServerAdapter):
    method run (line 3504) | def run(self, handler):  # pragma: no cover
  class MeinheldServer (line 3513) | class MeinheldServer(ServerAdapter):
    method run (line 3514) | def run(self, handler):
  class FapwsServer (line 3520) | class FapwsServer(ServerAdapter):
    method run (line 3523) | def run(self, handler):  # pragma: no cover
  class TornadoServer (line 3546) | class TornadoServer(ServerAdapter):
    method run (line 3549) | def run(self, handler):  # pragma: no cover
  class AppEngineServer (line 3557) | class AppEngineServer(ServerAdapter):
    method run (line 3561) | def run(self, handler):
  class TwistedServer (line 3573) | class TwistedServer(ServerAdapter):
    method run (line 3576) | def run(self, handler):
  class DieselServer (line 3589) | class DieselServer(ServerAdapter):
    method run (line 3592) | def run(self, handler):
  class GeventServer (line 3599) | class GeventServer(ServerAdapter):
    method run (line 3605) | def run(self, handler):
  class GunicornServer (line 3620) | class GunicornServer(ServerAdapter):
    method run (line 3623) | def run(self, handler):
  class EventletServer (line 3644) | class EventletServer(ServerAdapter):
    method run (line 3654) | def run(self, handler):
  class BjoernServer (line 3674) | class BjoernServer(ServerAdapter):
    method run (line 3677) | def run(self, handler):
  class AsyncioServerAdapter (line 3682) | class AsyncioServerAdapter(ServerAdapter):
    method get_event_loop (line 3684) | def get_event_loop(self):
  class AiohttpServer (line 3688) | class AiohttpServer(AsyncioServerAdapter):
    method get_event_loop (line 3694) | def get_event_loop(self):
    method run (line 3698) | def run(self, handler):
  class AiohttpUVLoopServer (line 3711) | class AiohttpUVLoopServer(AiohttpServer):
    method get_event_loop (line 3715) | def get_event_loop(self):
  class AutoServer (line 3720) | class AutoServer(ServerAdapter):
    method run (line 3725) | def run(self, handler):
  function load (line 3761) | def load(target, **namespace):
  function load_app (line 3781) | def load_app(target):
  function run (line 3799) | def run(app=None,
  class FileCheckerThread (line 3908) | class FileCheckerThread(threading.Thread):
    method __init__ (line 3912) | def __init__(self, lockfile, interval):
    method run (line 3919) | def run(self):
    method __enter__ (line 3941) | def __enter__(self):
    method __exit__ (line 3944) | def __exit__(self, exc_type, *_):
  class TemplateError (line 3954) | class TemplateError(BottleException):
  class BaseTemplate (line 3958) | class BaseTemplate:
    method __init__ (line 3964) | def __init__(self,
    method search (line 3995) | def search(cls, name, lookup=None):
    method global_config (line 4015) | def global_config(cls, key, *args):
    method prepare (line 4023) | def prepare(self, **options):
    method render (line 4030) | def render(self, *args, **kwargs):
  class MakoTemplate (line 4040) | class MakoTemplate(BaseTemplate):
    method prepare (line 4041) | def prepare(self, **options):
    method render (line 4054) | def render(self, *args, **kwargs):
  class CheetahTemplate (line 4062) | class CheetahTemplate(BaseTemplate):
    method prepare (line 4063) | def prepare(self, **options):
    method render (line 4073) | def render(self, *args, **kwargs):
  class Jinja2Template (line 4083) | class Jinja2Template(BaseTemplate):
    method prepare (line 4084) | def prepare(self, filters=None, tests=None, globals={}, **kwargs):
    method render (line 4095) | def render(self, *args, **kwargs):
    method loader (line 4102) | def loader(self, name):
  class SimpleTemplate (line 4112) | class SimpleTemplate(BaseTemplate):
    method prepare (line 4113) | def prepare(self,
    method co (line 4126) | def co(self):
    method code (line 4130) | def code(self):
    method _rebase (line 4144) | def _rebase(self, _env, _name=None, **kwargs):
    method _include (line 4147) | def _include(self, _env, _name=None, **kwargs):
    method execute (line 4154) | def execute(self, _stdout, kwargs):
    method render (line 4177) | def render(self, *args, **kwargs):
  class StplSyntaxError (line 4188) | class StplSyntaxError(TemplateError):
  class StplParser (line 4192) | class StplParser:
    method __init__ (line 4241) | def __init__(self, source, syntax=None, encoding='utf8'):
    method get_syntax (line 4249) | def get_syntax(self):
    method set_syntax (line 4253) | def set_syntax(self, syntax):
    method translate (line 4267) | def translate(self):
    method read_code (line 4290) | def read_code(self, pysource, multiline):
    method flush_text (line 4343) | def flush_text(self):
    method process_inline (line 4365) | def process_inline(chunk):
    method write_code (line 4369) | def write_code(self, line, comment=''):
  function template (line 4375) | def template(*args, **kwargs):
  function view (line 4408) | def view(tpl_name, **defaults):
  function _main (line 4524) | def _main(argv):  # pragma: no coverage
  function main (line 4578) | def main():

FILE: test/test_app.py
  class TestApplicationObject (line 10) | class TestApplicationObject(unittest.TestCase):
    method test_setattr (line 12) | def test_setattr(self):

FILE: test/test_auth.py
  class TestBasicAuth (line 5) | class TestBasicAuth(ServerTestBase):
    method test__header (line 7) | def test__header(self):

FILE: test/test_config.py
  class TestConfDict (line 7) | class TestConfDict(unittest.TestCase):
    method test_isadict (line 8) | def test_isadict(self):
    method test_write (line 31) | def test_write(self):
    method test_update (line 39) | def test_update(self):
    method test_string_save_keys (line 46) | def test_string_save_keys(self):
    method test_namespaces (line 53) | def test_namespaces(self):
    method test_meta (line 58) | def test_meta(self):
    method test_load_dict (line 68) | def test_load_dict(self):
    method test_load_module (line 87) | def test_load_module(self):
    method test_overlay (line 96) | def test_overlay(self):
    method test_gc_overlays (line 158) | def test_gc_overlays(self):
  class TestINIConfigLoader (line 167) | class TestINIConfigLoader(unittest.TestCase):
    method setUpClass (line 169) | def setUpClass(self):
    method tearDownClass (line 186) | def tearDownClass(self):
    method test_load_config (line 190) | def test_load_config(self):

FILE: test/test_contextlocals.py
  function run_thread (line 11) | def run_thread(func):
  class TestThreadLocals (line 16) | class TestThreadLocals(unittest.TestCase):
    method test_request (line 17) | def test_request(self):
    method test_response (line 30) | def test_response(self):

FILE: test/test_environ.py
  class TestRequest (line 18) | class TestRequest(unittest.TestCase):
    method test_app_property (line 20) | def test_app_property(self):
    method test_route_property (line 27) | def test_route_property(self):
    method test_url_for_property (line 32) | def test_url_for_property(self):
    method test_path (line 39) | def test_path(self):
    method test_method (line 52) | def test_method(self):
    method test_script_name (line 60) | def test_script_name(self):
    method test_pathshift (line 73) | def test_pathshift(self):
    method test_url (line 92) | def test_url(self):
    method test_dict_access (line 109) | def test_dict_access(self):
    method test_readonly_environ (line 124) | def test_readonly_environ(self):
    method test_header_access (line 129) | def test_header_access(self):
    method test_header_access_special (line 140) | def test_header_access_special(self):
    method test_cookie_dict (line 149) | def test_cookie_dict(self):
    method test_get (line 161) | def test_get(self):
    method test_post (line 174) | def test_post(self):
    method test_bodypost (line 195) | def test_bodypost(self):
    method test_body_noclose (line 206) | def test_body_noclose(self):
    method test_params (line 220) | def test_params(self):
    method test_getpostleak (line 233) | def test_getpostleak(self):
    method test_body (line 246) | def test_body(self):
    method test_bigbody (line 259) | def test_bigbody(self):
    method test_tobigbody (line 273) | def test_tobigbody(self):
    method _test_chunked (line 286) | def _test_chunked(self, body, expect):
    method test_chunked (line 297) | def test_chunked(self):
    method test_chunked_meta_fields (line 303) | def test_chunked_meta_fields(self):
    method test_chunked_not_terminated (line 308) | def test_chunked_not_terminated(self):
    method test_chunked_wrong_size (line 311) | def test_chunked_wrong_size(self):
    method test_chunked_illegal_size (line 314) | def test_chunked_illegal_size(self):
    method test_chunked_not_chunked_at_all (line 317) | def test_chunked_not_chunked_at_all(self):
    method test_multipart (line 320) | def test_multipart(self):
    method test_json_empty (line 360) | def test_json_empty(self):
    method test_json_noheader (line 364) | def test_json_noheader(self):
    method test_json_tobig (line 374) | def test_json_tobig(self):
    method test_json_valid (line 384) | def test_json_valid(self):
    method test_json_forged_header_issue616 (line 394) | def test_json_forged_header_issue616(self):
    method test_json_header_empty_body (line 403) | def test_json_header_empty_body(self):
    method test_isajax (line 411) | def test_isajax(self):
    method test_auth (line 418) | def test_auth(self):
    method test_remote_route (line 430) | def test_remote_route(self):
    method test_remote_addr (line 441) | def test_remote_addr(self):
    method test_user_defined_attributes (line 452) | def test_user_defined_attributes(self):
  class TestResponse (line 471) | class TestResponse(unittest.TestCase):
    method test_constructor_body (line 473) | def test_constructor_body(self):
    method test_constructor_status (line 480) | def test_constructor_status(self):
    method test_constructor_headerlist (line 493) | def test_constructor_headerlist(self):
    method test_wsgi_header_values (line 499) | def test_wsgi_header_values(self):
    method test_set_status (line 512) | def test_set_status(self):
    method test_content_type (line 588) | def test_content_type(self):
    method test_charset (line 593) | def test_charset(self):
    method test_set_cookie (line 601) | def test_set_cookie(self):
    method test_set_cookie_value_long_string (line 611) | def test_set_cookie_value_long_string(self):
    method test_set_cookie_name_long_string (line 615) | def test_set_cookie_name_long_string(self):
    method test_set_cookie_maxage (line 619) | def test_set_cookie_maxage(self):
    method test_set_cookie_expires (line 629) | def test_set_cookie_expires(self):
    method test_set_cookie_secure (line 639) | def test_set_cookie_secure(self):
    method test_set_cookie_httponly (line 648) | def test_set_cookie_httponly(self):
    method test_set_cookie_samesite (line 659) | def test_set_cookie_samesite(self):
    method test_clone_cookie (line 675) | def test_clone_cookie(self):
    method test_delete_cookie (line 683) | def test_delete_cookie(self):
    method test_set_header (line 691) | def test_set_header(self):
    method test_append_header (line 705) | def test_append_header(self):
    method test_delete_header (line 719) | def test_delete_header(self):
    method test_non_string_header (line 726) | def test_non_string_header(self):
    method test_prevent_control_characters_in_headers (line 735) | def test_prevent_control_characters_in_headers(self):
    method test_expires_header (line 757) | def test_expires_header(self):
  class TestRedirect (line 774) | class TestRedirect(unittest.TestCase):
    method assertRedirect (line 776) | def assertRedirect(self, target, result, query=None, status=303, **args):
    method test_absolute_path (line 792) | def test_absolute_path(self):
    method test_relative_path (line 805) | def test_relative_path(self):
    method test_sheme (line 832) | def test_sheme(self):
    method test_host_http_1_0 (line 838) | def test_host_http_1_0(self):
    method test_host_http_1_1 (line 847) | def test_host_http_1_1(self):
    method test_host_http_proxy (line 858) | def test_host_http_proxy(self):
    method test_specialchars (line 864) | def test_specialchars(self):
    method test_redirect_preserve_cookies (line 870) | def test_redirect_preserve_cookies(self):
  class TestWSGIHeaderDict (line 881) | class TestWSGIHeaderDict(unittest.TestCase):
    method setUp (line 882) | def setUp(self):
    method test_empty (line 886) | def test_empty(self):
    method test_native (line 889) | def test_native(self):
    method test_unicode (line 893) | def test_unicode(self):
    method test_dict (line 897) | def test_dict(self):

FILE: test/test_exc.py
  class SomeError (line 4) | class SomeError(Exception):
  class TestAppException (line 7) | class TestAppException(ServerTestBase):
    method test_no_exc (line 9) | def test_no_exc(self):
    method test_memory_error (line 14) | def test_memory_error(self):
    method test_system_Exit (line 20) | def test_system_Exit(self):
    method test_other_error (line 26) | def test_other_error(self):
    method test_noncatched_error (line 32) | def test_noncatched_error(self):

FILE: test/test_fileupload.py
  class TestFileUpload (line 10) | class TestFileUpload(unittest.TestCase):
    method test_name (line 11) | def test_name(self):
    method test_raw_filename (line 14) | def test_raw_filename(self):
    method test_content_type (line 17) | def test_content_type(self):
    method assertFilename (line 21) | def assertFilename(self, bad, good):
    method test_filename (line 25) | def test_filename(self):
    method test_preserve_case_issue_582 (line 40) | def test_preserve_case_issue_582(self):
    method test_save_buffer (line 43) | def test_save_buffer(self):
    method test_save_file (line 50) | def test_save_file(self):
    method test_save_overwrite_lock (line 57) | def test_save_overwrite_lock(self):
    method test_save_dir (line 61) | def test_save_dir(self):

FILE: test/test_formsdict.py
  class TestFormsDict (line 7) | class TestFormsDict(unittest.TestCase):
    method test_attr_access (line 8) | def test_attr_access(self):
    method test_attr_missing (line 14) | def test_attr_missing(self):

FILE: test/test_html_helper.py
  class TestHttpUtils (line 6) | class TestHttpUtils(unittest.TestCase):
    method test_accept_header (line 10) | def test_accept_header(self):

FILE: test/test_importhook.py
  class TestImportHooks (line 6) | class TestImportHooks(unittest.TestCase):
    method make_module (line 8) | def make_module(self, name, **args):
    method test_direkt_import (line 14) | def test_direkt_import(self):
    method test_from_import (line 19) | def test_from_import(self):
    method test_data_import (line 24) | def test_data_import(self):
    method test_import_fail (line 29) | def test_import_fail(self):
    method test_ext_isfile (line 35) | def test_ext_isfile(self):

FILE: test/test_jinja2.py
  class TestJinja2Template (line 8) | class TestJinja2Template(unittest.TestCase):
    method test_string (line 10) | def test_string(self):
    method test_file (line 15) | def test_file(self):
    method test_name (line 21) | def test_name(self):
    method test_notfound (line 27) | def test_notfound(self):
    method test_error (line 31) | def test_error(self):
    method test_inherit (line 35) | def test_inherit(self):
    method test_custom_filters (line 41) | def test_custom_filters(self):
    method test_custom_tests (line 48) | def test_custom_tests(self):
    method test_template_shortcut (line 57) | def test_template_shortcut(self):
    method test_view_decorator (line 61) | def test_view_decorator(self):

FILE: test/test_mako.py
  class TestMakoTemplate (line 6) | class TestMakoTemplate(unittest.TestCase):
    method test_string (line 7) | def test_string(self):
    method test_file (line 12) | def test_file(self):
    method test_name (line 18) | def test_name(self):
    method test_notfound (line 24) | def test_notfound(self):
    method test_error (line 28) | def test_error(self):
    method test_inherit (line 32) | def test_inherit(self):
    method test_template_shortcut (line 42) | def test_template_shortcut(self):
    method test_view_decorator (line 46) | def test_view_decorator(self):

FILE: test/test_mdict.py
  class TestMultiDict (line 4) | class TestMultiDict(unittest.TestCase):
    method test_isadict (line 5) | def test_isadict(self):
    method test_ismulti (line 24) | def test_ismulti(self):
    method test_isheader (line 32) | def test_isheader(self):
    method test_headergetbug (line 41) | def test_headergetbug(self):

FILE: test/test_mount.py
  class TestAppMounting (line 6) | class TestAppMounting(ServerTestBase):
    method setUp (line 7) | def setUp(self):
    method test_mount_unicode_path_bug602 (line 16) | def test_mount_unicode_path_bug602(self):
    method test_mount_order_bug581 (line 22) | def test_mount_order_bug581(self):
    method test_mount (line 31) | def test_mount(self):
    method test_mount_meta (line 40) | def test_mount_meta(self):
    method test_no_slash_prefix (line 48) | def test_no_slash_prefix(self):
    method test_mount_no_plugins (line 58) | def test_mount_no_plugins(self):
    method test_mount_wsgi (line 69) | def test_mount_wsgi(self):
    method test_mount_cookie (line 81) | def test_mount_cookie(self):
    method test_mount_wsgi_ctype_bug (line 90) | def test_mount_wsgi_ctype_bug(self):
    method test_mount_json_bug (line 98) | def test_mount_json_bug(self):
    method test_mount_get_url (line 105) | def test_mount_get_url(self):
  class TestAppMerging (line 114) | class TestAppMerging(ServerTestBase):
    method setUp (line 115) | def setUp(self):
    method test_merge (line 123) | def test_merge(self):

FILE: test/test_multipart.py
  class BaseMultipartTest (line 9) | class BaseMultipartTest(unittest.TestCase):
    method setUp (line 10) | def setUp(self):
    method reset (line 13) | def reset(self):
    method write (line 17) | def write(self, *lines):
    method parse (line 21) | def parse(self, ctype=None, clen=-1, **kwargs):
    method assertFile (line 30) | def assertFile(self, name, filename, ctype, data):
    method assertForm (line 40) | def assertForm(self, name, data):
  class TestHeaderParser (line 52) | class TestHeaderParser(BaseMultipartTest):
    method test_options_parser (line 54) | def test_options_parser(self):
  class TestMultipartParser (line 67) | class TestMultipartParser(BaseMultipartTest):
    method assertIterline (line 69) | def assertIterline(self, data, *expected, **options):
    method test_iterlines (line 74) | def test_iterlines(self):
    method test_iterlines_limit (line 77) | def test_iterlines_limit(self):
    method test_fuzzy_lineiter (line 81) | def test_fuzzy_lineiter(self):
    method test_big_file (line 103) | def test_big_file(self):
    method test_file_seek (line 129) | def test_file_seek(self):
    method test_unicode_value (line 141) | def test_unicode_value(self):
    method test_multiline_header (line 154) | def test_multiline_header(self):
  class TestBrokenMultipart (line 175) | class TestBrokenMultipart(BaseMultipartTest):
    method assertMPError (line 177) | def assertMPError(self, **ka):
    method test_big_boundary (line 180) | def test_big_boundary(self):
    method test_missing_content_type (line 183) | def test_missing_content_type(self):
    method test_unsupported_content_type (line 186) | def test_unsupported_content_type(self):
    method test_missing_boundary (line 189) | def test_missing_boundary(self):
    method test_no_terminator (line 192) | def test_no_terminator(self):
    method test_no_newline_after_content (line 198) | def test_no_newline_after_content(self):
    method test_no_newline_after_middle_content (line 204) | def test_no_newline_after_middle_content(self):
    method test_preamble_before_start_boundary (line 214) | def test_preamble_before_start_boundary(self):
    method test_no_start_boundary (line 224) | def test_no_start_boundary(self):
    method test_disk_limit (line 230) | def test_disk_limit(self):
    method test_mem_limit (line 236) | def test_mem_limit(self):
    method test_invalid_header (line 244) | def test_invalid_header(self):
    method test_content_length_to_small (line 251) | def test_content_length_to_small(self):
    method test_no_disposition_header (line 258) | def test_no_disposition_header(self):
  class TestWerkzeugExamples (line 694) | class TestWerkzeugExamples(BaseMultipartTest):
    method test_werkzeug_examples (line 695) | def test_werkzeug_examples(self):

FILE: test/test_oorouting.py
  class TestRouter (line 17) | class TestRouter(object):
    method route_1 (line 25) | def route_1(self, msg):
  class TestRoutes (line 30) | class TestRoutes(unittest.TestCase):
    method test_route1 (line 31) | def test_route1(self):

FILE: test/test_outputfilter.py
  class TestOutputFilter (line 16) | class TestOutputFilter(ServerTestBase):
    method test_bytes (line 19) | def test_bytes(self):
    method test_bytearray (line 23) | def test_bytearray(self):
    method test_tuple (line 27) | def test_tuple(self):
    method test_emptylist (line 31) | def test_emptylist(self):
    method test_none (line 35) | def test_none(self):
    method test_illegal (line 39) | def test_illegal(self):
    method test_error (line 44) | def test_error(self):
    method test_fatal_error (line 50) | def test_fatal_error(self):
    method test_file (line 55) | def test_file(self):
    method test_unicode (line 59) | def test_unicode(self):
    method test_json (line 78) | def test_json(self):
    method test_json_serialization_error (line 85) | def test_json_serialization_error(self):
    method test_json_HTTPResponse (line 96) | def test_json_HTTPResponse(self):
    method test_json_HTTPError (line 102) | def test_json_HTTPError(self):
    method test_generator_callback (line 109) | def test_generator_callback(self):
    method test_empty_generator_callback (line 117) | def test_empty_generator_callback(self):
    method test_error_in_generator_callback (line 125) | def test_error_in_generator_callback(self):
    method test_fatal_error_in_generator_callback (line 132) | def test_fatal_error_in_generator_callback(self):
    method test_httperror_in_generator_callback (line 139) | def test_httperror_in_generator_callback(self):
    method test_httpresponse_in_generator_callback (line 148) | def test_httpresponse_in_generator_callback(self):
    method test_unicode_generator_callback (line 154) | def test_unicode_generator_callback(self):
    method test_invalid_generator_callback (line 160) | def test_invalid_generator_callback(self):
    method test_iterator_with_close (line 167) | def test_iterator_with_close(self):
    method test_cookie (line 184) | def test_cookie(self):

FILE: test/test_plugins.py
  class MyPlugin (line 8) | class MyPlugin(object):
    method __init__ (line 9) | def __init__(self):
    method setup (line 14) | def setup(self, app):
    method apply (line 17) | def apply(self, func, config):
  function my_decorator (line 25) | def my_decorator(func):
  class TestPluginManagement (line 31) | class TestPluginManagement(tools.ServerTestBase):
    method verify_installed (line 33) | def verify_installed(self, plugin, otype, **config):
    method test_install_plugin (line 39) | def test_install_plugin(self):
    method test_install_decorator (line 45) | def test_install_decorator(self):
    method test_install_non_plugin (line 50) | def test_install_non_plugin(self):
    method test_uninstall_by_instance (line 53) | def test_uninstall_by_instance(self):
    method test_uninstall_by_type (line 60) | def test_uninstall_by_type(self):
    method test_uninstall_by_name (line 67) | def test_uninstall_by_name(self):
    method test_uninstall_all (line 75) | def test_uninstall_all(self):
    method test_route_plugin (line 81) | def test_route_plugin(self):
    method test_plugin_oder (line 90) | def test_plugin_oder(self):
    method test_skip_by_instance (line 103) | def test_skip_by_instance(self):
    method test_skip_by_class (line 118) | def test_skip_by_class(self):
    method test_skip_by_name (line 127) | def test_skip_by_name(self):
    method test_skip_all (line 137) | def test_skip_all(self):
    method test_skip_nonlist (line 146) | def test_skip_nonlist(self):
    method test_json_plugin_catches_httpresponse (line 155) | def test_json_plugin_catches_httpresponse(self):
  class TestPluginAPI (line 167) | class TestPluginAPI(tools.ServerTestBase):
    method setUp (line 169) | def setUp(self):
    method test_callable (line 175) | def test_callable(self):
    method test_apply (line 184) | def test_apply(self):
    method test_instance_method_wrapper (line 196) | def test_instance_method_wrapper(self):
    method test_setup (line 205) | def test_setup(self):
    method test_close (line 212) | def test_close(self):

FILE: test/test_resources.py
  class TestResourceManager (line 14) | class TestResourceManager(unittest.TestCase):
    method test_path_normalize (line 16) | def test_path_normalize(self):
    method test_path_create (line 22) | def test_path_create(self):
    method test_path_absolutize (line 35) | def test_path_absolutize(self):
    method test_path_unique (line 53) | def test_path_unique(self):
    method test_root_path (line 58) | def test_root_path(self):
    method test_path_order (line 74) | def test_path_order(self):
    method test_get (line 85) | def test_get(self):
    method test_open (line 93) | def test_open(self):

FILE: test/test_route.py
  class TestReFlatten (line 8) | class TestReFlatten(unittest.TestCase):
    method test_re_flatten (line 10) | def test_re_flatten(self):
  class TestRoute (line 18) | class TestRoute(unittest.TestCase):
    method test_callback_inspection (line 21) | def test_callback_inspection(self):
    method test_callback_inspection_multiple_args (line 44) | def test_callback_inspection_multiple_args(self):
    method test_callback_inspection_newsig (line 66) | def test_callback_inspection_newsig(self):
    method test_unwrap_wrapped (line 72) | def test_unwrap_wrapped(self):
    method test_unwrap_closure (line 83) | def test_unwrap_closure(self):
    method test_unwrap_closure_callable (line 98) | def test_unwrap_closure_callable(self):
    method test_unwrap_method (line 108) | def test_unwrap_method(self):
  function _null_decorator (line 119) | def _null_decorator(func, update_wrapper=True):

FILE: test/test_router.py
  class TestRouter (line 8) | class TestRouter(unittest.TestCase):
    method setUp (line 11) | def setUp(self):
    method add (line 14) | def add(self, path, target, method='GET', **ka):
    method match (line 19) | def match(self, path, method='GET'):
    method assertMatches (line 25) | def assertMatches(self, rule, url, method='GET', **args):
    method testBasic (line 31) | def testBasic(self):
    method testNewSyntax (line 43) | def testNewSyntax(self):
    method testUnicode (line 55) | def testUnicode(self):
    method testValueErrorInFilter (line 58) | def testValueErrorInFilter(self):
    method testIntFilter (line 64) | def testIntFilter(self):
    method testFloatFilter (line 68) | def testFloatFilter(self):
    method testPathFilter (line 77) | def testPathFilter(self):
    method testAnonWildcard (line 81) | def testAnonWildcard(self):
    method testWildcardNames (line 86) | def testWildcardNames(self):
    method testParentheses (line 90) | def testParentheses(self):
    method testErrorInPattern (line 96) | def testErrorInPattern(self):
    method testBuild (line 100) | def testBuild(self):
    method testBuildAnon (line 113) | def testBuildAnon(self):
    method testBuildFilter (line 126) | def testBuildFilter(self):
    method test_dynamic_before_static_any (line 136) | def test_dynamic_before_static_any(self):
    method test_any_static_before_dynamic (line 143) | def test_any_static_before_dynamic(self):
    method test_dynamic_any_if_method_exists (line 150) | def test_dynamic_any_if_method_exists(self):
    method test_lots_of_routes (line 158) | def test_lots_of_routes(self):
  class TestRouterInCGIMode (line 164) | class TestRouterInCGIMode(TestRouter):

FILE: test/test_securecookies.py
  class TestSignedCookies (line 9) | class TestSignedCookies(unittest.TestCase):
    method setUp (line 10) | def setUp(self):
    method tear_down (line 16) | def tear_down(self):
    method get_pairs (line 19) | def get_pairs(self):
    method set_pairs (line 25) | def set_pairs(self, pairs):
    method testValid (line 29) | def testValid(self):
    method testWrongKey (line 36) | def testWrongKey(self):
  class TestSignedCookiesWithPickle (line 44) | class TestSignedCookiesWithPickle(TestSignedCookies):
    method setUp (line 45) | def setUp(self):
    method testValid (line 50) | def testValid(self):
    method testWrongKey (line 54) | def testWrongKey(self):

FILE: test/test_sendfile.py
  class TestDateParser (line 21) | class TestDateParser(unittest.TestCase):
    method test_rfc1123 (line 22) | def test_rfc1123(self):
    method test_rfc850 (line 28) | def test_rfc850(self):
    method test_asctime (line 35) | def test_asctime(self):
    method test_bad (line 42) | def test_bad(self):
  class TestSendFile (line 47) | class TestSendFile(unittest.TestCase):
    method setUp (line 48) | def setUp(self):
    method test_valid (line 55) | def test_valid(self):
    method test_invalid (line 60) | def test_invalid(self):
    method test_file_not_readable (line 66) | def test_file_not_readable(self):
    method test_mime (line 80) | def test_mime(self):
    method test_mime_gzip (line 91) | def test_mime_gzip(self):
    method test_ims (line 103) | def test_ims(self):
    method test_ims_empty (line 113) | def test_ims_empty(self):
    method test_etag (line 118) | def test_etag(self):
    method test_download (line 137) | def test_download(self):
    method test_range (line 149) | def test_range(self):
    method test_range_parser (line 158) | def test_range_parser(self):
    method test_custom_headers (line 165) | def test_custom_headers(self):

FILE: test/test_stpl.py
  class TestSimpleTemplate (line 10) | class TestSimpleTemplate(unittest.TestCase):
    method assertRenders (line 11) | def assertRenders(self, tpl, to, *args, **vars):
    method test_string (line 16) | def test_string(self):
    method test_self_as_variable_name (line 20) | def test_self_as_variable_name(self):
    method test_file (line 23) | def test_file(self):
    method test_name (line 28) | def test_name(self):
    method test_unicode (line 33) | def test_unicode(self):
    method test_unicode_code (line 37) | def test_unicode_code(self):
    method test_import (line 43) | def test_import(self):
    method test_data (line 48) | def test_data(self):
    method test_htmlutils_quote (line 60) | def test_htmlutils_quote(self):
    method test_escape (line 63) | def test_escape(self):
    method test_noescape (line 67) | def test_noescape(self):
    method test_noescape_setting (line 71) | def test_noescape_setting(self):
    method test_blocks (line 79) | def test_blocks(self):
    method test_elsebug (line 88) | def test_elsebug(self):
    method test_commentbug (line 93) | def test_commentbug(self):
    method test_multiline (line 97) | def test_multiline(self):
    method test_newline_in_parameterlist (line 101) | def test_newline_in_parameterlist(self):
    method test_dedentbug (line 105) | def test_dedentbug(self):
    method test_onelinebugs (line 116) | def test_onelinebugs(self):
    method test_onelineblocks (line 135) | def test_onelineblocks(self):
    method test_escaped_codelines (line 141) | def test_escaped_codelines(self):
    method test_nobreak (line 146) | def test_nobreak(self):
    method test_nonobreak (line 150) | def test_nonobreak(self):
    method test_include (line 154) | def test_include(self):
    method test_rebase (line 160) | def test_rebase(self):
    method test_get (line 167) | def test_get(self):
    method test_setdefault (line 171) | def test_setdefault(self):
    method test_defnied (line 176) | def test_defnied(self):
    method test_notfound (line 180) | def test_notfound(self):
    method test_error (line 184) | def test_error(self):
    method test_winbreaks (line 189) | def test_winbreaks(self):
    method test_winbreaks_end_bug (line 193) | def test_winbreaks_end_bug(self):
    method test_commentonly (line 200) | def test_commentonly(self):
    method test_template_shortcut (line 205) | def test_template_shortcut(self):
    method test_view_decorator (line 209) | def test_view_decorator(self):
    method test_view_decorator_issue_407 (line 215) | def test_view_decorator_issue_407(self):
    method test_global_config (line 226) | def test_global_config(self):
    method test_bug_no_whitespace_before_stmt (line 231) | def test_bug_no_whitespace_before_stmt(self):
    method test_bug_block_keywords_eat_prefixed_code (line 234) | def test_bug_block_keywords_eat_prefixed_code(self):
  class TestSTPLDir (line 241) | class TestSTPLDir(unittest.TestCase):
    method fix_ident (line 242) | def fix_ident(self, string):
    method assertRenders (line 252) | def assertRenders(self, source, result, syntax=None, *args, **vars):
    method test_multiline_block (line 263) | def test_multiline_block(self):
    method test_multiline_ignore_eob_in_string (line 277) | def test_multiline_ignore_eob_in_string(self):
    method test_multiline_find_eob_in_comments (line 289) | def test_multiline_find_eob_in_comments(self):
    method test_multiline_indention (line 302) | def test_multiline_indention(self):
    method test_multiline_eob_after_end (line 316) | def test_multiline_eob_after_end(self):
    method test_multiline_eob_in_single_line_code (line 327) | def test_multiline_eob_in_single_line_code(self):
    method test_multiline_strings_in_code_line (line 337) | def test_multiline_strings_in_code_line(self):
    method test_multiline_comprehensions_in_code_line (line 348) | def test_multiline_comprehensions_in_code_line(self):
    method test_end_keyword_on_same_line (line 361) | def test_end_keyword_on_same_line(self):

FILE: test/test_wsgi.py
  class TestWsgi (line 7) | class TestWsgi(ServerTestBase):
    method test_get (line 10) | def test_get(self):
    method test_post (line 18) | def test_post(self):
    method test_headget (line 26) | def test_headget(self):
    method test_request_attrs (line 41) | def test_request_attrs(self):
    method get204 (line 52) | def get204(self):
    method get304 (line 61) | def get304(self):
    method test_anymethod (line 72) | def test_anymethod(self):
    method test_500 (line 88) | def test_500(self):
    method test_500_unicode (line 94) | def test_500_unicode(self):
    method test_utf8_url (line 99) | def test_utf8_url(self):
    method test_utf8_header (line 105) | def test_utf8_header(self):
    method test_utf8_404 (line 114) | def test_utf8_404(self):
    method test_401 (line 117) | def test_401(self):
    method test_303 (line 129) | def test_303(self):
    method test_generator_callback (line 144) | def test_generator_callback(self):
    method test_cookie (line 158) | def test_cookie(self):
  class TestErrorHandling (line 174) | class TestErrorHandling(ServerTestBase):
    method test_error_routing (line 175) | def test_error_routing(self):
  class CloseableBody (line 201) | class CloseableBody:
    method __init__ (line 203) | def __init__(self, body):
    method __iter__ (line 207) | def __iter__(self):
    method close (line 210) | def close(self):
  class TestCloseable (line 214) | class TestCloseable(ServerTestBase):
    method setUp (line 217) | def setUp(self):
    method closeable (line 220) | def closeable(self, body=["OK"]):
    method assertClosed (line 223) | def assertClosed(self, body, open_args=None):
    method test_direct (line 231) | def test_direct(self):
  class TestRouteDecorator (line 246) | class TestRouteDecorator(ServerTestBase):
    method test_decorators (line 247) | def test_decorators(self):
    method test_single_path (line 256) | def test_single_path(self):
    method test_path_list (line 262) | def test_path_list(self):
    method test_no_path (line 269) | def test_no_path(self):
    method test_no_params_at_all (line 275) | def test_no_params_at_all(self):
    method test_method (line 281) | def test_method(self):
    method test_method_list (line 288) | def test_method_list(self):
    method test_apply (line 295) | def test_apply(self):
    method test_apply_list (line 307) | def test_apply_list(self):
    method test_hooks (line 323) | def test_hooks(self):
    method test_after_request_sees_HTTPError_response (line 336) | def test_after_request_sees_HTTPError_response(self):
    method test_after_request_hooks_run_after_exception (line 353) | def test_after_request_hooks_run_after_exception(self):
    method test_after_request_hooks_run_after_exception_in_before_hook (line 373) | def test_after_request_hooks_run_after_exception_in_before_hook(self):
    method test_after_request_hooks_may_rise_response_exception (line 393) | def test_after_request_hooks_may_rise_response_exception(self):
    method test_after_response_hook_can_set_headers (line 410) | def test_after_response_hook_can_set_headers(self):
    method test_template (line 431) | def test_template(self):
    method test_template_opts (line 436) | def test_template_opts(self):
    method test_name (line 441) | def test_name(self):
    method test_callback (line 446) | def test_callback(self):
  class TestDecorators (line 456) | class TestDecorators(ServerTestBase):
    method test_view (line 459) | def test_view(self):
    method test_view_error (line 470) | def test_view_error(self):
    method test_truncate_body (line 480) | def test_truncate_body(self):
    method test_routebuild (line 492) | def test_routebuild(self):
    method test_autoroute (line 506) | def test_autoroute(self):
  class TestAppShortcuts (line 521) | class TestAppShortcuts(ServerTestBase):
    method setUp (line 522) | def setUp(self):
    method testWithStatement (line 525) | def testWithStatement(self):
    method assertWraps (line 533) | def assertWraps(self, test, other):
    method test_module_shortcuts (line 536) | def test_module_shortcuts(self):
    method test_module_shortcuts_with_different_name (line 543) | def test_module_shortcuts_with_different_name(self):

FILE: test/tools.py
  function warn (line 19) | def warn(msg):
  function tobs (line 23) | def tobs(data):
  class chdir (line 28) | class chdir(object):
    method __init__ (line 29) | def __init__(self, dir):
    method __enter__ (line 35) | def __enter__(self):
    method __exit__ (line 38) | def __exit__(self, exc_type, exc_val, tb):
  class assertWarn (line 42) | class assertWarn(object):
    method __init__ (line 43) | def __init__(self, text):
    method __call__ (line 46) | def __call__(self, func):
  function api (line 58) | def api(introduced, deprecated=None, removed=None):
  function wsgistr (line 78) | def wsgistr(s):
  class ServerTestBase (line 81) | class ServerTestBase(unittest.TestCase):
    method setUp (line 82) | def setUp(self):
    method urlopen (line 89) | def urlopen(self, path, method='GET', post='', env=None, crash=None):
    method postmultipart (line 123) | def postmultipart(self, path, fields, files):
    method tearDown (line 127) | def tearDown(self):
    method assertStatus (line 130) | def assertStatus(self, code, route='/', **kargs):
    method assertBody (line 133) | def assertBody(self, body, route='/', **kargs):
    method assertInBody (line 136) | def assertInBody(self, body, route='/', **kargs):
    method assertHeader (line 141) | def assertHeader(self, name, value, route='/', **kargs):
    method assertHeaderAny (line 144) | def assertHeaderAny(self, name, route='/', **kargs):
    method assertInError (line 147) | def assertInError(self, search, route='/', **kargs):
  function multipart_environ (line 153) | def multipart_environ(fields, files):
Condensed preview — 217 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,046K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 37,
    "preview": "github: [defnull]\nliberapay: defnull\n"
  },
  {
    "path": ".github/workflows/run_tests.yml",
    "chars": 602,
    "preview": "name: Run Tests\non: [push, pull_request, workflow_call]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    strategy:\n      m"
  },
  {
    "path": ".gitignore",
    "chars": 188,
    "preview": "*.pyc\n*.pyo\n*.db\n*.log\n*.mo\n._*\n*.*~\n__pycache__\n\ndist/\nbuild/\nMANIFEST\nbottle.egg-info/\n\n.idea/\n\nhtmlcov/\n.htmlcoverage"
  },
  {
    "path": ".readthedocs.yaml",
    "chars": 634,
    "preview": "# Read the Docs configuration file for Sphinx projects\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html f"
  },
  {
    "path": "AUTHORS",
    "chars": 1327,
    "preview": "Bottle is written and maintained by Marcel Hellkamp <marc@bottlepy.org>.\n\nThanks to all the people who found bugs, sent "
  },
  {
    "path": "LICENSE",
    "chars": 1066,
    "preview": "Copyright (c) 2009-2025, Marcel Hellkamp.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n"
  },
  {
    "path": "Makefile",
    "chars": 1112,
    "preview": "VERSION = $(shell ./bottle.py --version)\nVENV = build/venv\n\n.PHONY: test\ntest: venv\n\t$(VENV)/bin/pytest\n\n.PHONY: coverag"
  },
  {
    "path": "README.rst",
    "chars": 2851,
    "preview": ".. image:: https://bottlepy.org/docs/dev/_static/logo_nav.png\n  :target: https://bottlepy.org/\n  :alt: Bottle Logo\n  :al"
  },
  {
    "path": "bottle.py",
    "chars": 175936,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nBottle is a fast and simple micro-framework for small web applications"
  },
  {
    "path": "docs/_locale/.tx/config",
    "chars": 2008,
    "preview": "[main]\nhost = https://www.transifex.com\ntype = PO\n\n[bottle.development]\nfile_filter = <lang>/LC_MESSAGES/development.po\n"
  },
  {
    "path": "docs/_locale/README.txt",
    "chars": 405,
    "preview": "Translation Workflow\n====================\n\nIf documentation changed, run `make push` to push new messages to transiflex "
  },
  {
    "path": "docs/_locale/_pot/api.pot",
    "chars": 49056,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/async.pot",
    "chars": 7828,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/changelog.pot",
    "chars": 23563,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/configuration.pot",
    "chars": 10022,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/contact.pot",
    "chars": 2341,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/deployment.pot",
    "chars": 10712,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/development.pot",
    "chars": 13944,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/faq.pot",
    "chars": 2816,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/index.pot",
    "chars": 3490,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/plugindev.pot",
    "chars": 12559,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/plugins/index.pot",
    "chars": 6285,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/recipes.pot",
    "chars": 9056,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/routing.pot",
    "chars": 5913,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/stpl.pot",
    "chars": 8592,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/tutorial.pot",
    "chars": 47789,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/_pot/tutorial_app.pot",
    "chars": 29986,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/api.po",
    "chars": 50095,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/async.po",
    "chars": 8189,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/changelog.po",
    "chars": 24203,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/configuration.po",
    "chars": 10338,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/contact.po",
    "chars": 2554,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/deployment.po",
    "chars": 11025,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/development.po",
    "chars": 26072,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/faq.po",
    "chars": 4581,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/index.po",
    "chars": 3650,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/plugindev.po",
    "chars": 13052,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/plugins/index.po",
    "chars": 6409,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/recipes.po",
    "chars": 9378,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/routing.po",
    "chars": 6127,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/stpl.po",
    "chars": 8936,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/tutorial.po",
    "chars": 52038,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/de_DE/LC_MESSAGES/tutorial_app.po",
    "chars": 31058,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/api.po",
    "chars": 49874,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/async.po",
    "chars": 8173,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/changelog.po",
    "chars": 24186,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/configuration.po",
    "chars": 10321,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/contact.po",
    "chars": 3735,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/deployment.po",
    "chars": 11063,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/development.po",
    "chars": 14465,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/faq.po",
    "chars": 2965,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/index.po",
    "chars": 4000,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/plugindev.po",
    "chars": 13035,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/plugins/index.po",
    "chars": 6392,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/recipes.po",
    "chars": 9361,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/routing.po",
    "chars": 6110,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/stpl.po",
    "chars": 8919,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/tutorial.po",
    "chars": 49414,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/fr/LC_MESSAGES/tutorial_app.po",
    "chars": 31041,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/api.po",
    "chars": 49884,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/async.po",
    "chars": 8183,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/changelog.po",
    "chars": 24196,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/configuration.po",
    "chars": 10331,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/contact.po",
    "chars": 2464,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/deployment.po",
    "chars": 11018,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/development.po",
    "chars": 14475,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/faq.po",
    "chars": 2957,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/index.po",
    "chars": 4552,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/plugindev.po",
    "chars": 13045,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/plugins/index.po",
    "chars": 6402,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/recipes.po",
    "chars": 9373,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/routing.po",
    "chars": 6120,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/stpl.po",
    "chars": 8929,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/tutorial.po",
    "chars": 50168,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ja_JP/LC_MESSAGES/tutorial_app.po",
    "chars": 31051,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/api.po",
    "chars": 46601,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/async.po",
    "chars": 7922,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/changelog.po",
    "chars": 17053,
    "preview": "#\nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 1"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/configuration.po",
    "chars": 6949,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/contact.po",
    "chars": 2203,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/deployment.po",
    "chars": 10891,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/development.po",
    "chars": 14386,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/faq.po",
    "chars": 2693,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/index.po",
    "chars": 3324,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/plugindev.po",
    "chars": 12795,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/plugins/index.po",
    "chars": 4199,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/recipes.po",
    "chars": 8287,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/routing.po",
    "chars": 5499,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/stpl.po",
    "chars": 8113,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/tutorial.po",
    "chars": 49956,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/_pot/tutorial_app.po",
    "chars": 31720,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/api.po",
    "chars": 50012,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/async.po",
    "chars": 8192,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/changelog.po",
    "chars": 24205,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/configuration.po",
    "chars": 10340,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/contact.po",
    "chars": 2487,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/deployment.po",
    "chars": 11027,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/development.po",
    "chars": 14484,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/faq.po",
    "chars": 3065,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/index.po",
    "chars": 5555,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/plugindev.po",
    "chars": 13054,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/plugins/index.po",
    "chars": 8666,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/recipes.po",
    "chars": 9395,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/routing.po",
    "chars": 6129,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/stpl.po",
    "chars": 8938,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/tutorial.po",
    "chars": 51106,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/pt_BR/LC_MESSAGES/tutorial_app.po",
    "chars": 31060,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/requirements.txt",
    "chars": 36,
    "preview": "sphinx\nsphinx-intl\ntransifex-client\n"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/api.po",
    "chars": 50029,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/async.po",
    "chars": 8327,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/changelog.po",
    "chars": 24341,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/configuration.po",
    "chars": 10476,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/contact.po",
    "chars": 2609,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/deployment.po",
    "chars": 11163,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/development.po",
    "chars": 14620,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/faq.po",
    "chars": 3102,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/index.po",
    "chars": 3788,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/plugindev.po",
    "chars": 13190,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/plugins/index.po",
    "chars": 6547,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/recipes.po",
    "chars": 9516,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/routing.po",
    "chars": 6265,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/stpl.po",
    "chars": 9074,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/tutorial.po",
    "chars": 50877,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/ru_RU/LC_MESSAGES/tutorial_app.po",
    "chars": 31196,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/api.po",
    "chars": 46601,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/async.po",
    "chars": 7922,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/changelog.po",
    "chars": 17053,
    "preview": "#\nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 1"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/configuration.po",
    "chars": 6949,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/contact.po",
    "chars": 2203,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/deployment.po",
    "chars": 10891,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/development.po",
    "chars": 14386,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/faq.po",
    "chars": 2693,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/index.po",
    "chars": 3324,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/plugindev.po",
    "chars": 12795,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/plugins/index.po",
    "chars": 4199,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/recipes.po",
    "chars": 8287,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/routing.po",
    "chars": 5499,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/stpl.po",
    "chars": 8113,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/tutorial.po",
    "chars": 49956,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/_pot/tutorial_app.po",
    "chars": 31720,
    "preview": "# \nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Bottle 0.13-dev\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: 2015-01-22 "
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/api.po",
    "chars": 50068,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/async.po",
    "chars": 10797,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/changelog.po",
    "chars": 24210,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/configuration.po",
    "chars": 11641,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/contact.po",
    "chars": 2471,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/deployment.po",
    "chars": 12275,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/development.po",
    "chars": 18512,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/faq.po",
    "chars": 3696,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/index.po",
    "chars": 4389,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/plugindev.po",
    "chars": 16578,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/plugins/index.po",
    "chars": 6805,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/recipes.po",
    "chars": 11905,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/routing.po",
    "chars": 7244,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/stpl.po",
    "chars": 9797,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/tutorial.po",
    "chars": 63185,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/_locale/zh_CN/LC_MESSAGES/tutorial_app.po",
    "chars": 37468,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) 2009-2020, Marcel Hellkamp\n# This file is distributed under the same license a"
  },
  {
    "path": "docs/api.rst",
    "chars": 6047,
    "preview": "==============================\nAPI Reference\n==============================\n\n.. module:: bottle\n   :platform: Unix, Wind"
  },
  {
    "path": "docs/async.rst",
    "chars": 8351,
    "preview": "Asynchronous Applications\n=========================\n\nAsynchronous design patterns don't mix well with the synchronous na"
  },
  {
    "path": "docs/changelog.rst",
    "chars": 18772,
    "preview": ".. highlight:: python\n.. currentmodule:: bottle\n\n=============\nRelease Notes\n=============\n\nThis project loosly follows"
  },
  {
    "path": "docs/conf.py",
    "chars": 910,
    "preview": "# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport time\n\n# Use the matching bottle version, not a globally installed on"
  },
  {
    "path": "docs/configuration.rst",
    "chars": 7085,
    "preview": "=============\nConfiguration\n=============\n\n.. currentmodule:: bottle\n\nBottle applications can store their configuration "
  },
  {
    "path": "docs/contributors.rst",
    "chars": 63,
    "preview": "============\nContributors\n============\n\n.. include:: ../AUTHORS"
  },
  {
    "path": "docs/deployment.rst",
    "chars": 5778,
    "preview": ".. highlight:: python\n.. currentmodule:: bottle\n\n.. _flup: https://pypi.org/project/flup/\n.. _gae: https://code.google.c"
  },
  {
    "path": "docs/development.rst",
    "chars": 6087,
    "preview": "Developer Notes\n=================\n\nThis document is intended for developers and package maintainers interested in the bo"
  },
  {
    "path": "docs/faq.rst",
    "chars": 14001,
    "preview": ".. currentmodule:: bottle\n\n.. _beaker: https://beaker.readthedocs.io/en/latest/\n.. _mod_python: https://www.modpython.or"
  },
  {
    "path": "docs/index.rst",
    "chars": 4287,
    "preview": ".. highlight:: python\n.. currentmodule:: bottle\n\n.. _mako: https://www.makotemplates.org/\n.. _cheetah: https://www.cheet"
  },
  {
    "path": "docs/plugins/dev.rst",
    "chars": 10980,
    "preview": "\n.. currentmodule:: bottle\n\n.. _plugindev:\n\n===============\nWriting Plugins\n===============\n\nThis guide explains the plu"
  },
  {
    "path": "docs/plugins/index.rst",
    "chars": 7670,
    "preview": ".. currentmodule:: bottle\n\n.. _plugins:\n\n=============\nUsing Plugins\n=============\n\n.. versionadded:: 0.9\n\nBottle's core"
  },
  {
    "path": "docs/plugins/list.rst",
    "chars": 3338,
    "preview": ".. currentmodule:: bottle\n\n=========================\n3rd Party Plugins\n=========================\n\nThis is a list of thir"
  },
  {
    "path": "docs/routing.rst",
    "chars": 5495,
    "preview": ".. currentmodule:: bottle\r\n\r\n================================================================================\r\nRequest R"
  },
  {
    "path": "docs/stpl.rst",
    "chars": 8503,
    "preview": "==============\nSimpleTemplate\n==============\n\n.. currentmodule:: bottle\n\nBottle comes with a fast, powerful and easy to "
  },
  {
    "path": "docs/tutorial.rst",
    "chars": 43416,
    "preview": ".. currentmodule:: bottle\n\n\n\n===============\nUser's Guide\n===============\n\nThis guide introduces you to the concepts and"
  },
  {
    "path": "docs/tutorial_app.rst",
    "chars": 46843,
    "preview": ".. _Bottle: https://bottlepy.org\n.. _WSGI: https://peps.python.org/pep-3333/\n.. _Python: https://www.python.org\n.. _SQLi"
  },
  {
    "path": "pyproject.toml",
    "chars": 1742,
    "preview": "[build-system]\nrequires = [\"flit_core >=3.9,<4\"]\nbuild-backend = \"flit_core.buildapi\"\n\n[project]\nname = \"bottle\"\ndynamic"
  },
  {
    "path": "test/.coveragerc",
    "chars": 102,
    "preview": "[run]\nbranch = True\nparallel = True\ndata_file = ../build/.coverage\n\n[html]\ndirectory = build/coverage\n"
  },
  {
    "path": "test/__init__.py",
    "chars": 215,
    "preview": "from __future__ import with_statement\nfrom .tools import chdir\nimport unittest\nimport sys, os\n\ntry:\n    import coverage\n"
  },
  {
    "path": "test/build_python.sh",
    "chars": 1220,
    "preview": "#!/bin/bash -e\n# This script builds a specific python release to a prefix directory\n\n# Stop on any errors\ntrap exit ERR\n"
  },
  {
    "path": "test/example_settings.py",
    "chars": 39,
    "preview": "A = {\n    \"B\": {\n        \"C\": 3\n    }\n}"
  },
  {
    "path": "test/test_app.py",
    "chars": 536,
    "preview": "# -*- coding: utf-8 -*-\n\"\"\" Tests for the functionality of the application object.\n\n    TODO: Move other tests here.\n\"\"\""
  },
  {
    "path": "test/test_auth.py",
    "chars": 345,
    "preview": "# -*- coding: utf-8 -*-\nimport bottle\nfrom .tools import ServerTestBase\n\nclass TestBasicAuth(ServerTestBase):\n\n    def t"
  },
  {
    "path": "test/test_config.py",
    "chars": 7372,
    "preview": "import os\nimport tempfile\nimport unittest\nfrom bottle import ConfigDict\n\n\nclass TestConfDict(unittest.TestCase):\n    def"
  },
  {
    "path": "test/test_contextlocals.py",
    "chars": 1238,
    "preview": "# -*- coding: utf-8 -*-\n'''\nSome objects are context-local, meaning that they have different values depending on the con"
  },
  {
    "path": "test/test_environ.py",
    "chars": 38591,
    "preview": "# -*- coding: utf-8 -*-\n''' Tests for the BaseRequest and BaseResponse objects and their subclasses. '''\n\nimport unittes"
  },
  {
    "path": "test/test_exc.py",
    "chars": 1135,
    "preview": "import bottle\nfrom .tools import ServerTestBase\n\nclass SomeError(Exception):\n    pass\n\nclass TestAppException(ServerTest"
  },
  {
    "path": "test/test_fileupload.py",
    "chars": 2475,
    "preview": "# -*- coding: utf-8 -*-\n''' Tests for the FileUpload wrapper. '''\n\nimport unittest\nimport sys, os.path\nimport bottle\nfro"
  },
  {
    "path": "test/test_formsdict.py",
    "chars": 513,
    "preview": "# -*- coding: utf-8 -*-\n# '瓶' means \"Bottle\"\n\nimport unittest\nfrom bottle import FormsDict, touni, tob\n\nclass TestFormsD"
  },
  {
    "path": "test/test_html_helper.py",
    "chars": 707,
    "preview": "import unittest\n\nfrom bottle import _parse_http_header\n\n\nclass TestHttpUtils(unittest.TestCase):\n\n    # TODO: Move more "
  },
  {
    "path": "test/test_importhook.py",
    "chars": 1290,
    "preview": "# -*- coding: utf-8 -*-\nimport unittest\nimport sys, os\nimport bottle\n\nclass TestImportHooks(unittest.TestCase):\n\n    def"
  },
  {
    "path": "test/test_jinja2.py",
    "chars": 2745,
    "preview": "# -*- coding: utf-8 -*-\nimport unittest\nfrom bottle import Jinja2Template, jinja2_template, jinja2_view, touni\nfrom .too"
  },
  {
    "path": "test/test_mako.py",
    "chars": 2185,
    "preview": "from __future__ import with_statement\nimport unittest\nfrom .tools import warn, chdir\nfrom bottle import MakoTemplate, ma"
  },
  {
    "path": "test/test_mdict.py",
    "chars": 1975,
    "preview": "import unittest\nfrom bottle import MultiDict, HeaderDict\n\nclass TestMultiDict(unittest.TestCase):\n    def test_isadict(s"
  },
  {
    "path": "test/test_mount.py",
    "chars": 4404,
    "preview": "# -*- coding: utf-8 -*-\nimport bottle\nfrom .tools import ServerTestBase, api\nfrom bottle import response\n\nclass TestAppM"
  },
  {
    "path": "test/test_multipart.py",
    "chars": 38334,
    "preview": "# -*- coding: utf-8 -*-\nimport unittest\nimport base64\nimport sys, os.path, tempfile\nfrom io import BytesIO\n\nimport bottl"
  },
  {
    "path": "test/test_oorouting.py",
    "chars": 955,
    "preview": "\"\"\"\nTests & demonstrates various OO approaches to routes\n\"\"\"\nimport unittest\nimport sys\n\nif sys.version_info >= (3, 0, 0"
  },
  {
    "path": "test/test_outputfilter.py",
    "chars": 6258,
    "preview": "# -*- coding: utf-8 -*-\n'''Everything returned by Bottle()._cast() MUST be WSGI compatiple.'''\n\nimport unittest\nimport b"
  },
  {
    "path": "test/test_plugins.py",
    "chars": 7526,
    "preview": "# -*- coding: utf-8 -*-\nimport unittest\nfrom . import tools\n\nfrom bottle import HTTPResponse, HTTPError, json_dumps\n\n\ncl"
  },
  {
    "path": "test/test_resources.py",
    "chars": 3129,
    "preview": "import os.path\nimport sys\nimport unittest\nfrom bottle import ResourceManager\n\nif sys.platform == 'win32':\n    TEST_PATHS"
  },
  {
    "path": "test/test_route.py",
    "chars": 4115,
    "preview": "import functools\nimport unittest\nimport bottle\nfrom .tools import api\nfrom bottle import _re_flatten\n\n\nclass TestReFlatt"
  },
  {
    "path": "test/test_router.py",
    "chars": 6930,
    "preview": "# -*- coding: utf-8 -*-\n\nimport unittest\nimport bottle\nimport warnings\n\n\nclass TestRouter(unittest.TestCase):\n    CGI = "
  },
  {
    "path": "test/test_securecookies.py",
    "chars": 1745,
    "preview": "#coding: utf-8\nimport unittest\n\nimport bottle\nfrom bottle import tob, touni\nfrom .tools import api\n\n\nclass TestSignedCoo"
  }
]

// ... and 17 more files (download for full content)

About this extraction

This page contains the full source code of the bottlepy/bottle GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 217 files (2.7 MB), approximately 724.1k tokens, and a symbol index with 882 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!