flask.py
This file
Path
flask.py
801 lines · 29.9 KiB · Python
Last changed by
Use setdefault() because it sets session.modified correctly.florentxbefore adoptiondbe0df7
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"""12from __future__ import with_statement13import os14import sys1516from jinja2 import Environment, PackageLoader, FileSystemLoader17from werkzeug import Request as RequestBase, Response as ResponseBase, \18 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \19 ImmutableDict, cached_property20from werkzeug.routing import Map, Rule21from werkzeug.exceptions import HTTPException22from werkzeug.contrib.securecookie import SecureCookie2324# try to load the best simplejson implementation available. If JSON25# is not installed, we add a failing class.26json_available = True27try:28 import simplejson as json29except ImportError:30 try:31 import json32 except ImportError:33 json_available = False3435# utilities we import from Werkzeug and Jinja2 that are unused36# in the module but are exported as public interface.37from werkzeug import abort, redirect38from jinja2 import Markup, escape3940# use pkg_resource if that works, otherwise fall back to cwd. The41# current working directory is generally not reliable with the notable42# exception of google appengine.43try:44 import pkg_resources45 pkg_resources.resource_stream46except (ImportError, AttributeError):47 pkg_resources = None484950class Request(RequestBase):51 """The request object used by default in flask. Remembers the52 matched endpoint and view arguments.5354 It is what ends up as :class:`~flask.request`. If you want to replace55 the request object used you can subclass this and set56 :attr:`~flask.Flask.request_class` to your subclass.57 """5859 endpoint = view_args = None6061 @cached_property62 def json(self):63 """If the mimetype is `application/json` this will contain the64 parsed JSON data.65 """66 if __debug__:67 _assert_have_json()68 if self.mimetype == 'application/json':69 return json.loads(self.data)707172class Response(ResponseBase):73 """The response object that is used by default in flask. Works like the74 response object from Werkzeug but is set to have a HTML mimetype by75 default. Quite often you don't have to create this object yourself because76 :meth:`~flask.Flask.make_response` will take care of that for you.7778 If you want to replace the response object used you can subclass this and79 set :attr:`~flask.Flask.request_class` to your subclass.80 """81 default_mimetype = 'text/html'828384class _RequestGlobals(object):85 pass868788class _NullSession(SecureCookie):89 """Class used to generate nicer error messages if sessions are not90 available. Will still allow read-only access to the empty session91 but fail on setting.92 """9394 def _fail(self, *args, **kwargs):95 raise RuntimeError('the session is unavailable because no secret '96 'key was set. Set the secret_key on the '97 'application to something unique and secret')98 __setitem__ = __delitem__ = clear = pop = popitem = \99 update = setdefault = _fail100 del _fail101102103class _RequestContext(object):104 """The request context contains all request relevant information. It is105 created at the beginning of the request and pushed to the106 `_request_ctx_stack` and removed at the end of it. It will create the107 URL adapter and request object for the WSGI environment provided.108 """109110 def __init__(self, app, environ):111 self.app = app112 self.url_adapter = app.url_map.bind_to_environ(environ)113 self.request = app.request_class(environ)114 self.session = app.open_session(self.request)115 if self.session is None:116 self.session = _NullSession()117 self.g = _RequestGlobals()118 self.flashes = None119120 def __enter__(self):121 _request_ctx_stack.push(self)122123 def __exit__(self, exc_type, exc_value, tb):124 # do not pop the request stack if we are in debug mode and an125 # exception happened. This will allow the debugger to still126 # access the request object in the interactive shell.127 if tb is None or not self.app.debug:128 _request_ctx_stack.pop()129130131def url_for(endpoint, **values):132 """Generates a URL to the given endpoint with the method provided.133134 :param endpoint: the endpoint of the URL (name of the function)135 :param values: the variable arguments of the URL rule136 """137 return _request_ctx_stack.top.url_adapter.build(endpoint, values)138139140def get_template_attribute(template_name, attribute):141 """Loads a macro (or variable) a template exports. This can be used to142 invoke a macro from within Python code. If you for example have a143 template named `_foo.html` with the following contents:144145 .. sourcecode:: html+jinja146147 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}148149 You can access this from Python code like this::150151 hello = get_template_attribute('_foo.html', 'hello')152 return hello('World')153154 .. versionadded:: 0.2155156 :param template_name: the name of the template157 :param attribute: the name of the variable of macro to acccess158 """159 return getattr(current_app.jinja_env.get_template(template_name).module,160 attribute)161162163def flash(message):164 """Flashes a message to the next request. In order to remove the165 flashed message from the session and to display it to the user,166 the template has to call :func:`get_flashed_messages`.167168 :param message: the message to be flashed.169 """170 session.setdefault('_flashes', []).append(message)171172173def get_flashed_messages():174 """Pulls all flashed messages from the session and returns them.175 Further calls in the same request to the function will return176 the same messages.177 """178 flashes = _request_ctx_stack.top.flashes179 if flashes is None:180 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])181 return flashes182183184def jsonify(*args, **kwargs):185 """Creates a :class:`~flask.Response` with the JSON representation of186 the given arguments with an `application/json` mimetype. The arguments187 to this function are the same as to the :class:`dict` constructor.188189 Example usage::190191 @app.route('/_get_current_user')192 def get_current_user():193 return jsonify(username=g.user.username,194 email=g.user.email,195 id=g.user.id)196197 This will send a JSON response like this to the browser::198199 {200 "username": "admin",201 "email": "admin@localhost",202 "id": 42203 }204205 This requires Python 2.6 or an installed version of simplejson.206207 .. versionadded:: 0.2208 """209 if __debug__:210 _assert_have_json()211 return current_app.response_class(json.dumps(dict(*args, **kwargs),212 indent=None if request.is_xhr else 2), mimetype='application/json')213214215def render_template(template_name, **context):216 """Renders a template from the template folder with the given217 context.218219 :param template_name: the name of the template to be rendered220 :param context: the variables that should be available in the221 context of the template.222 """223 current_app.update_template_context(context)224 return current_app.jinja_env.get_template(template_name).render(context)225226227def render_template_string(source, **context):228 """Renders a template from the given template source string229 with the given context.230231 :param template_name: the sourcecode of the template to be232 rendered233 :param context: the variables that should be available in the234 context of the template.235 """236 current_app.update_template_context(context)237 return current_app.jinja_env.from_string(source).render(context)238239240def _default_template_ctx_processor():241 """Default template context processor. Injects `request`,242 `session` and `g`.243 """244 reqctx = _request_ctx_stack.top245 return dict(246 request=reqctx.request,247 session=reqctx.session,248 g=reqctx.g249 )250251252def _assert_have_json():253 """Helper function that fails if JSON is unavailable."""254 if not json_available:255 raise RuntimeError('simplejson not installed')256257258def _get_package_path(name):259 """Returns the path to a package or cwd if that cannot be found."""260 try:261 return os.path.abspath(os.path.dirname(sys.modules[name].__file__))262 except (KeyError, AttributeError):263 return os.getcwd()264265266# figure out if simplejson escapes slashes. This behaviour was changed267# from one version to another without reason.268if not json_available or '\\/' not in json.dumps('/'):269270 def _tojson_filter(*args, **kwargs):271 if __debug__:272 _assert_have_json()273 return json.dumps(*args, **kwargs).replace('/', '\\/')274else:275 _tojson_filter = json.dumps276277278class Flask(object):279 """The flask object implements a WSGI application and acts as the central280 object. It is passed the name of the module or package of the281 application. Once it is created it will act as a central registry for282 the view functions, the URL rules, template configuration and much more.283284 The name of the package is used to resolve resources from inside the285 package or the folder the module is contained in depending on if the286 package parameter resolves to an actual python package (a folder with287 an `__init__.py` file inside) or a standard module (just a `.py` file).288289 For more information about resource loading, see :func:`open_resource`.290291 Usually you create a :class:`Flask` instance in your main module or292 in the `__init__.py` file of your package like this::293294 from flask import Flask295 app = Flask(__name__)296 """297298 #: the class that is used for request objects. See :class:`~flask.request`299 #: for more information.300 request_class = Request301302 #: the class that is used for response objects. See303 #: :class:`~flask.Response` for more information.304 response_class = Response305306 #: path for the static files. If you don't want to use static files307 #: you can set this value to `None` in which case no URL rule is added308 #: and the development server will no longer serve any static files.309 static_path = '/static'310311 #: if a secret key is set, cryptographic components can use this to312 #: sign cookies and other things. Set this to a complex random value313 #: when you want to use the secure cookie for instance.314 secret_key = None315316 #: The secure cookie uses this for the name of the session cookie317 session_cookie_name = 'session'318319 #: options that are passed directly to the Jinja2 environment320 jinja_options = ImmutableDict(321 autoescape=True,322 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']323 )324325 def __init__(self, package_name):326 #: the debug flag. Set this to `True` to enable debugging of327 #: the application. In debug mode the debugger will kick in328 #: when an unhandled exception ocurrs and the integrated server329 #: will automatically reload the application if changes in the330 #: code are detected.331 self.debug = False332333 #: the name of the package or module. Do not change this once334 #: it was set by the constructor.335 self.package_name = package_name336337 #: where is the app root located?338 self.root_path = _get_package_path(self.package_name)339340 #: a dictionary of all view functions registered. The keys will341 #: be function names which are also used to generate URLs and342 #: the values are the function objects themselves.343 #: to register a view function, use the :meth:`route` decorator.344 self.view_functions = {}345346 #: a dictionary of all registered error handlers. The key is347 #: be the error code as integer, the value the function that348 #: should handle that error.349 #: To register a error handler, use the :meth:`errorhandler`350 #: decorator.351 self.error_handlers = {}352353 #: a list of functions that should be called at the beginning354 #: of the request before request dispatching kicks in. This355 #: can for example be used to open database connections or356 #: getting hold of the currently logged in user.357 #: To register a function here, use the :meth:`before_request`358 #: decorator.359 self.before_request_funcs = []360361 #: a list of functions that are called at the end of the362 #: request. The function is passed the current response363 #: object and modify it in place or replace it.364 #: To register a function here use the :meth:`after_request`365 #: decorator.366 self.after_request_funcs = []367368 #: a list of functions that are called without arguments369 #: to populate the template context. Each returns a dictionary370 #: that the template context is updated with.371 #: To register a function here, use the :meth:`context_processor`372 #: decorator.373 self.template_context_processors = [_default_template_ctx_processor]374375 #: the :class:`~werkzeug.routing.Map` for this instance. You can use376 #: this to change the routing converters after the class was created377 #: but before any routes are connected. Example::378 #:379 #: from werkzeug import BaseConverter380 #:381 #: class ListConverter(BaseConverter):382 #: def to_python(self, value):383 #: return value.split(',')384 #: def to_url(self, values):385 #: return ','.join(BaseConverter.to_url(value)386 #: for value in values)387 #:388 #: app = Flask(__name__)389 #: app.url_map.converters['list'] = ListConverter390 self.url_map = Map()391392 if self.static_path is not None:393 self.add_url_rule(self.static_path + '/<filename>',394 build_only=True, endpoint='static')395 if pkg_resources is not None:396 target = (self.package_name, 'static')397 else:398 target = os.path.join(self.root_path, 'static')399 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {400 self.static_path: target401 })402403 #: the Jinja2 environment. It is created from the404 #: :attr:`jinja_options` and the loader that is returned405 #: by the :meth:`create_jinja_loader` function.406 self.jinja_env = Environment(loader=self.create_jinja_loader(),407 **self.jinja_options)408 self.jinja_env.globals.update(409 url_for=url_for,410 get_flashed_messages=get_flashed_messages411 )412 self.jinja_env.filters['tojson'] = _tojson_filter413414 def create_jinja_loader(self):415 """Creates the Jinja loader. By default just a package loader for416 the configured package is returned that looks up templates in the417 `templates` folder. To add other loaders it's possible to418 override this method.419 """420 if pkg_resources is None:421 return FileSystemLoader(os.path.join(self.root_path, 'templates'))422 return PackageLoader(self.package_name)423424 def update_template_context(self, context):425 """Update the template context with some commonly used variables.426 This injects request, session and g into the template context.427428 :param context: the context as a dictionary that is updated in place429 to add extra variables.430 """431 for func in self.template_context_processors:432 context.update(func())433434 def run(self, host='127.0.0.1', port=5000, **options):435 """Runs the application on a local development server. If the436 :attr:`debug` flag is set the server will automatically reload437 for code changes and show a debugger in case an exception happened.438439 :param host: the hostname to listen on. set this to ``'0.0.0.0'``440 to have the server available externally as well.441 :param port: the port of the webserver442 :param options: the options to be forwarded to the underlying443 Werkzeug server. See :func:`werkzeug.run_simple`444 for more information.445 """446 from werkzeug import run_simple447 if 'debug' in options:448 self.debug = options.pop('debug')449 options.setdefault('use_reloader', self.debug)450 options.setdefault('use_debugger', self.debug)451 return run_simple(host, port, self, **options)452453 def test_client(self):454 """Creates a test client for this application. For information455 about unit testing head over to :ref:`testing`.456 """457 from werkzeug import Client458 return Client(self, self.response_class, use_cookies=True)459460 def open_resource(self, resource):461 """Opens a resource from the application's resource folder. To see462 how this works, consider the following folder structure::463464 /myapplication.py465 /schemal.sql466 /static467 /style.css468 /template469 /layout.html470 /index.html471472 If you want to open the `schema.sql` file you would do the473 following::474475 with app.open_resource('schema.sql') as f:476 contents = f.read()477 do_something_with(contents)478479 :param resource: the name of the resource. To access resources within480 subfolders use forward slashes as separator.481 """482 if pkg_resources is None:483 return open(os.path.join(self.root_path, resource), 'rb')484 return pkg_resources.resource_stream(self.package_name, resource)485486 def open_session(self, request):487 """Creates or opens a new session. Default implementation stores all488 session data in a signed cookie. This requires that the489 :attr:`secret_key` is set.490491 :param request: an instance of :attr:`request_class`.492 """493 key = self.secret_key494 if key is not None:495 return SecureCookie.load_cookie(request, self.session_cookie_name,496 secret_key=key)497498 def save_session(self, session, response):499 """Saves the session if it needs updates. For the default500 implementation, check :meth:`open_session`.501502 :param session: the session to be saved (a503 :class:`~werkzeug.contrib.securecookie.SecureCookie`504 object)505 :param response: an instance of :attr:`response_class`506 """507 session.save_cookie(response, self.session_cookie_name)508509 def add_url_rule(self, rule, endpoint, view_func=None, **options):510 """Connects a URL rule. Works exactly like the :meth:`route`511 decorator. If a view_func is provided it will be registered with the512 endpoint.513514 Basically this example::515516 @app.route('/')517 def index():518 pass519520 Is equivalent to the following::521522 def index():523 pass524 app.add_url_rule('/', 'index', index)525526 If the view_func is not provided you will need to connect the endpoint527 to a view function like so::528529 app.view_functions['index'] = index530531 .. versionchanged:: 0.2532 `view_func` parameter added533534 :param rule: the URL rule as string535 :param endpoint: the endpoint for the registered URL rule. Flask536 itself assumes the name of the view function as537 endpoint538 :param view_func: the function to call when serving a request to the539 provided endpoint540 :param options: the options to be forwarded to the underlying541 :class:`~werkzeug.routing.Rule` object542 """543 options['endpoint'] = endpoint544 options.setdefault('methods', ('GET',))545 self.url_map.add(Rule(rule, **options))546 if view_func is not None:547 self.view_functions[endpoint] = view_func548549 def route(self, rule, **options):550 """A decorator that is used to register a view function for a551 given URL rule. Example::552553 @app.route('/')554 def index():555 return 'Hello World'556557 Variables parts in the route can be specified with angular558 brackets (``/user/<username>``). By default a variable part559 in the URL accepts any string without a slash however a different560 converter can be specified as well by using ``<converter:name>``.561562 Variable parts are passed to the view function as keyword563 arguments.564565 The following converters are possible:566567 =========== ===========================================568 `int` accepts integers569 `float` like `int` but for floating point values570 `path` like the default but also accepts slashes571 =========== ===========================================572573 Here some examples::574575 @app.route('/')576 def index():577 pass578579 @app.route('/<username>')580 def show_user(username):581 pass582583 @app.route('/post/<int:post_id>')584 def show_post(post_id):585 pass586587 An important detail to keep in mind is how Flask deals with trailing588 slashes. The idea is to keep each URL unique so the following rules589 apply:590591 1. If a rule ends with a slash and is requested without a slash592 by the user, the user is automatically redirected to the same593 page with a trailing slash attached.594 2. If a rule does not end with a trailing slash and the user request595 the page with a trailing slash, a 404 not found is raised.596597 This is consistent with how web servers deal with static files. This598 also makes it possible to use relative link targets safely.599600 The :meth:`route` decorator accepts a couple of other arguments601 as well:602603 :param rule: the URL rule as string604 :param methods: a list of methods this rule should be limited605 to (``GET``, ``POST`` etc.). By default a rule606 just listens for ``GET`` (and implicitly ``HEAD``).607 :param subdomain: specifies the rule for the subdoain in case608 subdomain matching is in use.609 :param strict_slashes: can be used to disable the strict slashes610 setting for this rule. See above.611 :param options: other options to be forwarded to the underlying612 :class:`~werkzeug.routing.Rule` object.613 """614 def decorator(f):615 self.add_url_rule(rule, f.__name__, f, **options)616 return f617 return decorator618619 def errorhandler(self, code):620 """A decorator that is used to register a function give a given621 error code. Example::622623 @app.errorhandler(404)624 def page_not_found():625 return 'This page does not exist', 404626627 You can also register a function as error handler without using628 the :meth:`errorhandler` decorator. The following example is629 equivalent to the one above::630631 def page_not_found():632 return 'This page does not exist', 404633 app.error_handlers[404] = page_not_found634635 :param code: the code as integer for the handler636 """637 def decorator(f):638 self.error_handlers[code] = f639 return f640 return decorator641642 def before_request(self, f):643 """Registers a function to run before each request."""644 self.before_request_funcs.append(f)645 return f646647 def after_request(self, f):648 """Register a function to be run after each request."""649 self.after_request_funcs.append(f)650 return f651652 def context_processor(self, f):653 """Registers a template context processor function."""654 self.template_context_processors.append(f)655 return f656657 def match_request(self):658 """Matches the current request against the URL map and also659 stores the endpoint and view arguments on the request object660 is successful, otherwise the exception is stored.661 """662 rv = _request_ctx_stack.top.url_adapter.match()663 request.endpoint, request.view_args = rv664 return rv665666 def dispatch_request(self):667 """Does the request dispatching. Matches the URL and returns the668 return value of the view or error handler. This does not have to669 be a response object. In order to convert the return value to a670 proper response object, call :func:`make_response`.671 """672 try:673 endpoint, values = self.match_request()674 return self.view_functions[endpoint](**values)675 except HTTPException, e:676 handler = self.error_handlers.get(e.code)677 if handler is None:678 return e679 return handler(e)680 except Exception, e:681 handler = self.error_handlers.get(500)682 if self.debug or handler is None:683 raise684 return handler(e)685686 def make_response(self, rv):687 """Converts the return value from a view function to a real688 response object that is an instance of :attr:`response_class`.689690 The following types are allowd for `rv`:691692 ======================= ===========================================693 :attr:`response_class` the object is returned unchanged694 :class:`str` a response object is created with the695 string as body696 :class:`unicode` a response object is created with the697 string encoded to utf-8 as body698 :class:`tuple` the response object is created with the699 contents of the tuple as arguments700 a WSGI function the function is called as WSGI application701 and buffered as response object702 ======================= ===========================================703704 :param rv: the return value from the view function705 """706 if isinstance(rv, self.response_class):707 return rv708 if isinstance(rv, basestring):709 return self.response_class(rv)710 if isinstance(rv, tuple):711 return self.response_class(*rv)712 return self.response_class.force_type(rv, request.environ)713714 def preprocess_request(self):715 """Called before the actual request dispatching and will716 call every as :meth:`before_request` decorated function.717 If any of these function returns a value it's handled as718 if it was the return value from the view and further719 request handling is stopped.720 """721 for func in self.before_request_funcs:722 rv = func()723 if rv is not None:724 return rv725726 def process_response(self, response):727 """Can be overridden in order to modify the response object728 before it's sent to the WSGI server. By default this will729 call all the :meth:`after_request` decorated functions.730731 :param response: a :attr:`response_class` object.732 :return: a new response object or the same, has to be an733 instance of :attr:`response_class`.734 """735 session = _request_ctx_stack.top.session736 if not isinstance(session, _NullSession):737 self.save_session(session, response)738 for handler in self.after_request_funcs:739 response = handler(response)740 return response741742 def wsgi_app(self, environ, start_response):743 """The actual WSGI application. This is not implemented in744 `__call__` so that middlewares can be applied without losing a745 reference to the class. So instead of doing this::746747 app = MyMiddleware(app)748749 It's a better idea to do this instead::750751 app.wsgi_app = MyMiddleware(app.wsgi_app)752753 Then you still have the original application object around and754 can continue to call methods on it.755756 :param environ: a WSGI environment757 :param start_response: a callable accepting a status code,758 a list of headers and an optional759 exception context to start the response760 """761 with self.request_context(environ):762 rv = self.preprocess_request()763 if rv is None:764 rv = self.dispatch_request()765 response = self.make_response(rv)766 response = self.process_response(response)767 return response(environ, start_response)768769 def request_context(self, environ):770 """Creates a request context from the given environment and binds771 it to the current context. This must be used in combination with772 the `with` statement because the request is only bound to the773 current context for the duration of the `with` block.774775 Example usage::776777 with app.request_context(environ):778 do_something_with(request)779780 :params environ: a WSGI environment781 """782 return _RequestContext(self, environ)783784 def test_request_context(self, *args, **kwargs):785 """Creates a WSGI environment from the given values (see786 :func:`werkzeug.create_environ` for more information, this787 function accepts the same arguments).788 """789 return self.request_context(create_environ(*args, **kwargs))790791 def __call__(self, environ, start_response):792 """Shortcut for :attr:`wsgi_app`."""793 return self.wsgi_app(environ, start_response)794795796# context locals797_request_ctx_stack = LocalStack()798current_app = LocalProxy(lambda: _request_ctx_stack.top.app)799request = LocalProxy(lambda: _request_ctx_stack.top.request)800session = LocalProxy(lambda: _request_ctx_stack.top.session)801g = LocalProxy(lambda: _request_ctx_stack.top.g)