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', 'after'], called)
'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.assertEqual(['before', 'route', 'after'], called)
'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.assertEqual(['before', 'after'], called)
'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'], called)
'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') self.assertBody(result, '/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.assertBody('', '/test/304')
'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.assertEqual('/app/a/xxx/c', bottle.url('named', b='xxx')) bottle.request.environ['SCRIPT_NAME'] = '/app/' self.assertEqual('/app/a/xxx/c', bottle.url('named', b='xxx')) bottle.request.environ['SCRIPT_NAME'] = 'app/' self.assertEqual('/app/a/xxx/c', bottle.url('named', b='xxx'))
'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 = MakoTemplate('<%inherit file="views/mako_base.tpl"/>\nc${var}c\n', lookup=['./']).render(var='v') self.assertEqual('o\ncvc\no\n', 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)) self.assertEqual('ungerade', t.render(var=1))
'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) self.assertEqual('/', BaseRequest({}).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_NAME': raw}).script_name) self.assertEqual('/', BaseRequest({}).script_name)
'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)) self.assertEqual(['/a/b/c', '/d'], test_shift('/a/b', '/c/d', 1)) self.assertEqual(['/a', '/b/c/d'], test_shift('/a/b', '/c/d', (-1))) self.assertEqual(['/a/b/c', '/d/'], test_shift('/a/b', '/c/d/', 1)) self.assertEqual(['/a', '/b/c/d/'], test_shift('/a/b', '/c/d/', (-1))) self.assertEqual(['/a/b/c', '/d/'], test_shift('/a/b/', '/c/d/', 1)) self.assertEqual(['/a', '/b/c/d/'], test_shift('/a/b/', '/c/d/', (-1))) self.assertEqual(['/a/b/c/d', '/'], test_shift('/', '/a/b/c/d', 4)) self.assertEqual(['/', '/a/b/c/d/'], test_shift('/a/b/c/d', '/', (-4))) self.assertRaises(AssertionError, test_shift, '/a/b', '/c/d', 3) self.assertRaises(AssertionError, test_shift, '/a/b', '/c/d', (-3))
'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.assertEqual('http://example.com:81/', request.url) request = BaseRequest({'wsgi.url_scheme': 'https', 'SERVER_NAME': 'example.com'}) self.assertEqual('https://example.com/', request.url) request = BaseRequest({'HTTP_HOST': 'example.com', 'PATH_INFO': '/path', 'QUERY_STRING': '1=b&c=d', 'SCRIPT_NAME': '/sp'}) self.assertEqual('http://example.com/sp/path?1=b&c=d', request.url) request = BaseRequest({'HTTP_HOST': 'example.com', 'PATH_INFO': '/pa th', 'SCRIPT_NAME': '/s p'}) self.assertEqual('http://example.com/s%20p/pa%20th', request.url)
'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' self.assertEqual(request[k], 'test') del request['PATH_INFO'] self.assertTrue(('PATH_INFO' not in request))
'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')) self.assertTrue((request.headers['Some-Other-Header'] == 'some other 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_cookie(n))
'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')) self.assertEqual('1', request.query['a']) self.assertEqual('b', request.query['b']) self.assertEqual(tonat(tob('\xe7\x93\xb6'), 'latin1'), request.query['cn']) self.assertEqual(touni('\xe7\x93\xb6'), request.query.cn)
'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.assertTrue(('b' in request.POST)) self.assertEqual(['a', '1'], request.POST.getall('a')) self.assertEqual(['b'], request.POST.getall('b')) self.assertEqual('1', request.POST['a']) self.assertEqual('b', request.POST['b']) self.assertEqual('', request.POST['c']) self.assertEqual('', request.POST['d']) self.assertEqual(tonat(tob('\xe7\x93\xb6'), 'latin1'), request.POST['cn']) self.assertEqual(touni('\xe7\x93\xb6'), request.POST.cn)
'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.assertEqual(sq, request.body.read())
'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())) self.assertEqual('p', request.params['c'])
'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'], list(request.POST.keys()))
'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'), request.body.readline()) self.assertEqual(tob('abc'), request.body.readline(3))
'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())) self.assertEqual(1024, len(request.body.read(1024))) self.assertEqual((1024 * 1000), len(request.body.readline())) self.assertEqual(1024, len(request.body.readline(1024)))
'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, len(request.body.readline())) self.assertEqual(42, len(request.body.readline(1024)))
'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) self.assertTrue(('file1' in request.POST)) self.assertTrue(('file1' in request.files)) self.assertTrue(('file1' not in request.forms)) cmp = (tob('content1') if (sys.version_info >= (3, 2, 0)) else 'content1') self.assertEqual(cmp, request.POST['file1'].file.read()) self.assertTrue(('\xe4\xb8\x87\xe9\x9a\xbe' in request.POST)) self.assertTrue(('\xe4\xb8\x87\xe9\x9a\xbe' in request.files)) self.assertTrue(('\xe4\xb8\x87\xe9\x9a\xbe' not in request.forms)) self.assertEqual('foo.py', request.POST['\xe4\xb8\x87\xe9\x9a\xbe'].filename) self.assertTrue(request.files['\xe4\xb8\x87\xe9\x9a\xbe']) self.assertFalse(request.files.file77) x = request.POST['\xe4\xb8\x87\xe9\x9a\xbe'].file.read() if ((3, 2, 0) > sys.version_info >= (3, 0, 0)): x = x.encode('utf8') self.assertEqual(tob('\xc3\xa4\n\xc3\xb6\r\xc3\xbc'), x) self.assertTrue(('file3' not in request.POST)) self.assertTrue(('file3' not in request.files)) self.assertTrue(('file3' not in request.forms)) self.assertEqual('value1', request.POST['field1']) self.assertTrue(('field1' not in request.files)) self.assertEqual('value1', request.forms['field1']) self.assertEqual(2, len(request.POST.getall('field2'))) self.assertEqual(['value2', 'value3'], request.POST.getall('field2')) self.assertEqual(['value2', 'value3'], request.forms.getall('field2')) self.assertTrue(('field2' not in request.files))
'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, (lambda : BaseRequest(e).json))
'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, test)
'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) = self.filters[mode](conf) if (not key): pattern += ('(?:%s)' % mask) key = ('anon%d' % anons) anons += 1 else: 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.') return url_args elif re_pattern.groupindex: def getargs(path): return re_match(path).groupdict() 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) 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)
'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]) return (url if (not query) else ((url + '?') + urlencode(query))) except KeyError as E: raise RouteBuildError(('Missing URL argument: %r' % E.args[0]))
'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])): (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 {})) allowed = set([]) nocheck = set(methods) for method in (set(self.static) - nocheck): if (path in self.static[method]): allowed.add(verb) 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) raise HTTPError(404, ('Not found: ' + repr(path)))
'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.skiplist)): continue if name: unique.add(name) (yield p)
'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 if (not isinstance(func, FunctionType)): func = filter((lambda x: isinstance(x, FunctionType)), map((lambda x: x.cell_contents), attributes)) func = list(func)[0] return func
'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 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.'
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(plugin, 'close'): plugin.close() if removed: self.reset() return removed
'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 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`).'
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 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)
'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) if isinstance(out, bytes): if ('Content-Length' not in response): response['Content-Length'] = len(out) return [out] 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) 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) try: iout = iter(out) first = next(iout) while (not first): first = next(iout) except StopIteration: return self._cast('') except HTTPResponse as E: first = E except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception as error: if (not self.catchall): raise first = HTTPError(500, 'Unhandled exception', error, format_exc()) if isinstance(first, HTTPResponse): return self._cast(first) elif isinstance(first, bytes): new_iter = itertools.chain([first], iout) elif isinstance(first, unicode): encoder = (lambda x: x.encode(response.charset)) new_iter = imap(encoder, itertools.chain([first], iout)) else: 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
'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) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception as E: 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)]
'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 = pickle.loads(base64.b64decode(msg)) if (dst and (dst[0] == key)): return dst[1] return default return (value or default)
'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