desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Issue #671'
def test_after_request_sees_HTTPError_response(self):
called = [] @bottle.hook('after_request') def after_request(): called.append('after') self.assertEqual(400, bottle.response.status_code) @bottle.get('/') def _get(): called.append('route') bottle.abort(400, 'test') self.urlopen('/') self.assertEqual(['route', ...
'Issue #671'
def test_after_request_hooks_run_after_exception(self):
called = [] @bottle.hook('before_request') def before_request(): called.append('before') @bottle.hook('after_request') def after_request(): called.append('after') @bottle.get('/') def _get(): called.append('route') (1 / 0) self.urlopen('/') self.assert...
'Issue #671'
def test_after_request_hooks_run_after_exception_in_before_hook(self):
called = [] @bottle.hook('before_request') def before_request(): called.append('before') (1 / 0) @bottle.hook('after_request') def after_request(): called.append('after') @bottle.get('/') def _get(): called.append('route') self.urlopen('/') self.assert...
'Issue #671'
def test_after_request_hooks_may_rise_response_exception(self):
called = [] @bottle.hook('after_request') def after_request(): called.append('after') bottle.abort(400, 'hook_content') @bottle.get('/') def _get(): called.append('route') return 'XXX' self.assertInBody('hook_content', '/') self.assertEqual(['route', 'after'],...
'WSGI: Test view-decorator (should override autojson)'
def test_view(self):
with chdir(__file__): @bottle.route('/tpl') @bottle.view('stpl_t2main') def test(): return dict(content='1234') result = '+base+\n+main+\n!1234!\n+include+\n-main-\n+include+\n-base-\n' self.assertHeader('Content-Type', 'text/html; charset=UTF-8', '/tpl') ...
'WSGI: Test if view-decorator reacts on non-dict return values correctly.'
def test_view_error(self):
@bottle.route('/tpl') @bottle.view('stpl_t2main') def test(): return bottle.HTTPError(401, 'The cake is a lie!') self.assertInBody('The cake is a lie!', '/tpl') self.assertInBody('401 Unauthorized', '/tpl') self.assertStatus(401, '/tpl')
'WSGI: Some HTTP status codes must not be used with a response-body'
def test_truncate_body(self):
@bottle.route('/test/:code') def test(code): bottle.response.status = int(code) return 'Some body content' self.assertBody('Some body content', '/test/200') self.assertBody('', '/test/100') self.assertBody('', '/test/101') self.assertBody('', '/test/204') self.ass...
'WSGI: Test route builder'
def test_routebuild(self):
def foo(): pass bottle.route('/a/:b/c', name='named')(foo) bottle.request.environ['SCRIPT_NAME'] = '' self.assertEqual('/a/xxx/c', bottle.url('named', b='xxx')) self.assertEqual('/a/xxx/c', bottle.app().get_url('named', b='xxx')) bottle.request.environ['SCRIPT_NAME'] = '/app' self.as...
'Templates: Mako string'
def test_string(self):
t = MakoTemplate('start ${var} end').render(var='var') self.assertEqual('start var end', t)
'Templates: Mako file'
def test_file(self):
with chdir(__file__): t = MakoTemplate(name='./views/mako_simple.tpl', lookup=['.']).render(var='var') self.assertEqual('start var end\n', t)
'Templates: Mako lookup by name'
def test_name(self):
with chdir(__file__): t = MakoTemplate(name='mako_simple', lookup=['./views/']).render(var='var') self.assertEqual('start var end\n', t)
'Templates: Unavailable templates'
def test_notfound(self):
self.assertRaises(Exception, MakoTemplate, name='abcdef')
'Templates: Exceptions'
def test_error(self):
self.assertRaises(Exception, MakoTemplate, '%for badsyntax')
'Templates: Mako lookup and inherience'
def test_inherit(self):
with chdir(__file__): t = MakoTemplate(name='mako_inherit', lookup=['./views/']).render(var='v') self.assertEqual('o\ncvc\no\n', t) t = MakoTemplate('<%inherit file="mako_base.tpl"/>\nc${var}c\n', lookup=['./views/']).render(var='v') self.assertEqual('o\ncvc\no\n', t) t = ...
'Templates: Jinja2 string'
def test_string(self):
t = Jinja2Template('start {{var}} end').render(var='var') self.assertEqual('start var end', ''.join(t))
'Templates: Jinja2 file'
def test_file(self):
with chdir(__file__): t = Jinja2Template(name='./views/jinja2_simple.tpl', lookup=['.']).render(var='var') self.assertEqual('start var end', ''.join(t))
'Templates: Jinja2 lookup by name'
def test_name(self):
with chdir(__file__): t = Jinja2Template(name='jinja2_simple', lookup=['./views/']).render(var='var') self.assertEqual('start var end', ''.join(t))
'Templates: Unavailable templates'
def test_notfound(self):
self.assertRaises(Exception, Jinja2Template, name='abcdef')
'Templates: Exceptions'
def test_error(self):
self.assertRaises(Exception, Jinja2Template, '{% for badsyntax')
'Templates: Jinja2 lookup and inherience'
def test_inherit(self):
with chdir(__file__): t = Jinja2Template(name='jinja2_inherit', lookup=['./views/']).render() self.assertEqual('begin abc end', ''.join(t))
'Templates: jinja2 custom filters'
def test_custom_filters(self):
from bottle import jinja2_template as template settings = dict(filters={'star': (lambda var: touni('').join((touni('*'), var, touni('*'))))}) t = Jinja2Template('start {{var|star}} end', **settings) self.assertEqual('start *var* end', t.render(var='var'))
'Templates: jinja2 custom tests'
def test_custom_tests(self):
from bottle import jinja2_template as template TEMPL = touni('{% if var is even %}gerade{% else %}ungerade{% endif %}') settings = dict(tests={'even': (lambda x: (False if (x % 2) else True))}) t = Jinja2Template(TEMPL, **settings) self.assertEqual('gerade', t.render(var=2...
'Static ANY routes have lower priority than dynamic GET routes.'
def test_dynamic_before_static_any(self):
self.add('/foo', 'foo', 'ANY') self.assertEqual(self.match('/foo')[0], 'foo') self.add('/<:>', 'bar', 'GET') self.assertEqual(self.match('/foo')[0], 'bar')
'Static ANY routes have higher priority than dynamic ANY routes.'
def test_any_static_before_dynamic(self):
self.add('/<:>', 'bar', 'ANY') self.assertEqual(self.match('/foo')[0], 'bar') self.add('/foo', 'foo', 'ANY') self.assertEqual(self.match('/foo')[0], 'foo')
'Check dynamic ANY routes if the matching method is known, but not matched.'
def test_dynamic_any_if_method_exists(self):
self.add('/bar<:>', 'bar', 'GET') self.assertEqual(self.match('/barx')[0], 'bar') self.add('/foo<:>', 'foo', 'ANY') self.assertEqual(self.match('/foox')[0], 'foo')
'Test a simple static page with this server adapter.'
def test_import_fail(self):
def test(): import bottle.ext.doesnotexist self.assertRaises(ImportError, test)
'The virtual module needs a valid __file__ attribute. If not, the Google app engine development server crashes on windows.'
def test_ext_isfile(self):
from bottle import ext self.assertTrue(os.path.isfile(ext.__file__))
'Attributed can be assigned, but only once.'
def test_setattr(self):
app = Bottle() app.test = 5 self.assertEquals(5, app.test) self.assertRaises(AttributeError, setattr, app, 'test', 6) del app.test app.test = 6 self.assertEquals(6, app.test)
'PATH_INFO normalization.'
def test_path(self):
tests = [('', '/'), ('x', '/x'), ('x/', '/x/'), ('/x', '/x'), ('/x/', '/x/')] for (raw, norm) in tests: self.assertEqual(norm, BaseRequest({'PATH_INFO': raw}).path) tests = [('///', '/'), ('//x', '/x')] for (raw, norm) in tests: self.assertEqual(norm, BaseRequest({'PATH_INFO': raw}).path...
'SCRIPT_NAME normalization.'
def test_script_name(self):
tests = [('', '/'), ('x', '/x/'), ('x/', '/x/'), ('/x', '/x/'), ('/x/', '/x/')] for (raw, norm) in tests: self.assertEqual(norm, BaseRequest({'SCRIPT_NAME': raw}).script_name) tests = [('///', '/'), ('///x///', '/x/')] for (raw, norm) in tests: self.assertEqual(norm, BaseRequest({'SCRIPT...
'Request.path_shift()'
def test_pathshift(self):
def test_shift(s, p, c): request = BaseRequest({'SCRIPT_NAME': s, 'PATH_INFO': p}) request.path_shift(c) return [request['SCRIPT_NAME'], request.path] self.assertEqual(['/a/b', '/c/d'], test_shift('/a/b', '/c/d', 0)) self.assertEqual(['/a/b', '/c/d/'], test_shift('/a/b', '/c/d/', 0))...
'Environ: URL building'
def test_url(self):
request = BaseRequest({'HTTP_HOST': 'example.com'}) self.assertEqual('http://example.com/', request.url) request = BaseRequest({'SERVER_NAME': 'example.com'}) self.assertEqual('http://example.com/', request.url) request = BaseRequest({'SERVER_NAME': 'example.com', 'SERVER_PORT': '81'}) self.asse...
'Environ: request objects are environment dicts'
def test_dict_access(self):
e = {} wsgiref.util.setup_testing_defaults(e) request = BaseRequest(e) self.assertEqual(list(request), list(e.keys())) self.assertEqual(len(request), len(e)) for (k, v) in e.items(): self.assertTrue((k in request)) self.assertEqual(request[k], v) request[k] = 'test' ...
'Environ: Request objects decode headers'
def test_header_access(self):
e = {} wsgiref.util.setup_testing_defaults(e) e['HTTP_SOME_HEADER'] = 'some value' request = BaseRequest(e) request['HTTP_SOME_OTHER_HEADER'] = 'some other value' self.assertTrue(('Some-Header' in request.headers)) self.assertTrue((request.headers['Some-Header'] == 'some value'))...
'Environ: Cookie dict'
def test_cookie_dict(self):
t = dict() t['a=a'] = {'a': 'a'} t['a=a; b=b'] = {'a': 'a', 'b': 'b'} t['a=a; a=b'] = {'a': 'b'} for (k, v) in t.items(): request = BaseRequest({'HTTP_COOKIE': k}) for n in v: self.assertEqual(v[n], request.cookies[n]) self.assertEqual(v[n], request.get_...
'Environ: GET data'
def test_get(self):
qs = tonat(tob('a=a&a=1&b=b&c=c&cn=%e7%93%b6'), 'latin1') request = BaseRequest({'QUERY_STRING': qs}) self.assertTrue(('a' in request.query)) self.assertTrue(('b' in request.query)) self.assertEqual(['a', '1'], request.query.getall('a')) self.assertEqual(['b'], request.query.getall('b')) sel...
'Environ: POST data'
def test_post(self):
sq = tob('a=a&a=1&b=b&c=&d&cn=%e7%93%b6') e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(sq) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(sq)) e['REQUEST_METHOD'] = 'POST' request = BaseRequest(e) self.assertTrue(('a' in request.POST)) self.assertTru...
'Test that the body file handler is not closed after request.POST'
def test_body_noclose(self):
sq = tob('a=a&a=1&b=b&c=&d') e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(sq) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(sq)) e['REQUEST_METHOD'] = 'POST' request = BaseRequest(e) self.assertEqual(sq, request.body.read()) request.POST self.as...
'Environ: GET and POST are combined in request.param'
def test_params(self):
e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob('b=b&c=p')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '7' e['QUERY_STRING'] = 'a=a&c=g' e['REQUEST_METHOD'] = 'POST' request = BaseRequest(e) self.assertEqual(['a', 'b', 'c'], sorted(request.params.keys())) ...
'Environ: GET and POST should not leak into each other'
def test_getpostleak(self):
e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob('b=b')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '3' e['QUERY_STRING'] = 'a=a' e['REQUEST_METHOD'] = 'POST' request = BaseRequest(e) self.assertEqual(['a'], list(request.GET.keys())) self.assertEqual(['b...
'Environ: Request.body should behave like a file object factory'
def test_body(self):
e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob('abc')) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(3) request = BaseRequest(e) self.assertEqual(tob('abc'), request.body.read()) self.assertEqual(tob('abc'), request.body.read(3)) self.assertEqual(tob('abc...
'Environ: Request.body should handle big uploads using files'
def test_bigbody(self):
e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(((tob('x') * 1024) * 1000)) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str((1024 * 1000)) request = BaseRequest(e) self.assertTrue(hasattr(request.body, 'fileno')) self.assertEqual((1024 * 1000), len(request.body.read...
'Environ: Request.body should truncate to Content-Length bytes'
def test_tobigbody(self):
e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write((tob('x') * 1024)) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = '42' request = BaseRequest(e) self.assertEqual(42, len(request.body.read())) self.assertEqual(42, len(request.body.read(1024))) self.assertEqual(42, le...
'Environ: POST (multipart files and multible values per key)'
def test_multipart(self):
fields = [('field1', 'value1'), ('field2', 'value2'), ('field2', 'value3')] files = [('file1', 'filename1.txt', 'content1'), ('\xe4\xb8\x87\xe9\x9a\xbe', '\xe4\xb8\x87\xe9\x9a\xbefoo.py', '\xc3\xa4\n\xc3\xb6\r\xc3\xbc')] e = tools.multipart_environ(fields=fields, files=files) request = BaseRequest(e) ...
'Environ: Request.json property with empty body.'
def test_json_empty(self):
self.assertEqual(BaseRequest({}).json, None)
'Environ: Request.json property with missing content-type header.'
def test_json_noheader(self):
test = dict(a=5, b='test', c=[1, 2, 3]) e = {} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob(json_dumps(test))) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(json_dumps(test))) self.assertEqual(BaseRequest(e).json, None)
'Environ: Request.json property with huge body.'
def test_json_tobig(self):
test = dict(a=5, tobig=('x' * bottle.BaseRequest.MEMFILE_MAX)) e = {'CONTENT_TYPE': 'application/json'} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob(json_dumps(test))) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(json_dumps(test))) self.assertRaises(HTTPError, (l...
'Environ: Request.json property.'
def test_json_valid(self):
test = dict(a=5, b='test', c=[1, 2, 3]) e = {'CONTENT_TYPE': 'application/json; charset=UTF-8'} wsgiref.util.setup_testing_defaults(e) e['wsgi.input'].write(tob(json_dumps(test))) e['wsgi.input'].seek(0) e['CONTENT_LENGTH'] = str(len(json_dumps(test))) self.assertEqual(BaseRequest(e).json...
'Request Content-Type is application/json but body is empty'
def test_json_header_empty_body(self):
e = {'CONTENT_TYPE': 'application/json'} wsgiref.util.setup_testing_defaults(e) wsgiref.util.setup_testing_defaults(e) e['CONTENT_LENGTH'] = '0' self.assertEqual(BaseRequest(e).json, None)
'The target URL is not quoted automatically.'
def test_specialchars(self):
self.assertRedirect('./te st.html', 'http://example.com/a%20a/b%20b/te st.html', HTTP_HOST='example.com', SCRIPT_NAME='/a a/', PATH_INFO='/b b/')
'Create a new Bottle app set it as default_app'
def setUp(self):
self.port = 8080 self.host = 'localhost' self.app = bottle.app.push() self.wsgiapp = wsgiref.validate.validator(self.app)
'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.'
def add_filter(self, name, func):
self.filters[name] = func
'Add a new rule or replace the target for an existing rule.'
def add(self, rule, method, target, name=None):
anons = 0 keys = [] pattern = '' filters = [] 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)...
'Build an URL by filling the wildcards in a rule.'
def build(self, _name, *anons, **query):
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]) ret...
'Return a (target, url_args) tuple or raise HTTPError(400/404/405).'
def match(self, environ):
verb = environ['REQUEST_METHOD'].upper() path = (environ['PATH_INFO'] or '/') if (verb == 'HEAD'): methods = ['PROXY', verb, 'GET', 'ANY'] else: methods = ['PROXY', verb, 'ANY'] for method in methods: if ((method in self.static) and (path in self.static[method])): ...
'The route callback with all plugins applied. This property is created on demand and then cached to speed up subsequent requests.'
@cached_property def call(self):
return self._make_callback()
'Forget any cached values. The next time :attr:`call` is accessed, all plugins are re-applied.'
def reset(self):
self.__dict__.pop('call', None)
'Do all on-demand work immediately (useful for debugging).'
def prepare(self):
self.call
'Yield all Plugins affecting this route.'
def all_plugins(self):
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.skipl...
'Return the callback. If the callback is a decorated function, try to recover the original function.'
def get_undecorated_callback(self):
func = self.callback func = getattr(func, ('__func__' if py3k else 'im_func'), func) closure_attr = ('__closure__' if py3k else 'func_closure') while (hasattr(func, closure_attr) and getattr(func, closure_attr)): attributes = getattr(func, closure_attr) func = attributes[0].cell_contents...
'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.'
def get_callback_args(self):
return getargspec(self.get_undecorated_callback())[0]
'Lookup a config field and return its value, first checking the route.config, then route.app.config.'
def get_config(self, key, default=None):
depr(0, 13, 'Route.get_config() is deprectated.', 'The Route.config property already includes values from the application config for missing keys. Access it directly.') return self.config.get(key, default)
'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.'
def add_hook(self, name, func):
if (name in self.__hook_reversed): self._hooks[name].insert(0, func) else: self._hooks[name].append(func)
'Remove a callback from a hook.'
def remove_hook(self, name, func):
if ((name in self._hooks) and (func in self._hooks[name])): self._hooks[name].remove(func) return True
'Trigger a hook and return a list of results.'
def trigger_hook(self, __name, *args, **kwargs):
return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
'Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.'
def hook(self, name):
def decorator(func): self.add_hook(name, func) return func return decorator
'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 moun...
def mount(self, prefix, app, **options):
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)
'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.'
def merge(self, routes):
if isinstance(routes, Bottle): routes = routes.routes for route in routes: self.add_route(route)
'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.'
def install(self, plugin):
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
'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.'
def uninstall(self, plugin):
(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(plugi...
'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.'
def reset(self, route=None):
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')
'Close the application and all installed plugins.'
def close(self):
for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close()
'Calls :func:`run` with the same parameters.'
def run(self, **kwargs):
run(self, **kwargs)
'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.'
def match(self, environ):
return self.router.match(environ)
'Return a string that matches a named route'
def get_url(self, routename, **kargs):
scriptname = (request.environ.get('SCRIPT_NAME', '').strip('/') + '/') location = self.router.build(routename, **kargs).lstrip('/') return urljoin(urljoin('/', scriptname), location)
'Add a route object, but do not change the :data:`Route.app` attribute.'
def add_route(self, route):
self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare()
'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 generat...
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config):
if callable(path): (path, callback) = (None, path) plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): if isinstance(callback, basestring): callback = load(callback) for rule in (makelist(path) or yieldroutes(callback)): for verb i...
'Equals :meth:`route`.'
def get(self, path=None, method='GET', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``POST`` method parameter.'
def post(self, path=None, method='POST', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``PUT`` method parameter.'
def put(self, path=None, method='PUT', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``DELETE`` method parameter.'
def delete(self, path=None, method='DELETE', **options):
return self.route(path, method, **options)
'Equals :meth:`route` with a ``PATCH`` method parameter.'
def patch(self, path=None, method='PATCH', **options):
return self.route(path, method, **options)
'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 error(self, code=500, callback=None):
def decorator(callback): if isinstance(callback, basestring): callback = load(callback) self.error_handler[int(code)] = callback return callback return (decorator(callback) if callback else decorator)
'Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes'
def _cast(self, out, peek=None):
if (not out): if ('Content-Length' not in response): response['Content-Length'] = 0 return [] if (isinstance(out, (tuple, list)) and isinstance(out[0], (bytes, unicode))): out = out[0][0:0].join(out) if isinstance(out, unicode): out = out.encode(response.charset) ...
'The bottle WSGI-interface.'
def wsgi(self, environ, start_response):
try: out = self._cast(self._handle(environ)) if ((response._status_code in (100, 101, 204, 304)) or (environ['REQUEST_METHOD'] == 'HEAD')): if hasattr(out, 'close'): out.close() out = [] start_response(response._status_line, response.headerlist) ...
'Each instance of :class:\'Bottle\' is a WSGI application.'
def __call__(self, environ, start_response):
return self.wsgi(environ, start_response)
'Use this application as default for all module-level shortcuts.'
def __enter__(self):
default_app.push(self) return self
'Wrap a WSGI environ dictionary.'
def __init__(self, environ=None):
self.environ = ({} if (environ is None) else environ) self.environ['bottle.request'] = self
'Bottle application handling this request.'
@DictProperty('environ', 'bottle.app', read_only=True) def app(self):
raise RuntimeError('This request is not connected to an application.')
'The bottle :class:`Route` object that matches this request.'
@DictProperty('environ', 'bottle.route', read_only=True) def route(self):
raise RuntimeError('This request is not connected to a route.')
'The arguments extracted from the URL.'
@DictProperty('environ', 'route.url_args', read_only=True) def url_args(self):
raise RuntimeError('This request is not connected to a route.')
'The value of ``PATH_INFO`` with exactly one prefixed slash (to fix broken clients and avoid the "empty path" edge case).'
@property def path(self):
return ('/' + self.environ.get('PATH_INFO', '').lstrip('/'))
'The ``REQUEST_METHOD`` value as an uppercase string.'
@property def method(self):
return self.environ.get('REQUEST_METHOD', 'GET').upper()
'A :class:`WSGIHeaderDict` that provides case-insensitive access to HTTP request headers.'
@DictProperty('environ', 'bottle.request.headers', read_only=True) def headers(self):
return WSGIHeaderDict(self.environ)
'Return the value of a request header, or a given default value.'
def get_header(self, name, default=None):
return self.headers.get(name, default)
'Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT decoded. Use :meth:`get_cookie` if you expect signed cookies.'
@DictProperty('environ', 'bottle.request.cookies', read_only=True) def cookies(self):
cookies = SimpleCookie(self.environ.get('HTTP_COOKIE', '')).values() return FormsDict(((c.key, c.value) for c in cookies))
'Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value.'
def get_cookie(self, key, default=None, secret=None, digestmod=hashlib.sha256):
value = self.cookies.get(key) if secret: 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...
'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`.'
@DictProperty('environ', 'bottle.request.query', read_only=True) def query(self):
get = self.environ['bottle.get'] = FormsDict() pairs = _parse_qsl(self.environ.get('QUERY_STRING', '')) for (key, value) in pairs: get[key] = value return get
'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`.'
@DictProperty('environ', 'bottle.request.forms', read_only=True) def forms(self):
forms = FormsDict() for (name, item) in self.POST.allitems(): if (not isinstance(item, FileUpload)): forms[name] = item return forms
'A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`.'
@DictProperty('environ', 'bottle.request.params', read_only=True) def params(self):
params = FormsDict() for (key, value) in self.query.allitems(): params[key] = value for (key, value) in self.forms.allitems(): params[key] = value return params