flask.py
This file
Path
flask.py
605 lines · 23.1 KiB · Python
Last changed by
Added testing documentationArmin Ronacherbefore adoption03148db
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import os13import sys14import pkg_resources15from threading import local16from contextlib import contextmanager17from jinja2 import Environment, PackageLoader18from werkzeug import Request as RequestBase, Response as ResponseBase, \19 LocalStack, LocalProxy, create_environ, cached_property20from werkzeug.routing import Map, Rule21from werkzeug.exceptions import HTTPException, InternalServerError22from werkzeug.contrib.securecookie import SecureCookie2324# utilities we import from Werkzeug and Jinja2 that are unused25# in the module but are exported as public interface.26from werkzeug import abort, redirect27from jinja2 import Markup, escape282930class Request(RequestBase):31 """The request object used by default in flask. Remembers the32 matched endpoint and view arguments.3334 It is what ends up as :class:`~flask.request`. If you want to replace35 the request object used you can subclass this and set36 :attr:`~flask.Flask.request_class` to your subclass.37 """3839 def __init__(self, environ):40 RequestBase.__init__(self, environ)41 self.endpoint = None42 self.view_args = None434445class Response(ResponseBase):46 """The response object that is used by default in flask. Works like the47 response object from Werkzeug but is set to have a HTML mimetype by48 default. Quite often you don't have to create this object yourself because49 :meth:`~flask.Flask.make_response` will take care of that for you.5051 If you want to replace the response object used you can subclass this and52 set :attr:`~flask.Flask.request_class` to your subclass.53 """54 default_mimetype = 'text/html'555657class _RequestGlobals(object):58 pass596061class _RequestContext(object):62 """The request context contains all request relevant information. It is63 created at the beginning of the request and pushed to the64 `_request_ctx_stack` and removed at the end of it. It will create the65 URL adapter and request object for the WSGI environment provided.66 """6768 def __init__(self, app, environ):69 self.app = app70 self.url_adapter = app.url_map.bind_to_environ(environ)71 self.request = app.request_class(environ)72 self.session = app.open_session(self.request)73 self.g = _RequestGlobals()74 self.flashes = None757677def url_for(endpoint, **values):78 """Generates a URL to the given endpoint with the method provided.7980 :param endpoint: the endpoint of the URL (name of the function)81 :param values: the variable arguments of the URL rule82 """83 return _request_ctx_stack.top.url_adapter.build(endpoint, values)848586def flash(message):87 """Flashes a message to the next request. In order to remove the88 flashed message from the session and to display it to the user,89 the template has to call :func:`get_flashed_messages`.9091 :param message: the message to be flashed.92 """93 session['_flashes'] = (session.get('_flashes', [])) + [message]949596def get_flashed_messages():97 """Pulls all flashed messages from the session and returns them.98 Further calls in the same request to the function will return99 the same messages.100 """101 flashes = _request_ctx_stack.top.flashes102 if flashes is None:103 _request_ctx_stack.top.flashes = flashes = \104 session.pop('_flashes', [])105 return flashes106107108def render_template(template_name, **context):109 """Renders a template from the template folder with the given110 context.111112 :param template_name: the name of the template to be rendered113 :param context: the variables that should be available in the114 context of the template.115 """116 current_app.update_template_context(context)117 return current_app.jinja_env.get_template(template_name).render(context)118119120def render_template_string(source, **context):121 """Renders a template from the given template source string122 with the given context.123124 :param template_name: the sourcecode of the template to be125 rendered126 :param context: the variables that should be available in the127 context of the template.128 """129 current_app.update_template_context(context)130 return current_app.jinja_env.from_string(source).render(context)131132133class Flask(object):134 """The flask object implements a WSGI application and acts as the central135 object. It is passed the name of the module or package of the136 application. Once it is created it will act as a central registry for137 the view functions, the URL rules, template configuration and much more.138139 The name of the package is used to resolve resources from inside the140 package or the folder the module is contained in depending on if the141 package parameter resolves to an actual python package (a folder with142 an `__init__.py` file inside) or a standard module (just a `.py` file).143144 For more information about resource loading, see :func:`open_resource`.145146 Usually you create a :class:`Flask` instance in your main module or147 in the `__init__.py` file of your package like this::148149 from flask import Flask150 app = Flask(__name__)151 """152153 #: the class that is used for request objects. See :class:`~flask.request`154 #: for more information.155 request_class = Request156157 #: the class that is used for response objects. See158 #: :class:`~flask.Response` for more information.159 response_class = Response160161 #: path for the static files. If you don't want to use static files162 #: you can set this value to `None` in which case no URL rule is added163 #: and the development server will no longer serve any static files.164 static_path = '/static'165166 #: if a secret key is set, cryptographic components can use this to167 #: sign cookies and other things. Set this to a complex random value168 #: when you want to use the secure cookie for instance.169 secret_key = None170171 #: The secure cookie uses this for the name of the session cookie172 session_cookie_name = 'session'173174 #: options that are passed directly to the Jinja2 environment175 jinja_options = dict(176 autoescape=True,177 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']178 )179180 def __init__(self, package_name):181 #: the debug flag. Set this to `True` to enable debugging of182 #: the application. In debug mode the debugger will kick in183 #: when an unhandled exception ocurrs and the integrated server184 #: will automatically reload the application if changes in the185 #: code are detected.186 self.debug = False187188 #: the name of the package or module. Do not change this once189 #: it was set by the constructor.190 self.package_name = package_name191192 #: a dictionary of all view functions registered. The keys will193 #: be function names which are also used to generate URLs and194 #: the values are the function objects themselves.195 #: to register a view function, use the :meth:`route` decorator.196 self.view_functions = {}197198 #: a dictionary of all registered error handlers. The key is199 #: be the error code as integer, the value the function that200 #: should handle that error.201 #: To register a error handler, use the :meth:`errorhandler`202 #: decorator.203 self.error_handlers = {}204205 #: a list of functions that should be called at the beginning206 #: of the request before request dispatching kicks in. This207 #: can for example be used to open database connections or208 #: getting hold of the currently logged in user.209 #: To register a function here, use the :meth:`request_init`210 #: decorator.211 self.request_init_funcs = []212213 #: a list of functions that are called at the end of the214 #: request. Tha function is passed the current response215 #: object and modify it in place or replace it.216 #: To register a function here use the :meth:`request_shtdown`217 #: decorator.218 self.request_shutdown_funcs = []219 self.url_map = Map()220221 if self.static_path is not None:222 self.url_map.add(Rule(self.static_path + '/<filename>',223 build_only=True, endpoint='static'))224225 #: the Jinja2 environment. It is created from the226 #: :attr:`jinja_options` and the loader that is returned227 #: by the :meth:`create_jinja_loader` function.228 self.jinja_env = Environment(loader=self.create_jinja_loader(),229 **self.jinja_options)230 self.jinja_env.globals.update(231 url_for=url_for,232 get_flashed_messages=get_flashed_messages233 )234235 def create_jinja_loader(self):236 """Creates the Jinja loader. By default just a package loader for237 the configured package is returned that looks up templates in the238 `templates` folder. To add other loaders it's possible to239 override this method.240 """241 return PackageLoader(self.package_name)242243 def update_template_context(self, context):244 """Update the template context with some commonly used variables.245 This injects request, session and g into the template context.246247 :param context: the context as a dictionary that is updated in place248 to add extra variables.249 """250 reqctx = _request_ctx_stack.top251 context['request'] = reqctx.request252 context['session'] = reqctx.session253 context['g'] = reqctx.g254255 def run(self, host='localhost', port=5000, **options):256 """Runs the application on a local development server. If the257 :attr:`debug` flag is set the server will automatically reload258 for code changes and show a debugger in case an exception happened.259260 :param host: the hostname to listen on. set this to ``'0.0.0.0'``261 to have the server available externally as well.262 :param port: the port of the webserver263 :param options: the options to be forwarded to the underlying264 Werkzeug server. See :func:`werkzeug.run_simple`265 for more information.266 """267 from werkzeug import run_simple268 if 'debug' in options:269 self.debug = options.pop('debug')270 if self.static_path is not None:271 options['static_files'] = {272 self.static_path: (self.package_name, 'static')273 }274 options.setdefault('use_reloader', self.debug)275 options.setdefault('use_debugger', self.debug)276 return run_simple(host, port, self, **options)277278 def test_client(self):279 """Creates a test client for this application. For information280 about unit testing head over to :ref:`testing`.281 """282 from werkzeug import Client283 return Client(self, self.response_class, use_cookies=True)284285 def open_resource(self, resource):286 """Opens a resource from the application's resource folder. To see287 how this works, consider the following folder structure::288289 /myapplication.py290 /schemal.sql291 /static292 /style.css293 /template294 /layout.html295 /index.html296297 If you want to open the `schema.sql` file you would do the298 following::299300 with app.open_resource('schema.sql') as f:301 contents = f.read()302 do_something_with(contents)303304 :param resource: the name of the resource. To access resources within305 subfolders use forward slashes as separator.306 """307 return pkg_resources.resource_stream(self.package_name, resource)308309 def open_session(self, request):310 """Creates or opens a new session. Default implementation stores all311 session data in a signed cookie. This requires that the312 :attr:`secret_key` is set.313314 :param request: an instance of :attr:`request_class`.315 """316 key = self.secret_key317 if key is not None:318 return SecureCookie.load_cookie(request, self.session_cookie_name,319 secret_key=key)320321 def save_session(self, session, response):322 """Saves the session if it needs updates. For the default323 implementation, check :meth:`open_session`.324325 :param session: the session to be saved (a326 :class:`~werkzeug.contrib.securecookie.SecureCookie`327 object)328 :param request: an instance of :attr:`response_class`329 """330 if session is not None:331 session.save_cookie(response, self.session_cookie_name)332333 def add_url_rule(self, rule, endpoint, **options):334 """Connects a URL rule. Works exactly like the :meth:`route`335 decorator but does not register the view function for the endpoint.336337 Basically this example::338339 @app.route('/')340 def index():341 pass342343 Is equivalent to the following::344345 def index():346 pass347 app.add_url_rule('index', '/')348 app.view_functions['index'] = index349350 :param rule: the URL rule as string351 :param endpoint: the endpoint for the registered URL rule. Flask352 itself assumes the name of the view function as353 endpoint354 :param options: the options to be forwarded to the underlying355 :class:`~werkzeug.routing.Rule` object356 """357 options['endpoint'] = endpoint358 options.setdefault('methods', ('GET',))359 self.url_map.add(Rule(rule, **options))360361 def route(self, rule, **options):362 """A decorator that is used to register a view function for a363 given URL rule. Example::364365 @app.route('/')366 def index():367 return 'Hello World'368369 Variables parts in the route can be specified with angular370 brackets (``/user/<username>``). By default a variable part371 in the URL accepts any string without a slash however a different372 converter can be specified as well by using ``<converter:name>``.373374 Variable parts are passed to the view function as keyword375 arguments.376377 The following converters are possible:378379 =========== ===========================================380 `int` accepts integers381 `float` like `int` but for floating point values382 `path` like the default but also accepts slashes383 =========== ===========================================384385 Here some examples::386387 @app.route('/')388 def index():389 pass390391 @app.route('/<username>')392 def show_user(username):393 pass394395 @app.route('/post/<int:post_id>')396 def show_post(post_id):397 pass398399 An important detail to keep in mind is how Flask deals with trailing400 slashes. The idea is to keep each URL unique so the following rules401 apply:402403 1. If a rule ends with a slash and is requested without a slash404 by the user, the user is automatically redirected to the same405 page with a trailing slash attached.406 2. If a rule does not end with a trailing slash and the user request407 the page with a trailing slash, a 404 not found is raised.408409 This is consistent with how web servers deal with static files. This410 also makes it possible to use relative link targets safely.411412 The :meth:`route` decorator accepts a couple of other arguments413 as well:414415 :param rule: the URL rule as string416 :param methods: a list of methods this rule should be limited417 to (``GET``, ``POST`` etc.). By default a rule418 just listens for ``GET`` (and implicitly ``HEAD``).419 :param subdomain: specifies the rule for the subdoain in case420 subdomain matching is in use.421 :param strict_slashes: can be used to disable the strict slashes422 setting for this rule. See above.423 :param options: other options to be forwarded to the underlying424 :class:`~werkzeug.routing.Rule` object.425 """426 def decorator(f):427 self.add_url_rule(rule, f.__name__, **options)428 self.view_functions[f.__name__] = f429 return f430 return decorator431432 def errorhandler(self, code):433 """A decorator that is used to register a function give a given434 error code. Example::435436 @app.errorhandler(404)437 def page_not_found():438 return 'This page does not exist', 404439440 You can also register a function as error handler without using441 the :meth:`errorhandler` decorator. The following example is442 equivalent to the one above::443444 def page_not_found():445 return 'This page does not exist', 404446 app.error_handlers[404] = page_not_found447448 :param code: the code as integer for the handler449 """450 def decorator(f):451 self.error_handlers[code] = f452 return f453 return decorator454455 def request_init(self, f):456 """Registers a function to run before each request."""457 self.request_init_funcs.append(f)458 return f459460 def request_shutdown(self, f):461 """Register a function to be run after each request."""462 self.request_shutdown_funcs.append(f)463 return f464465 def match_request(self):466 """Matches the current request against the URL map and also467 stores the endpoint and view arguments on the request object468 is successful, otherwise the exception is stored.469 """470 rv = _request_ctx_stack.top.url_adapter.match()471 request.endpoint, request.view_args = rv472 return rv473474 def dispatch_request(self):475 """Does the request dispatching. Matches the URL and returns the476 return value of the view or error handler. This does not have to477 be a response object. In order to convert the return value to a478 proper response object, call :func:`make_response`.479 """480 try:481 endpoint, values = self.match_request()482 return self.view_functions[endpoint](**values)483 except HTTPException, e:484 handler = self.error_handlers.get(e.code)485 if handler is None:486 return e487 return handler(e)488 except Exception, e:489 handler = self.error_handlers.get(500)490 if self.debug or handler is None:491 raise492 return handler(e)493494 def make_response(self, rv):495 """Converts the return value from a view function to a real496 response object that is an instance of :attr:`response_class`.497498 The following types are allowd for `rv`:499500 ======================= ===========================================501 :attr:`response_class` the object is returned unchanged502 :class:`str` a response object is created with the503 string as body504 :class:`unicode` a response object is created with the505 string encoded to utf-8 as body506 :class:`tuple` the response object is created with the507 contents of the tuple as arguments508 a WSGI function the function is called as WSGI application509 and buffered as response object510 ======================= ===========================================511512 :param rv: the return value from the view function513 """514 if isinstance(rv, self.response_class):515 return rv516 if isinstance(rv, basestring):517 return self.response_class(rv)518 if isinstance(rv, tuple):519 return self.response_class(*rv)520 return self.response_class.force_type(rv, request.environ)521522 def preprocess_request(self):523 """Called before the actual request dispatching and will524 call every as :func:`request_init` decorated function.525 If any of these function returns a value it's handled as526 if it was the return value from the view and further527 request handling is stopped.528 """529 for func in self.request_init_funcs:530 rv = func()531 if rv is not None:532 return rv533534 def process_response(self, response):535 """Can be overridden in order to modify the response object536 before it's sent to the WSGI server.537538 :param response: a :attr:`response_class` object.539 :return: a new response object or the same, has to be an540 instance of :attr:`response_class`.541 """542 session = _request_ctx_stack.top.session543 if session is not None:544 self.save_session(session, response)545 for handler in self.request_shutdown_funcs:546 response = handler(response)547 return response548549 def wsgi_app(self, environ, start_response):550 """The actual WSGI application. This is not implemented in551 `__call__` so that middlewares can be applied:552553 app.wsgi_app = MyMiddleware(app.wsgi_app)554555 :param environ: a WSGI environment556 :param start_response: a callable accepting a status code,557 a list of headers and an optional558 exception context to start the response559 """560 with self.request_context(environ):561 rv = self.preprocess_request()562 if rv is None:563 rv = self.dispatch_request()564 response = self.make_response(rv)565 response = self.process_response(response)566 return response(environ, start_response)567568 @contextmanager569 def request_context(self, environ):570 """Creates a request context from the given environment and binds571 it to the current context. This must be used in combination with572 the `with` statement because the request is only bound to the573 current context for the duration of the `with` block.574575 Example usage::576577 with app.request_context(environ):578 do_something_with(request)579580 :params environ: a WSGI environment581 """582 _request_ctx_stack.push(_RequestContext(self, environ))583 try:584 yield585 finally:586 _request_ctx_stack.pop()587588 def test_request_context(self, *args, **kwargs):589 """Creates a WSGI environment from the given values (see590 :func:`werkzeug.create_environ` for more information, this591 function accepts the same arguments).592 """593 return self.request_context(create_environ(*args, **kwargs))594595 def __call__(self, environ, start_response):596 """Shortcut for :attr:`wsgi_app`"""597 return self.wsgi_app(environ, start_response)598599600# context locals601_request_ctx_stack = LocalStack()602current_app = LocalProxy(lambda: _request_ctx_stack.top.app)603request = LocalProxy(lambda: _request_ctx_stack.top.request)604session = LocalProxy(lambda: _request_ctx_stack.top.session)605g = LocalProxy(lambda: _request_ctx_stack.top.g)