Merged in changes from justquick
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parents 10fff18, 1a69c7d · Browse files · 11 files·+1608 added−1602 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+1608 added−1602 removed
- tests:+3 added−3 removed
- other:+1605 added−1599 removed
Provenance
- Commit
81148db- Tree
2c287fd- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
10fff18- Parent 2
1a69c7d
11 files changed+1608 added−1602 removed
added:flask/__init__.py+23 added
1+# -*- coding: utf-8 -*-2+"""3+ flask4+ ~~~~~5+6+ A microframework based on Werkzeug. It's extensively documented7+ and follows best practice patterns.8+9+ :copyright: (c) 2010 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+# utilities we import from Werkzeug and Jinja2 that are unused14+# in the module but are exported as public interface.15+from werkzeug import abort, redirect16+from jinja2 import Markup, escape17+18+from flask.app import Flask19+from flask.helpers import url_for, jsonify, json_available, flash, send_file, \20+ get_flashed_messages, render_template, render_template, render_template_string, \21+ get_template_attribute22+from flask.globals import current_app, g, request, session, _request_ctx_stack23+from flask.module import Moduleadded:flask/app.py+798 added
1+from threading import Lock2+from datetime import timedelta, datetime3+from itertools import chain4+5+from jinja2 import Environment, PackageLoader, FileSystemLoader6+from werkzeug import ImmutableDict, SharedDataMiddleware, create_environ7+from werkzeug.routing import Map, Rule8+from werkzeug.exceptions import HTTPException, InternalServerError9+10+from flask.helpers import _PackageBoundObject, url_for, get_flashed_messages, \11+ _tojson_filter, get_pkg_resources12+from flask.wrappers import Request, Response13+from flask.conf import ConfigAttribute, Config14+from flask.ctx import _default_template_ctx_processor, _RequestContext15+from flask.globals import _request_ctx_stack, request16+from flask.session import Session, _NullSession17+from flask.module import _ModuleSetupState18+19+# a lock used for logger initialization20+_logger_lock = Lock()21+22+23+class Flask(_PackageBoundObject):24+ """The flask object implements a WSGI application and acts as the central25+ object. It is passed the name of the module or package of the26+ application. Once it is created it will act as a central registry for27+ the view functions, the URL rules, template configuration and much more.28+29+ The name of the package is used to resolve resources from inside the30+ package or the folder the module is contained in depending on if the31+ package parameter resolves to an actual python package (a folder with32+ an `__init__.py` file inside) or a standard module (just a `.py` file).33+34+ For more information about resource loading, see :func:`open_resource`.35+36+ Usually you create a :class:`Flask` instance in your main module or37+ in the `__init__.py` file of your package like this::38+39+ from flask import Flask40+ app = Flask(__name__)41+42+ .. admonition:: About the First Parameter43+44+ The idea of the first parameter is to give Flask an idea what45+ belongs to your application. This name is used to find resources46+ on the file system, can be used by extensions to improve debugging47+ information and a lot more.48+49+ So it's important what you provide there. If you are using a single50+ module, `__name__` is always the correct value. If you however are51+ using a package, it's usually recommended to hardcode the name of52+ your package there.53+54+ For example if your application is defined in `yourapplication/app.py`55+ you should create it with one of the two versions below::56+57+ app = Flask('yourapplication')58+ app = Flask(__name__.split('.')[0])59+60+ Why is that? The application will work even with `__name__`, thanks61+ to how resources are looked up. However it will make debugging more62+ painful. Certain extensions can make assumptions based on the63+ import name of your application. For example the Flask-SQLAlchemy64+ extension will look for the code in your application that triggered65+ an SQL query in debug mode. If the import name is not properly set66+ up, that debugging information is lost. (For example it would only67+ pick up SQL queries in `yourapplicaiton.app` and not68+ `yourapplication.views.frontend`)69+ """70+71+ #: The class that is used for request objects. See :class:`~flask.Request`72+ #: for more information.73+ request_class = Request74+75+ #: The class that is used for response objects. See76+ #: :class:`~flask.Response` for more information.77+ response_class = Response78+79+ #: Path for the static files. If you don't want to use static files80+ #: you can set this value to `None` in which case no URL rule is added81+ #: and the development server will no longer serve any static files.82+ static_path = '/static'83+84+ #: The debug flag. Set this to `True` to enable debugging of the85+ #: application. In debug mode the debugger will kick in when an unhandled86+ #: exception ocurrs and the integrated server will automatically reload87+ #: the application if changes in the code are detected.88+ #:89+ #: This attribute can also be configured from the config with the `DEBUG`90+ #: configuration key. Defaults to `False`.91+ debug = ConfigAttribute('DEBUG')92+93+ #: The testing flask. Set this to `True` to enable the test mode of94+ #: Flask extensions (and in the future probably also Flask itself).95+ #: For example this might activate unittest helpers that have an96+ #: additional runtime cost which should not be enabled by default.97+ #:98+ #: This attribute can also be configured from the config with the99+ #: `TESTING` configuration key. Defaults to `False`.100+ testing = ConfigAttribute('TESTING')101+102+ #: If a secret key is set, cryptographic components can use this to103+ #: sign cookies and other things. Set this to a complex random value104+ #: when you want to use the secure cookie for instance.105+ #:106+ #: This attribute can also be configured from the config with the107+ #: `SECRET_KEY` configuration key. Defaults to `None`.108+ secret_key = ConfigAttribute('SECRET_KEY')109+110+ #: The secure cookie uses this for the name of the session cookie.111+ #:112+ #: This attribute can also be configured from the config with the113+ #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``114+ session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')115+116+ #: A :class:`~datetime.timedelta` which is used to set the expiration117+ #: date of a permanent session. The default is 31 days which makes a118+ #: permanent session survive for roughly one month.119+ #:120+ #: This attribute can also be configured from the config with the121+ #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to122+ #: ``timedelta(days=31)``123+ permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME')124+125+ #: Enable this if you want to use the X-Sendfile feature. Keep in126+ #: mind that the server has to support this. This only affects files127+ #: sent with the :func:`send_file` method.128+ #:129+ #: .. versionadded:: 0.2130+ #:131+ #: This attribute can also be configured from the config with the132+ #: `USE_X_SENDFILE` configuration key. Defaults to `False`.133+ use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')134+135+ #: The name of the logger to use. By default the logger name is the136+ #: package name passed to the constructor.137+ #:138+ #: .. versionadded:: 0.4139+ logger_name = ConfigAttribute('LOGGER_NAME')140+141+ #: The logging format used for the debug logger. This is only used when142+ #: the application is in debug mode, otherwise the attached logging143+ #: handler does the formatting.144+ #:145+ #: .. versionadded:: 0.3146+ debug_log_format = (147+ '-' * 80 + '\n' +148+ '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +149+ '%(message)s\n' +150+ '-' * 80151+ )152+153+ #: Options that are passed directly to the Jinja2 environment.154+ jinja_options = ImmutableDict(155+ autoescape=True,156+ extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']157+ )158+159+ #: Default configuration parameters.160+ default_config = ImmutableDict({161+ 'DEBUG': False,162+ 'TESTING': False,163+ 'SECRET_KEY': None,164+ 'SESSION_COOKIE_NAME': 'session',165+ 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),166+ 'USE_X_SENDFILE': False,167+ 'LOGGER_NAME': None,168+ 'SERVER_NAME': None169+ })170+171+ def __init__(self, import_name):172+ _PackageBoundObject.__init__(self, import_name)173+174+ #: The configuration dictionary as :class:`Config`. This behaves175+ #: exactly like a regular dictionary but supports additional methods176+ #: to load a config from files.177+ self.config = Config(self.root_path, self.default_config)178+179+ #: Prepare the deferred setup of the logger.180+ self._logger = None181+ self.logger_name = self.import_name182+183+ #: A dictionary of all view functions registered. The keys will184+ #: be function names which are also used to generate URLs and185+ #: the values are the function objects themselves.186+ #: to register a view function, use the :meth:`route` decorator.187+ self.view_functions = {}188+189+ #: A dictionary of all registered error handlers. The key is190+ #: be the error code as integer, the value the function that191+ #: should handle that error.192+ #: To register a error handler, use the :meth:`errorhandler`193+ #: decorator.194+ self.error_handlers = {}195+196+ #: A dictionary with lists of functions that should be called at the197+ #: beginning of the request. The key of the dictionary is the name of198+ #: the module this function is active for, `None` for all requests.199+ #: This can for example be used to open database connections or200+ #: getting hold of the currently logged in user. To register a201+ #: function here, use the :meth:`before_request` decorator.202+ self.before_request_funcs = {}203+204+ #: A dictionary with lists of functions that should be called after205+ #: each request. The key of the dictionary is the name of the module206+ #: this function is active for, `None` for all requests. This can for207+ #: example be used to open database connections or getting hold of the208+ #: currently logged in user. To register a function here, use the209+ #: :meth:`before_request` decorator.210+ self.after_request_funcs = {}211+212+ #: A dictionary with list of functions that are called without argument213+ #: to populate the template context. They key of the dictionary is the214+ #: name of the module this function is active for, `None` for all215+ #: requests. Each returns a dictionary that the template context is216+ #: updated with. To register a function here, use the217+ #: :meth:`context_processor` decorator.218+ self.template_context_processors = {219+ None: [_default_template_ctx_processor]220+ }221+222+ #: The :class:`~werkzeug.routing.Map` for this instance. You can use223+ #: this to change the routing converters after the class was created224+ #: but before any routes are connected. Example::225+ #:226+ #: from werkzeug import BaseConverter227+ #:228+ #: class ListConverter(BaseConverter):229+ #: def to_python(self, value):230+ #: return value.split(',')231+ #: def to_url(self, values):232+ #: return ','.join(BaseConverter.to_url(value)233+ #: for value in values)234+ #:235+ #: app = Flask(__name__)236+ #: app.url_map.converters['list'] = ListConverter237+ self.url_map = Map()238+239+ if self.static_path is not None:240+ self.add_url_rule(self.static_path + '/<filename>',241+ build_only=True, endpoint='static')242+ if get_pkg_resources() is not None:243+ target = (self.import_name, 'static')244+ else:245+ target = os.path.join(self.root_path, 'static')246+ self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {247+ self.static_path: target248+ })249+250+ #: The Jinja2 environment. It is created from the251+ #: :attr:`jinja_options` and the loader that is returned252+ #: by the :meth:`create_jinja_loader` function.253+ self.jinja_env = Environment(loader=self.create_jinja_loader(),254+ **self.jinja_options)255+ self.jinja_env.globals.update(256+ url_for=url_for,257+ get_flashed_messages=get_flashed_messages258+ )259+ self.jinja_env.filters['tojson'] = _tojson_filter260+261+ @property262+ def logger(self):263+ """A :class:`logging.Logger` object for this application. The264+ default configuration is to log to stderr if the application is265+ in debug mode. This logger can be used to (surprise) log messages.266+ Here some examples::267+268+ app.logger.debug('A value for debugging')269+ app.logger.warning('A warning ocurred (%d apples)', 42)270+ app.logger.error('An error occoured')271+272+ .. versionadded:: 0.3273+ """274+ if self._logger and self._logger.name == self.logger_name:275+ return self._logger276+ with _logger_lock:277+ if self._logger and self._logger.name == self.logger_name:278+ return self._logger279+ from logging import getLogger, StreamHandler, Formatter, \280+ Logger, DEBUG281+ class DebugLogger(Logger):282+ def getEffectiveLevel(x):283+ return DEBUG if self.debug else Logger.getEffectiveLevel(x)284+ class DebugHandler(StreamHandler):285+ def emit(x, record):286+ StreamHandler.emit(x, record) if self.debug else None287+ handler = DebugHandler()288+ handler.setLevel(DEBUG)289+ handler.setFormatter(Formatter(self.debug_log_format))290+ logger = getLogger(self.logger_name)291+ logger.__class__ = DebugLogger292+ logger.addHandler(handler)293+ self._logger = logger294+ return logger295+296+ def create_jinja_loader(self):297+ """Creates the Jinja loader. By default just a package loader for298+ the configured package is returned that looks up templates in the299+ `templates` folder. To add other loaders it's possible to300+ override this method.301+ """302+ if get_pkg_resources() is None:303+ return FileSystemLoader(os.path.join(self.root_path, 'templates'))304+ return PackageLoader(self.import_name)305+306+ def update_template_context(self, context):307+ """Update the template context with some commonly used variables.308+ This injects request, session and g into the template context.309+310+ :param context: the context as a dictionary that is updated in place311+ to add extra variables.312+ """313+ funcs = self.template_context_processors[None]314+ mod = _request_ctx_stack.top.request.module315+ if mod is not None and mod in self.template_context_processors:316+ funcs = chain(funcs, self.template_context_processors[mod])317+ for func in funcs:318+ context.update(func())319+320+ def run(self, host='127.0.0.1', port=5000, **options):321+ """Runs the application on a local development server. If the322+ :attr:`debug` flag is set the server will automatically reload323+ for code changes and show a debugger in case an exception happened.324+325+ .. admonition:: Keep in Mind326+327+ Flask will supress any server error with a generic error page328+ unless it is in debug mode. As such to enable just the329+ interactive debugger without the code reloading, you ahve to330+ invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.331+ Setting ``use_debugger`` to `True` without being in debug mode332+ won't catch any exceptions because there won't be any to333+ catch.334+335+ :param host: the hostname to listen on. set this to ``'0.0.0.0'``336+ to have the server available externally as well.337+ :param port: the port of the webserver338+ :param options: the options to be forwarded to the underlying339+ Werkzeug server. See :func:`werkzeug.run_simple`340+ for more information.341+ """342+ from werkzeug import run_simple343+ if 'debug' in options:344+ self.debug = options.pop('debug')345+ options.setdefault('use_reloader', self.debug)346+ options.setdefault('use_debugger', self.debug)347+ return run_simple(host, port, self, **options)348+349+ def test_client(self):350+ """Creates a test client for this application. For information351+ about unit testing head over to :ref:`testing`.352+353+ The test client can be used in a `with` block to defer the closing down354+ of the context until the end of the `with` block. This is useful if355+ you want to access the context locals for testing::356+357+ with app.test_client() as c:358+ rv = c.get('/?vodka=42')359+ assert request.args['vodka'] == '42'360+361+ .. versionchanged:: 0.4362+ added support for `with` block usage for the client.363+ """364+ from werkzeug import Client365+ class FlaskClient(Client):366+ preserve_context = context_preserved = False367+ def open(self, *args, **kwargs):368+ if self.context_preserved:369+ _request_ctx_stack.pop()370+ self.context_preserved = False371+ kwargs.setdefault('environ_overrides', {}) \372+ ['flask._preserve_context'] = self.preserve_context373+ old = _request_ctx_stack.top374+ try:375+ return Client.open(self, *args, **kwargs)376+ finally:377+ self.context_preserved = _request_ctx_stack.top is not old378+ def __enter__(self):379+ self.preserve_context = True380+ return self381+ def __exit__(self, exc_type, exc_value, tb):382+ self.preserve_context = False383+ if self.context_preserved:384+ _request_ctx_stack.pop()385+ return FlaskClient(self, self.response_class, use_cookies=True)386+387+ def open_session(self, request):388+ """Creates or opens a new session. Default implementation stores all389+ session data in a signed cookie. This requires that the390+ :attr:`secret_key` is set.391+392+ :param request: an instance of :attr:`request_class`.393+ """394+ key = self.secret_key395+ if key is not None:396+ return Session.load_cookie(request, self.session_cookie_name,397+ secret_key=key)398+399+ def save_session(self, session, response):400+ """Saves the session if it needs updates. For the default401+ implementation, check :meth:`open_session`.402+403+ :param session: the session to be saved (a404+ :class:`~werkzeug.contrib.securecookie.SecureCookie`405+ object)406+ :param response: an instance of :attr:`response_class`407+ """408+ expires = None409+ if session.permanent:410+ expires = datetime.utcnow() + self.permanent_session_lifetime411+ session.save_cookie(response, self.session_cookie_name,412+ expires=expires, httponly=True)413+414+ def register_module(self, module, **options):415+ """Registers a module with this application. The keyword argument416+ of this function are the same as the ones for the constructor of the417+ :class:`Module` class and will override the values of the module if418+ provided.419+ """420+ options.setdefault('url_prefix', module.url_prefix)421+ state = _ModuleSetupState(self, **options)422+ for func in module._register_events:423+ func(state)424+425+ def add_url_rule(self, rule, endpoint=None, view_func=None, **options):426+ """Connects a URL rule. Works exactly like the :meth:`route`427+ decorator. If a view_func is provided it will be registered with the428+ endpoint.429+430+ Basically this example::431+432+ @app.route('/')433+ def index():434+ pass435+436+ Is equivalent to the following::437+438+ def index():439+ pass440+ app.add_url_rule('/', 'index', index)441+442+ If the view_func is not provided you will need to connect the endpoint443+ to a view function like so::444+445+ app.view_functions['index'] = index446+447+ .. versionchanged:: 0.2448+ `view_func` parameter added.449+450+ :param rule: the URL rule as string451+ :param endpoint: the endpoint for the registered URL rule. Flask452+ itself assumes the name of the view function as453+ endpoint454+ :param view_func: the function to call when serving a request to the455+ provided endpoint456+ :param options: the options to be forwarded to the underlying457+ :class:`~werkzeug.routing.Rule` object458+ """459+ if endpoint is None:460+ assert view_func is not None, 'expected view func if endpoint ' \461+ 'is not provided.'462+ endpoint = view_func.__name__463+ options['endpoint'] = endpoint464+ options.setdefault('methods', ('GET',))465+ self.url_map.add(Rule(rule, **options))466+ if view_func is not None:467+ self.view_functions[endpoint] = view_func468+469+ def route(self, rule, **options):470+ """A decorator that is used to register a view function for a471+ given URL rule. Example::472+473+ @app.route('/')474+ def index():475+ return 'Hello World'476+477+ Variables parts in the route can be specified with angular478+ brackets (``/user/<username>``). By default a variable part479+ in the URL accepts any string without a slash however a different480+ converter can be specified as well by using ``<converter:name>``.481+482+ Variable parts are passed to the view function as keyword483+ arguments.484+485+ The following converters are possible:486+487+ =========== ===========================================488+ `int` accepts integers489+ `float` like `int` but for floating point values490+ `path` like the default but also accepts slashes491+ =========== ===========================================492+493+ Here some examples::494+495+ @app.route('/')496+ def index():497+ pass498+499+ @app.route('/<username>')500+ def show_user(username):501+ pass502+503+ @app.route('/post/<int:post_id>')504+ def show_post(post_id):505+ pass506+507+ An important detail to keep in mind is how Flask deals with trailing508+ slashes. The idea is to keep each URL unique so the following rules509+ apply:510+511+ 1. If a rule ends with a slash and is requested without a slash512+ by the user, the user is automatically redirected to the same513+ page with a trailing slash attached.514+ 2. If a rule does not end with a trailing slash and the user request515+ the page with a trailing slash, a 404 not found is raised.516+517+ This is consistent with how web servers deal with static files. This518+ also makes it possible to use relative link targets safely.519+520+ The :meth:`route` decorator accepts a couple of other arguments521+ as well:522+523+ :param rule: the URL rule as string524+ :param methods: a list of methods this rule should be limited525+ to (``GET``, ``POST`` etc.). By default a rule526+ just listens for ``GET`` (and implicitly ``HEAD``).527+ :param subdomain: specifies the rule for the subdoain in case528+ subdomain matching is in use.529+ :param strict_slashes: can be used to disable the strict slashes530+ setting for this rule. See above.531+ :param options: other options to be forwarded to the underlying532+ :class:`~werkzeug.routing.Rule` object.533+ """534+ def decorator(f):535+ self.add_url_rule(rule, None, f, **options)536+ return f537+ return decorator538+539+ def errorhandler(self, code):540+ """A decorator that is used to register a function give a given541+ error code. Example::542+543+ @app.errorhandler(404)544+ def page_not_found(error):545+ return 'This page does not exist', 404546+547+ You can also register a function as error handler without using548+ the :meth:`errorhandler` decorator. The following example is549+ equivalent to the one above::550+551+ def page_not_found(error):552+ return 'This page does not exist', 404553+ app.error_handlers[404] = page_not_found554+555+ :param code: the code as integer for the handler556+ """557+ def decorator(f):558+ self.error_handlers[code] = f559+ return f560+ return decorator561+562+ def template_filter(self, name=None):563+ """A decorator that is used to register custom template filter.564+ You can specify a name for the filter, otherwise the function565+ name will be used. Example::566+567+ @app.template_filter()568+ def reverse(s):569+ return s[::-1]570+571+ :param name: the optional name of the filter, otherwise the572+ function name will be used.573+ """574+ def decorator(f):575+ self.jinja_env.filters[name or f.__name__] = f576+ return f577+ return decorator578+579+ def before_request(self, f):580+ """Registers a function to run before each request."""581+ self.before_request_funcs.setdefault(None, []).append(f)582+ return f583+584+ def after_request(self, f):585+ """Register a function to be run after each request."""586+ self.after_request_funcs.setdefault(None, []).append(f)587+ return f588+589+ def context_processor(self, f):590+ """Registers a template context processor function."""591+ self.template_context_processors[None].append(f)592+ return f593+594+ def handle_http_exception(self, e):595+ """Handles an HTTP exception. By default this will invoke the596+ registered error handlers and fall back to returning the597+ exception as response.598+599+ .. versionadded: 0.3600+ """601+ handler = self.error_handlers.get(e.code)602+ if handler is None:603+ return e604+ return handler(e)605+606+ def handle_exception(self, e):607+ """Default exception handling that kicks in when an exception608+ occours that is not catched. In debug mode the exception will609+ be re-raised immediately, otherwise it is logged and the handler610+ for a 500 internal server error is used. If no such handler611+ exists, a default 500 internal server error message is displayed.612+613+ .. versionadded: 0.3614+ """615+ handler = self.error_handlers.get(500)616+ if self.debug:617+ raise618+ self.logger.exception('Exception on %s [%s]' % (619+ request.path,620+ request.method621+ ))622+ if handler is None:623+ return InternalServerError()624+ return handler(e)625+626+ def dispatch_request(self):627+ """Does the request dispatching. Matches the URL and returns the628+ return value of the view or error handler. This does not have to629+ be a response object. In order to convert the return value to a630+ proper response object, call :func:`make_response`.631+ """632+ req = _request_ctx_stack.top.request633+ try:634+ if req.routing_exception is not None:635+ raise req.routing_exception636+ return self.view_functions[req.endpoint](**req.view_args)637+ except HTTPException, e:638+ return self.handle_http_exception(e)639+640+ def make_response(self, rv):641+ """Converts the return value from a view function to a real642+ response object that is an instance of :attr:`response_class`.643+644+ The following types are allowed for `rv`:645+646+ .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|647+648+ ======================= ===========================================649+ :attr:`response_class` the object is returned unchanged650+ :class:`str` a response object is created with the651+ string as body652+ :class:`unicode` a response object is created with the653+ string encoded to utf-8 as body654+ :class:`tuple` the response object is created with the655+ contents of the tuple as arguments656+ a WSGI function the function is called as WSGI application657+ and buffered as response object658+ ======================= ===========================================659+660+ :param rv: the return value from the view function661+ """662+ if rv is None:663+ raise ValueError('View function did not return a response')664+ if isinstance(rv, self.response_class):665+ return rv666+ if isinstance(rv, basestring):667+ return self.response_class(rv)668+ if isinstance(rv, tuple):669+ return self.response_class(*rv)670+ return self.response_class.force_type(rv, request.environ)671+672+ def preprocess_request(self):673+ """Called before the actual request dispatching and will674+ call every as :meth:`before_request` decorated function.675+ If any of these function returns a value it's handled as676+ if it was the return value from the view and further677+ request handling is stopped.678+ """679+ funcs = self.before_request_funcs.get(None, ())680+ mod = request.module681+ if mod and mod in self.before_request_funcs:682+ funcs = chain(funcs, self.before_request_funcs[mod])683+ for func in funcs:684+ rv = func()685+ if rv is not None:686+ return rv687+688+ def process_response(self, response):689+ """Can be overridden in order to modify the response object690+ before it's sent to the WSGI server. By default this will691+ call all the :meth:`after_request` decorated functions.692+693+ :param response: a :attr:`response_class` object.694+ :return: a new response object or the same, has to be an695+ instance of :attr:`response_class`.696+ """697+ ctx = _request_ctx_stack.top698+ mod = ctx.request.module699+ if not isinstance(ctx.session, _NullSession):700+ self.save_session(ctx.session, response)701+ funcs = ()702+ if mod and mod in self.after_request_funcs:703+ funcs = chain(funcs, self.after_request_funcs[mod])704+ if None in self.after_request_funcs:705+ funcs = chain(funcs, self.after_request_funcs[None])706+ for handler in funcs:707+ response = handler(response)708+ return response709+710+ def wsgi_app(self, environ, start_response):711+ """The actual WSGI application. This is not implemented in712+ `__call__` so that middlewares can be applied without losing a713+ reference to the class. So instead of doing this::714+715+ app = MyMiddleware(app)716+717+ It's a better idea to do this instead::718+719+ app.wsgi_app = MyMiddleware(app.wsgi_app)720+721+ Then you still have the original application object around and722+ can continue to call methods on it.723+724+ .. versionchanged:: 0.4725+ The :meth:`after_request` functions are now called even if an726+ error handler took over request processing. This ensures that727+ even if an exception happens database have the chance to728+ properly close the connection.729+730+ :param environ: a WSGI environment731+ :param start_response: a callable accepting a status code,732+ a list of headers and an optional733+ exception context to start the response734+ """735+ with self.request_context(environ):736+ try:737+ rv = self.preprocess_request()738+ if rv is None:739+ rv = self.dispatch_request()740+ response = self.make_response(rv)741+ except Exception, e:742+ response = self.make_response(self.handle_exception(e))743+ try:744+ response = self.process_response(response)745+ except Exception, e:746+ response = self.make_response(self.handle_exception(e))747+ return response(environ, start_response)748+749+ def request_context(self, environ):750+ """Creates a request context from the given environment and binds751+ it to the current context. This must be used in combination with752+ the `with` statement because the request is only bound to the753+ current context for the duration of the `with` block.754+755+ Example usage::756+757+ with app.request_context(environ):758+ do_something_with(request)759+760+ The object returned can also be used without the `with` statement761+ which is useful for working in the shell. The example above is762+ doing exactly the same as this code::763+764+ ctx = app.request_context(environ)765+ ctx.push()766+ try:767+ do_something_with(request)768+ finally:769+ ctx.pop()770+771+ The big advantage of this approach is that you can use it without772+ the try/finally statement in a shell for interactive testing:773+774+ >>> ctx = app.test_request_context()775+ >>> ctx.bind()776+ >>> request.path777+ u'/'778+ >>> ctx.unbind()779+780+ .. versionchanged:: 0.3781+ Added support for non-with statement usage and `with` statement782+ is now passed the ctx object.783+784+ :param environ: a WSGI environment785+ """786+ return _RequestContext(self, environ)787+788+ def test_request_context(self, *args, **kwargs):789+ """Creates a WSGI environment from the given values (see790+ :func:`werkzeug.create_environ` for more information, this791+ function accepts the same arguments).792+ """793+ return self.request_context(create_environ(*args, **kwargs))794+795+ def __call__(self, environ, start_response):796+ """Shortcut for :attr:`wsgi_app`."""797+ return self.wsgi_app(environ, start_response)798+added:flask/conf.py+139 added
1+import os2+import sys3+4+from werkzeug import import_string5+6+7+class ConfigAttribute(object):8+ """Makes an attribute forward to the config"""9+10+ def __init__(self, name):11+ self.__name__ = name12+13+ def __get__(self, obj, type=None):14+ if obj is None:15+ return self16+ return obj.config[self.__name__]17+18+ def __set__(self, obj, value):19+ obj.config[self.__name__] = value20+21+22+class Config(dict):23+ """Works exactly like a dict but provides ways to fill it from files24+ or special dictionaries. There are two common patterns to populate the25+ config.26+27+ Either you can fill the config from a config file::28+29+ app.config.from_pyfile('yourconfig.cfg')30+31+ Or alternatively you can define the configuration options in the32+ module that calls :meth:`from_object` or provide an import path to33+ a module that should be loaded. It is also possible to tell it to34+ use the same module and with that provide the configuration values35+ just before the call::36+37+ DEBUG = True38+ SECRET_KEY = 'development key'39+ app.config.from_object(__name__)40+41+ In both cases (loading from any Python file or loading from modules),42+ only uppercase keys are added to the config. This makes it possible to use43+ lowercase values in the config file for temporary values that are not added44+ to the config or to define the config keys in the same file that implements45+ the application.46+47+ Probably the most interesting way to load configurations is from an48+ environment variable pointing to a file::49+50+ app.config.from_envvar('YOURAPPLICATION_SETTINGS')51+52+ In this case before launching the application you have to set this53+ environment variable to the file you want to use. On Linux and OS X54+ use the export statement::55+56+ export YOURAPPLICATION_SETTINGS='/path/to/config/file'57+58+ On windows use `set` instead.59+60+ :param root_path: path to which files are read relative from. When the61+ config object is created by the application, this is62+ the application's :attr:`~flask.Flask.root_path`.63+ :param defaults: an optional dictionary of default values64+ """65+66+ def __init__(self, root_path, defaults=None):67+ dict.__init__(self, defaults or {})68+ self.root_path = root_path69+70+ def from_envvar(self, variable_name, silent=False):71+ """Loads a configuration from an environment variable pointing to72+ a configuration file. This basically is just a shortcut with nicer73+ error messages for this line of code::74+75+ app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])76+77+ :param variable_name: name of the environment variable78+ :param silent: set to `True` if you want silent failing for missing79+ files.80+ :return: bool. `True` if able to load config, `False` otherwise.81+ """82+ rv = os.environ.get(variable_name)83+ if not rv:84+ if silent:85+ return False86+ raise RuntimeError('The environment variable %r is not set '87+ 'and as such configuration could not be '88+ 'loaded. Set this variable and make it '89+ 'point to a configuration file' %90+ variable_name)91+ self.from_pyfile(rv)92+ return True93+94+ def from_pyfile(self, filename):95+ """Updates the values in the config from a Python file. This function96+ behaves as if the file was imported as module with the97+ :meth:`from_object` function.98+99+ :param filename: the filename of the config. This can either be an100+ absolute filename or a filename relative to the101+ root path.102+ """103+ filename = os.path.join(self.root_path, filename)104+ d = type(sys)('config')105+ d.__file__ = filename106+ execfile(filename, d.__dict__)107+ self.from_object(d)108+109+ def from_object(self, obj):110+ """Updates the values from the given object. An object can be of one111+ of the following two types:112+113+ - a string: in this case the object with that name will be imported114+ - an actual object reference: that object is used directly115+116+ Objects are usually either modules or classes.117+118+ Just the uppercase variables in that object are stored in the config119+ after lowercasing. Example usage::120+121+ app.config.from_object('yourapplication.default_config')122+ from yourapplication import default_config123+ app.config.from_object(default_config)124+125+ You should not use this function to load the actual configuration but126+ rather configuration defaults. The actual config should be loaded127+ with :meth:`from_pyfile` and ideally from a location not within the128+ package because the package might be installed system wide.129+130+ :param obj: an import name or object131+ """132+ if isinstance(obj, basestring):133+ obj = import_string(obj)134+ for key in dir(obj):135+ if key.isupper():136+ self[key] = getattr(obj, key)137+138+ def __repr__(self):139+ return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))added:flask/ctx.py+62 added
1+from werkzeug.exceptions import HTTPException2+3+from flask.wrappers import _RequestGlobals4+from flask.globals import _request_ctx_stack5+from flask.session import _NullSession6+7+8+class _RequestContext(object):9+ """The request context contains all request relevant information. It is10+ created at the beginning of the request and pushed to the11+ `_request_ctx_stack` and removed at the end of it. It will create the12+ URL adapter and request object for the WSGI environment provided.13+ """14+15+ def __init__(self, app, environ):16+ self.app = app17+ self.url_adapter = app.url_map.bind_to_environ(environ,18+ server_name=app.config['SERVER_NAME'])19+ self.request = app.request_class(environ)20+ self.session = app.open_session(self.request)21+ if self.session is None:22+ self.session = _NullSession()23+ self.g = _RequestGlobals()24+ self.flashes = None25+26+ try:27+ self.request.endpoint, self.request.view_args = \28+ self.url_adapter.match()29+ except HTTPException, e:30+ self.request.routing_exception = e31+32+ def push(self):33+ """Binds the request context."""34+ _request_ctx_stack.push(self)35+36+ def pop(self):37+ """Pops the request context."""38+ _request_ctx_stack.pop()39+40+ def __enter__(self):41+ self.push()42+ return self43+44+ def __exit__(self, exc_type, exc_value, tb):45+ # do not pop the request stack if we are in debug mode and an46+ # exception happened. This will allow the debugger to still47+ # access the request object in the interactive shell. Furthermore48+ # the context can be force kept alive for the test client.49+ if not self.request.environ.get('flask._preserve_context') and \50+ (tb is None or not self.app.debug):51+ self.pop()52+ 53+def _default_template_ctx_processor():54+ """Default template context processor. Injects `request`,55+ `session` and `g`.56+ """57+ reqctx = _request_ctx_stack.top58+ return dict(59+ request=reqctx.request,60+ session=reqctx.session,61+ g=reqctx.g62+ )added:flask/globals.py+8 added
1+from werkzeug import LocalStack, LocalProxy2+3+# context locals4+_request_ctx_stack = LocalStack()5+current_app = LocalProxy(lambda: _request_ctx_stack.top.app)6+request = LocalProxy(lambda: _request_ctx_stack.top.request)7+session = LocalProxy(lambda: _request_ctx_stack.top.session)8+g = LocalProxy(lambda: _request_ctx_stack.top.g)added:flask/helpers.py+328 added
1+import os2+import sys3+import mimetypes4+5+# try to load the best simplejson implementation available. If JSON6+# is not installed, we add a failing class.7+json_available = True8+try:9+ import simplejson as json10+except ImportError:11+ try:12+ import json13+ except ImportError:14+ json_available = False15+ 16+from werkzeug import Headers, wrap_file17+18+from flask.globals import session, _request_ctx_stack, current_app, request19+from flask.wrappers import Response20+21+ 22+def _assert_have_json():23+ """Helper function that fails if JSON is unavailable."""24+ if not json_available:25+ raise RuntimeError('simplejson not installed')26+27+# figure out if simplejson escapes slashes. This behaviour was changed28+# from one version to another without reason.29+if not json_available or '\\/' not in json.dumps('/'):30+31+ def _tojson_filter(*args, **kwargs):32+ if __debug__:33+ _assert_have_json()34+ return json.dumps(*args, **kwargs).replace('/', '\\/')35+else:36+ _tojson_filter = json.dumps37+38+def jsonify(*args, **kwargs):39+ """Creates a :class:`~flask.Response` with the JSON representation of40+ the given arguments with an `application/json` mimetype. The arguments41+ to this function are the same as to the :class:`dict` constructor.42+43+ Example usage::44+45+ @app.route('/_get_current_user')46+ def get_current_user():47+ return jsonify(username=g.user.username,48+ email=g.user.email,49+ id=g.user.id)50+51+ This will send a JSON response like this to the browser::52+53+ {54+ "username": "admin",55+ "email": "admin@localhost",56+ "id": 4257+ }58+59+ This requires Python 2.6 or an installed version of simplejson. For60+ security reasons only objects are supported toplevel. For more61+ information about this, have a look at :ref:`json-security`.62+63+ .. versionadded:: 0.264+ """65+ if __debug__:66+ _assert_have_json()67+ return current_app.response_class(json.dumps(dict(*args, **kwargs),68+ indent=None if request.is_xhr else 2), mimetype='application/json')69+ 70+def get_pkg_resources():71+ """Use pkg_resource if that works, otherwise fall back to cwd. The72+ current working directory is generally not reliable with the notable73+ exception of google appengine.74+ """75+ try:76+ import pkg_resources77+ pkg_resources.resource_stream78+ except (ImportError, AttributeError):79+ return80+ return pkg_resources81+82+83+def url_for(endpoint, **values):84+ """Generates a URL to the given endpoint with the method provided.85+ The endpoint is relative to the active module if modules are in use.86+87+ Here some examples:88+89+ ==================== ======================= =============================90+ Active Module Target Endpoint Target Function91+ ==================== ======================= =============================92+ `None` ``'index'`` `index` of the application93+ `None` ``'.index'`` `index` of the application94+ ``'admin'`` ``'index'`` `index` of the `admin` module95+ any ``'.index'`` `index` of the application96+ any ``'admin.index'`` `index` of the `admin` module97+ ==================== ======================= =============================98+99+ Variable arguments that are unknown to the target endpoint are appended100+ to the generated URL as query arguments.101+102+ For more information, head over to the :ref:`Quickstart <url-building>`.103+104+ :param endpoint: the endpoint of the URL (name of the function)105+ :param values: the variable arguments of the URL rule106+ :param _external: if set to `True`, an absolute URL is generated.107+ """108+ ctx = _request_ctx_stack.top109+ if '.' not in endpoint:110+ mod = ctx.request.module111+ if mod is not None:112+ endpoint = mod + '.' + endpoint113+ elif endpoint.startswith('.'):114+ endpoint = endpoint[1:]115+ external = values.pop('_external', False)116+ return ctx.url_adapter.build(endpoint, values, force_external=external)117+118+119+def get_template_attribute(template_name, attribute):120+ """Loads a macro (or variable) a template exports. This can be used to121+ invoke a macro from within Python code. If you for example have a122+ template named `_cider.html` with the following contents:123+124+ .. sourcecode:: html+jinja125+126+ {% macro hello(name) %}Hello {{ name }}!{% endmacro %}127+128+ You can access this from Python code like this::129+130+ hello = get_template_attribute('_cider.html', 'hello')131+ return hello('World')132+133+ .. versionadded:: 0.2134+135+ :param template_name: the name of the template136+ :param attribute: the name of the variable of macro to acccess137+ """138+ return getattr(current_app.jinja_env.get_template(template_name).module,139+ attribute)140+141+142+def flash(message, category='message'):143+ """Flashes a message to the next request. In order to remove the144+ flashed message from the session and to display it to the user,145+ the template has to call :func:`get_flashed_messages`.146+147+ .. versionchanged: 0.3148+ `category` parameter added.149+150+ :param message: the message to be flashed.151+ :param category: the category for the message. The following values152+ are recommended: ``'message'`` for any kind of message,153+ ``'error'`` for errors, ``'info'`` for information154+ messages and ``'warning'`` for warnings. However any155+ kind of string can be used as category.156+ """157+ session.setdefault('_flashes', []).append((category, message))158+159+160+def get_flashed_messages(with_categories=False):161+ """Pulls all flashed messages from the session and returns them.162+ Further calls in the same request to the function will return163+ the same messages. By default just the messages are returned,164+ but when `with_categories` is set to `True`, the return value will165+ be a list of tuples in the form ``(category, message)`` instead.166+167+ Example usage:168+169+ .. sourcecode:: html+jinja170+171+ {% for category, msg in get_flashed_messages(with_categories=true) %}172+ <p class=flash-{{ category }}>{{ msg }}173+ {% endfor %}174+175+ .. versionchanged:: 0.3176+ `with_categories` parameter added.177+178+ :param with_categories: set to `True` to also receive categories.179+ """180+ flashes = _request_ctx_stack.top.flashes181+ if flashes is None:182+ _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])183+ if not with_categories:184+ return [x[1] for x in flashes]185+ return flashes186+187+188+def send_file(filename_or_fp, mimetype=None, as_attachment=False,189+ attachment_filename=None):190+ """Sends the contents of a file to the client. This will use the191+ most efficient method available and configured. By default it will192+ try to use the WSGI server's file_wrapper support. Alternatively193+ you can set the application's :attr:`~Flask.use_x_sendfile` attribute194+ to ``True`` to directly emit an `X-Sendfile` header. This however195+ requires support of the underlying webserver for `X-Sendfile`.196+197+ By default it will try to guess the mimetype for you, but you can198+ also explicitly provide one. For extra security you probably want199+ to sent certain files as attachment (HTML for instance).200+201+ Please never pass filenames to this function from user sources without202+ checking them first. Something like this is usually sufficient to203+ avoid security problems::204+205+ if '..' in filename or filename.startswith('/'):206+ abort(404)207+208+ .. versionadded:: 0.2209+210+ :param filename_or_fp: the filename of the file to send. This is211+ relative to the :attr:`~Flask.root_path` if a212+ relative path is specified.213+ Alternatively a file object might be provided214+ in which case `X-Sendfile` might not work and215+ fall back to the traditional method.216+ :param mimetype: the mimetype of the file if provided, otherwise217+ auto detection happens.218+ :param as_attachment: set to `True` if you want to send this file with219+ a ``Content-Disposition: attachment`` header.220+ :param attachment_filename: the filename for the attachment if it221+ differs from the file's filename.222+ """223+ if isinstance(filename_or_fp, basestring):224+ filename = filename_or_fp225+ file = None226+ else:227+ file = filename_or_fp228+ filename = getattr(file, 'name', None)229+ if filename is not None:230+ filename = os.path.join(current_app.root_path, filename)231+ if mimetype is None and (filename or attachment_filename):232+ mimetype = mimetypes.guess_type(filename or attachment_filename)[0]233+ if mimetype is None:234+ mimetype = 'application/octet-stream'235+236+ headers = Headers()237+ if as_attachment:238+ if attachment_filename is None:239+ if filename is None:240+ raise TypeError('filename unavailable, required for '241+ 'sending as attachment')242+ attachment_filename = os.path.basename(filename)243+ headers.add('Content-Disposition', 'attachment',244+ filename=attachment_filename)245+246+ if current_app.use_x_sendfile and filename:247+ if file is not None:248+ file.close()249+ headers['X-Sendfile'] = filename250+ data = None251+ else:252+ if file is None:253+ file = open(filename, 'rb')254+ data = wrap_file(request.environ, file)255+256+ return Response(data, mimetype=mimetype, headers=headers,257+ direct_passthrough=True)258+259+260+def render_template(template_name, **context):261+ """Renders a template from the template folder with the given262+ context.263+264+ :param template_name: the name of the template to be rendered265+ :param context: the variables that should be available in the266+ context of the template.267+ """268+ current_app.update_template_context(context)269+ return current_app.jinja_env.get_template(template_name).render(context)270+271+272+def render_template_string(source, **context):273+ """Renders a template from the given template source string274+ with the given context.275+276+ :param template_name: the sourcecode of the template to be277+ rendered278+ :param context: the variables that should be available in the279+ context of the template.280+ """281+ current_app.update_template_context(context)282+ return current_app.jinja_env.from_string(source).render(context)283+284+285+def _get_package_path(name):286+ """Returns the path to a package or cwd if that cannot be found."""287+ try:288+ return os.path.abspath(os.path.dirname(sys.modules[name].__file__))289+ except (KeyError, AttributeError):290+ return os.getcwd()291+292+293+class _PackageBoundObject(object):294+295+ def __init__(self, import_name):296+ #: The name of the package or module. Do not change this once297+ #: it was set by the constructor.298+ self.import_name = import_name299+300+ #: Where is the app root located?301+ self.root_path = _get_package_path(self.import_name)302+303+ def open_resource(self, resource):304+ """Opens a resource from the application's resource folder. To see305+ how this works, consider the following folder structure::306+307+ /myapplication.py308+ /schemal.sql309+ /static310+ /style.css311+ /templates312+ /layout.html313+ /index.html314+315+ If you want to open the `schema.sql` file you would do the316+ following::317+318+ with app.open_resource('schema.sql') as f:319+ contents = f.read()320+ do_something_with(contents)321+322+ :param resource: the name of the resource. To access resources within323+ subfolders use forward slashes as separator.324+ """325+ pkg_resources = get_pkg_resources()326+ if pkg_resources is None:327+ return open(os.path.join(self.root_path, resource), 'rb')328+ return pkg_resources.resource_stream(self.import_name, resource)added:flask/module.py+152 added
1+from flask.helpers import _PackageBoundObject2+3+4+class _ModuleSetupState(object):5+6+ def __init__(self, app, url_prefix=None):7+ self.app = app8+ self.url_prefix = url_prefix9+10+11+class Module(_PackageBoundObject):12+ """Container object that enables pluggable applications. A module can13+ be used to organize larger applications. They represent blueprints that,14+ in combination with a :class:`Flask` object are used to create a large15+ application.16+17+ A module is like an application bound to an `import_name`. Multiple18+ modules can share the same import names, but in that case a `name` has19+ to be provided to keep them apart. If different import names are used,20+ the rightmost part of the import name is used as name.21+22+ Here an example structure for a larger appliation::23+24+ /myapplication25+ /__init__.py26+ /views27+ /__init__.py28+ /admin.py29+ /frontend.py30+31+ The `myapplication/__init__.py` can look like this::32+33+ from flask import Flask34+ from myapplication.views.admin import admin35+ from myapplication.views.frontend import frontend36+37+ app = Flask(__name__)38+ app.register_module(admin, url_prefix='/admin')39+ app.register_module(frontend)40+41+ And here an example view module (`myapplication/views/admin.py`)::42+43+ from flask import Module44+45+ admin = Module(__name__)46+47+ @admin.route('/')48+ def index():49+ pass50+51+ @admin.route('/login')52+ def login():53+ pass54+55+ For a gentle introduction into modules, checkout the56+ :ref:`working-with-modules` section.57+ """58+59+ def __init__(self, import_name, name=None, url_prefix=None):60+ if name is None:61+ assert '.' in import_name, 'name required if package name ' \62+ 'does not point to a submodule'63+ name = import_name.rsplit('.', 1)[1]64+ _PackageBoundObject.__init__(self, import_name)65+ self.name = name66+ self.url_prefix = url_prefix67+ self._register_events = []68+69+ def route(self, rule, **options):70+ """Like :meth:`Flask.route` but for a module. The endpoint for the71+ :func:`url_for` function is prefixed with the name of the module.72+ """73+ def decorator(f):74+ self.add_url_rule(rule, f.__name__, f, **options)75+ return f76+ return decorator77+78+ def add_url_rule(self, rule, endpoint, view_func=None, **options):79+ """Like :meth:`Flask.add_url_rule` but for a module. The endpoint for80+ the :func:`url_for` function is prefixed with the name of the module.81+ """82+ def register_rule(state):83+ the_rule = rule84+ if state.url_prefix:85+ the_rule = state.url_prefix + rule86+ state.app.add_url_rule(the_rule, '%s.%s' % (self.name, endpoint),87+ view_func, **options)88+ self._record(register_rule)89+90+ def before_request(self, f):91+ """Like :meth:`Flask.before_request` but for a module. This function92+ is only executed before each request that is handled by a function of93+ that module.94+ """95+ self._record(lambda s: s.app.before_request_funcs96+ .setdefault(self.name, []).append(f))97+ return f98+99+ def before_app_request(self, f):100+ """Like :meth:`Flask.before_request`. Such a function is executed101+ before each request, even if outside of a module.102+ """103+ self._record(lambda s: s.app.before_request_funcs104+ .setdefault(None, []).append(f))105+ return f106+107+ def after_request(self, f):108+ """Like :meth:`Flask.after_request` but for a module. This function109+ is only executed after each request that is handled by a function of110+ that module.111+ """112+ self._record(lambda s: s.app.after_request_funcs113+ .setdefault(self.name, []).append(f))114+ return f115+116+ def after_app_request(self, f):117+ """Like :meth:`Flask.after_request` but for a module. Such a function118+ is executed after each request, even if outside of the module.119+ """120+ self._record(lambda s: s.app.after_request_funcs121+ .setdefault(None, []).append(f))122+ return f123+124+ def context_processor(self, f):125+ """Like :meth:`Flask.context_processor` but for a module. This126+ function is only executed for requests handled by a module.127+ """128+ self._record(lambda s: s.app.template_context_processors129+ .setdefault(self.name, []).append(f))130+ return f131+132+ def app_context_processor(self, f):133+ """Like :meth:`Flask.context_processor` but for a module. Such a134+ function is executed each request, even if outside of the module.135+ """136+ self._record(lambda s: s.app.template_context_processors137+ .setdefault(None, []).append(f))138+ return f139+140+ def app_errorhandler(self, code):141+ """Like :meth:`Flask.errorhandler` but for a module. This142+ handler is used for all requests, even if outside of the module.143+144+ .. versionadded:: 0.4145+ """146+ def decorator(f):147+ self._record(lambda s: s.app.errorhandler(code)(f))148+ return f149+ return decorator150+151+ def _record(self, func):152+ self._register_events.append(func)added:flask/session.py+31 added
1+from werkzeug.contrib.securecookie import SecureCookie2+3+4+class Session(SecureCookie):5+ """Expands the session with support for switching between permanent6+ and non-permanent sessions.7+ """8+9+ def _get_permanent(self):10+ return self.get('_permanent', False)11+12+ def _set_permanent(self, value):13+ self['_permanent'] = bool(value)14+15+ permanent = property(_get_permanent, _set_permanent)16+ del _get_permanent, _set_permanent17+18+19+class _NullSession(Session):20+ """Class used to generate nicer error messages if sessions are not21+ available. Will still allow read-only access to the empty session22+ but fail on setting.23+ """24+25+ def _fail(self, *args, **kwargs):26+ raise RuntimeError('the session is unavailable because no secret '27+ 'key was set. Set the secret_key on the '28+ 'application to something unique and secret')29+ __setitem__ = __delitem__ = clear = pop = popitem = \30+ update = setdefault = _fail31+ del _failadded:flask/wrappers.py+64 added
1+from werkzeug import Request as RequestBase, Response as ResponseBase, \2+ cached_property3+4+from helpers import json5+6+7+class Request(RequestBase):8+ """The request object used by default in flask. Remembers the9+ matched endpoint and view arguments.10+11+ It is what ends up as :class:`~flask.request`. If you want to replace12+ the request object used you can subclass this and set13+ :attr:`~flask.Flask.request_class` to your subclass.14+ """15+16+ #: the endpoint that matched the request. This in combination with17+ #: :attr:`view_args` can be used to reconstruct the same or a18+ #: modified URL. If an exception happened when matching, this will19+ #: be `None`.20+ endpoint = None21+22+ #: a dict of view arguments that matched the request. If an exception23+ #: happened when matching, this will be `None`.24+ view_args = None25+26+ #: if matching the URL failed, this is the exception that will be27+ #: raised / was raised as part of the request handling. This is28+ #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or29+ #: something similar.30+ routing_exception = None31+32+ @property33+ def module(self):34+ """The name of the current module"""35+ if self.endpoint and '.' in self.endpoint:36+ return self.endpoint.rsplit('.', 1)[0]37+38+ @cached_property39+ def json(self):40+ """If the mimetype is `application/json` this will contain the41+ parsed JSON data.42+ """43+ if __debug__:44+ from flask.helpers import _assert_have_json45+ _assert_have_json()46+ if self.mimetype == 'application/json':47+ return json.loads(self.data)48+49+50+class Response(ResponseBase):51+ """The response object that is used by default in flask. Works like the52+ response object from Werkzeug but is set to have a HTML mimetype by53+ default. Quite often you don't have to create this object yourself because54+ :meth:`~flask.Flask.make_response` will take care of that for you.55+56+ If you want to replace the response object used you can subclass this and57+ set :attr:`~flask.Flask.response_class` to your subclass.58+ """59+ default_mimetype = 'text/html'60+61+62+class _RequestGlobals(object):63+ pass64+modified:tests/flask_tests.py+3 added-3 removed
19 unmodified lines20 from contextlib import contextmanager21 from datetime import datetime22 from werkzeug import parse_date, parse_options_header23 from cStringIO import StringIO24+from flask.helpers import json25 25-26 example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')27 sys.path.append(os.path.join(example_path, 'flaskr'))28 sys.path.append(os.path.join(example_path, 'minitwit'))29 378 unmodified lines408 c = app.test_client()409 for url in '/kw', '/dict':410 rv = c.get(url)411 assert rv.mimetype == 'application/json'412- assert flask.json.loads(rv.data) == d412+ assert json.loads(rv.data) == d413 414 def test_json_attr(self):415 app = flask.Flask(__name__)416 @app.route('/add', methods=['POST'])417 def add():418 return unicode(flask.request.json['a'] + flask.request.json['b'])419 c = app.test_client()420- rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),420+ rv = c.post('/add', data=json.dumps({'a': 1, 'b': 2}),421 content_type='application/json')422 assert rv.data == '3'423 424 def test_template_escaping(self):474 unmodified linesdeleted:flask.py-1599 removed
1-# -*- coding: utf-8 -*-2-"""3- flask4- ~~~~~5-6- A microframework based on Werkzeug. It's extensively documented7- and follows best practice patterns.8-9- :copyright: (c) 2010 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-from __future__ import with_statement13-import os14-import sys15-import mimetypes16-from datetime import datetime, timedelta17-18-# this is a workaround for appengine. Do not remove this import19-import werkzeug20-21-from itertools import chain22-from threading import Lock23-from jinja2 import Environment, PackageLoader, FileSystemLoader24-from werkzeug import Request as RequestBase, Response as ResponseBase, \25- LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \26- ImmutableDict, cached_property, wrap_file, Headers, \27- import_string28-from werkzeug.routing import Map, Rule29-from werkzeug.exceptions import HTTPException, InternalServerError30-from werkzeug.contrib.securecookie import SecureCookie31-32-# try to load the best simplejson implementation available. If JSON33-# is not installed, we add a failing class.34-json_available = True35-try:36- import simplejson as json37-except ImportError:38- try:39- import json40- except ImportError:41- json_available = False42-43-# utilities we import from Werkzeug and Jinja2 that are unused44-# in the module but are exported as public interface.45-from werkzeug import abort, redirect46-from jinja2 import Markup, escape47-48-# use pkg_resource if that works, otherwise fall back to cwd. The49-# current working directory is generally not reliable with the notable50-# exception of google appengine.51-try:52- import pkg_resources53- pkg_resources.resource_stream54-except (ImportError, AttributeError):55- pkg_resources = None56-57-# a lock used for logger initialization58-_logger_lock = Lock()59-60-61-class Request(RequestBase):62- """The request object used by default in flask. Remembers the63- matched endpoint and view arguments.64-65- It is what ends up as :class:`~flask.request`. If you want to replace66- the request object used you can subclass this and set67- :attr:`~flask.Flask.request_class` to your subclass.68- """69-70- #: the endpoint that matched the request. This in combination with71- #: :attr:`view_args` can be used to reconstruct the same or a72- #: modified URL. If an exception happened when matching, this will73- #: be `None`.74- endpoint = None75-76- #: a dict of view arguments that matched the request. If an exception77- #: happened when matching, this will be `None`.78- view_args = None79-80- #: if matching the URL failed, this is the exception that will be81- #: raised / was raised as part of the request handling. This is82- #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or83- #: something similar.84- routing_exception = None85-86- @property87- def module(self):88- """The name of the current module"""89- if self.endpoint and '.' in self.endpoint:90- return self.endpoint.rsplit('.', 1)[0]91-92- @cached_property93- def json(self):94- """If the mimetype is `application/json` this will contain the95- parsed JSON data.96- """97- if __debug__:98- _assert_have_json()99- if self.mimetype == 'application/json':100- return json.loads(self.data)101-102-103-class Response(ResponseBase):104- """The response object that is used by default in flask. Works like the105- response object from Werkzeug but is set to have a HTML mimetype by106- default. Quite often you don't have to create this object yourself because107- :meth:`~flask.Flask.make_response` will take care of that for you.108-109- If you want to replace the response object used you can subclass this and110- set :attr:`~flask.Flask.response_class` to your subclass.111- """112- default_mimetype = 'text/html'113-114-115-class _RequestGlobals(object):116- pass117-118-119-class Session(SecureCookie):120- """Expands the session with support for switching between permanent121- and non-permanent sessions.122- """123-124- def _get_permanent(self):125- return self.get('_permanent', False)126-127- def _set_permanent(self, value):128- self['_permanent'] = bool(value)129-130- permanent = property(_get_permanent, _set_permanent)131- del _get_permanent, _set_permanent132-133-134-class _NullSession(Session):135- """Class used to generate nicer error messages if sessions are not136- available. Will still allow read-only access to the empty session137- but fail on setting.138- """139-140- def _fail(self, *args, **kwargs):141- raise RuntimeError('the session is unavailable because no secret '142- 'key was set. Set the secret_key on the '143- 'application to something unique and secret')144- __setitem__ = __delitem__ = clear = pop = popitem = \145- update = setdefault = _fail146- del _fail147-148-149-class _RequestContext(object):150- """The request context contains all request relevant information. It is151- created at the beginning of the request and pushed to the152- `_request_ctx_stack` and removed at the end of it. It will create the153- URL adapter and request object for the WSGI environment provided.154- """155-156- def __init__(self, app, environ):157- self.app = app158- self.url_adapter = app.url_map.bind_to_environ(environ,159- server_name=app.config['SERVER_NAME'])160- self.request = app.request_class(environ)161- self.session = app.open_session(self.request)162- if self.session is None:163- self.session = _NullSession()164- self.g = _RequestGlobals()165- self.flashes = None166-167- try:168- self.request.endpoint, self.request.view_args = \169- self.url_adapter.match()170- except HTTPException, e:171- self.request.routing_exception = e172-173- def push(self):174- """Binds the request context."""175- _request_ctx_stack.push(self)176-177- def pop(self):178- """Pops the request context."""179- _request_ctx_stack.pop()180-181- def __enter__(self):182- self.push()183- return self184-185- def __exit__(self, exc_type, exc_value, tb):186- # do not pop the request stack if we are in debug mode and an187- # exception happened. This will allow the debugger to still188- # access the request object in the interactive shell. Furthermore189- # the context can be force kept alive for the test client.190- if not self.request.environ.get('flask._preserve_context') and \191- (tb is None or not self.app.debug):192- self.pop()193-194-195-def url_for(endpoint, **values):196- """Generates a URL to the given endpoint with the method provided.197- The endpoint is relative to the active module if modules are in use.198-199- Here some examples:200-201- ==================== ======================= =============================202- Active Module Target Endpoint Target Function203- ==================== ======================= =============================204- `None` ``'index'`` `index` of the application205- `None` ``'.index'`` `index` of the application206- ``'admin'`` ``'index'`` `index` of the `admin` module207- any ``'.index'`` `index` of the application208- any ``'admin.index'`` `index` of the `admin` module209- ==================== ======================= =============================210-211- Variable arguments that are unknown to the target endpoint are appended212- to the generated URL as query arguments.213-214- For more information, head over to the :ref:`Quickstart <url-building>`.215-216- :param endpoint: the endpoint of the URL (name of the function)217- :param values: the variable arguments of the URL rule218- :param _external: if set to `True`, an absolute URL is generated.219- """220- ctx = _request_ctx_stack.top221- if '.' not in endpoint:222- mod = ctx.request.module223- if mod is not None:224- endpoint = mod + '.' + endpoint225- elif endpoint.startswith('.'):226- endpoint = endpoint[1:]227- external = values.pop('_external', False)228- return ctx.url_adapter.build(endpoint, values, force_external=external)229-230-231-def get_template_attribute(template_name, attribute):232- """Loads a macro (or variable) a template exports. This can be used to233- invoke a macro from within Python code. If you for example have a234- template named `_cider.html` with the following contents:235-236- .. sourcecode:: html+jinja237-238- {% macro hello(name) %}Hello {{ name }}!{% endmacro %}239-240- You can access this from Python code like this::241-242- hello = get_template_attribute('_cider.html', 'hello')243- return hello('World')244-245- .. versionadded:: 0.2246-247- :param template_name: the name of the template248- :param attribute: the name of the variable of macro to acccess249- """250- return getattr(current_app.jinja_env.get_template(template_name).module,251- attribute)252-253-254-def flash(message, category='message'):255- """Flashes a message to the next request. In order to remove the256- flashed message from the session and to display it to the user,257- the template has to call :func:`get_flashed_messages`.258-259- .. versionchanged: 0.3260- `category` parameter added.261-262- :param message: the message to be flashed.263- :param category: the category for the message. The following values264- are recommended: ``'message'`` for any kind of message,265- ``'error'`` for errors, ``'info'`` for information266- messages and ``'warning'`` for warnings. However any267- kind of string can be used as category.268- """269- session.setdefault('_flashes', []).append((category, message))270-271-272-def get_flashed_messages(with_categories=False):273- """Pulls all flashed messages from the session and returns them.274- Further calls in the same request to the function will return275- the same messages. By default just the messages are returned,276- but when `with_categories` is set to `True`, the return value will277- be a list of tuples in the form ``(category, message)`` instead.278-279- Example usage:280-281- .. sourcecode:: html+jinja282-283- {% for category, msg in get_flashed_messages(with_categories=true) %}284- <p class=flash-{{ category }}>{{ msg }}285- {% endfor %}286-287- .. versionchanged:: 0.3288- `with_categories` parameter added.289-290- :param with_categories: set to `True` to also receive categories.291- """292- flashes = _request_ctx_stack.top.flashes293- if flashes is None:294- _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])295- if not with_categories:296- return [x[1] for x in flashes]297- return flashes298-299-300-def jsonify(*args, **kwargs):301- """Creates a :class:`~flask.Response` with the JSON representation of302- the given arguments with an `application/json` mimetype. The arguments303- to this function are the same as to the :class:`dict` constructor.304-305- Example usage::306-307- @app.route('/_get_current_user')308- def get_current_user():309- return jsonify(username=g.user.username,310- email=g.user.email,311- id=g.user.id)312-313- This will send a JSON response like this to the browser::314-315- {316- "username": "admin",317- "email": "admin@localhost",318- "id": 42319- }320-321- This requires Python 2.6 or an installed version of simplejson. For322- security reasons only objects are supported toplevel. For more323- information about this, have a look at :ref:`json-security`.324-325- .. versionadded:: 0.2326- """327- if __debug__:328- _assert_have_json()329- return current_app.response_class(json.dumps(dict(*args, **kwargs),330- indent=None if request.is_xhr else 2), mimetype='application/json')331-332-333-def send_file(filename_or_fp, mimetype=None, as_attachment=False,334- attachment_filename=None):335- """Sends the contents of a file to the client. This will use the336- most efficient method available and configured. By default it will337- try to use the WSGI server's file_wrapper support. Alternatively338- you can set the application's :attr:`~Flask.use_x_sendfile` attribute339- to ``True`` to directly emit an `X-Sendfile` header. This however340- requires support of the underlying webserver for `X-Sendfile`.341-342- By default it will try to guess the mimetype for you, but you can343- also explicitly provide one. For extra security you probably want344- to sent certain files as attachment (HTML for instance).345-346- Please never pass filenames to this function from user sources without347- checking them first. Something like this is usually sufficient to348- avoid security problems::349-350- if '..' in filename or filename.startswith('/'):351- abort(404)352-353- .. versionadded:: 0.2354-355- :param filename_or_fp: the filename of the file to send. This is356- relative to the :attr:`~Flask.root_path` if a357- relative path is specified.358- Alternatively a file object might be provided359- in which case `X-Sendfile` might not work and360- fall back to the traditional method.361- :param mimetype: the mimetype of the file if provided, otherwise362- auto detection happens.363- :param as_attachment: set to `True` if you want to send this file with364- a ``Content-Disposition: attachment`` header.365- :param attachment_filename: the filename for the attachment if it366- differs from the file's filename.367- """368- if isinstance(filename_or_fp, basestring):369- filename = filename_or_fp370- file = None371- else:372- file = filename_or_fp373- filename = getattr(file, 'name', None)374- if filename is not None:375- filename = os.path.join(current_app.root_path, filename)376- if mimetype is None and (filename or attachment_filename):377- mimetype = mimetypes.guess_type(filename or attachment_filename)[0]378- if mimetype is None:379- mimetype = 'application/octet-stream'380-381- headers = Headers()382- if as_attachment:383- if attachment_filename is None:384- if filename is None:385- raise TypeError('filename unavailable, required for '386- 'sending as attachment')387- attachment_filename = os.path.basename(filename)388- headers.add('Content-Disposition', 'attachment',389- filename=attachment_filename)390-391- if current_app.use_x_sendfile and filename:392- if file is not None:393- file.close()394- headers['X-Sendfile'] = filename395- data = None396- else:397- if file is None:398- file = open(filename, 'rb')399- data = wrap_file(request.environ, file)400-401- return Response(data, mimetype=mimetype, headers=headers,402- direct_passthrough=True)403-404-405-def render_template(template_name, **context):406- """Renders a template from the template folder with the given407- context.408-409- :param template_name: the name of the template to be rendered410- :param context: the variables that should be available in the411- context of the template.412- """413- current_app.update_template_context(context)414- return current_app.jinja_env.get_template(template_name).render(context)415-416-417-def render_template_string(source, **context):418- """Renders a template from the given template source string419- with the given context.420-421- :param template_name: the sourcecode of the template to be422- rendered423- :param context: the variables that should be available in the424- context of the template.425- """426- current_app.update_template_context(context)427- return current_app.jinja_env.from_string(source).render(context)428-429-430-def _default_template_ctx_processor():431- """Default template context processor. Injects `request`,432- `session` and `g`.433- """434- reqctx = _request_ctx_stack.top435- return dict(436- request=reqctx.request,437- session=reqctx.session,438- g=reqctx.g439- )440-441-442-def _assert_have_json():443- """Helper function that fails if JSON is unavailable."""444- if not json_available:445- raise RuntimeError('simplejson not installed')446-447-448-def _get_package_path(name):449- """Returns the path to a package or cwd if that cannot be found."""450- try:451- return os.path.abspath(os.path.dirname(sys.modules[name].__file__))452- except (KeyError, AttributeError):453- return os.getcwd()454-455-456-# figure out if simplejson escapes slashes. This behaviour was changed457-# from one version to another without reason.458-if not json_available or '\\/' not in json.dumps('/'):459-460- def _tojson_filter(*args, **kwargs):461- if __debug__:462- _assert_have_json()463- return json.dumps(*args, **kwargs).replace('/', '\\/')464-else:465- _tojson_filter = json.dumps466-467-468-class _PackageBoundObject(object):469-470- def __init__(self, import_name):471- #: The name of the package or module. Do not change this once472- #: it was set by the constructor.473- self.import_name = import_name474-475- #: Where is the app root located?476- self.root_path = _get_package_path(self.import_name)477-478- def open_resource(self, resource):479- """Opens a resource from the application's resource folder. To see480- how this works, consider the following folder structure::481-482- /myapplication.py483- /schemal.sql484- /static485- /style.css486- /templates487- /layout.html488- /index.html489-490- If you want to open the `schema.sql` file you would do the491- following::492-493- with app.open_resource('schema.sql') as f:494- contents = f.read()495- do_something_with(contents)496-497- :param resource: the name of the resource. To access resources within498- subfolders use forward slashes as separator.499- """500- if pkg_resources is None:501- return open(os.path.join(self.root_path, resource), 'rb')502- return pkg_resources.resource_stream(self.import_name, resource)503-504-505-class _ModuleSetupState(object):506-507- def __init__(self, app, url_prefix=None):508- self.app = app509- self.url_prefix = url_prefix510-511-512-class Module(_PackageBoundObject):513- """Container object that enables pluggable applications. A module can514- be used to organize larger applications. They represent blueprints that,515- in combination with a :class:`Flask` object are used to create a large516- application.517-518- A module is like an application bound to an `import_name`. Multiple519- modules can share the same import names, but in that case a `name` has520- to be provided to keep them apart. If different import names are used,521- the rightmost part of the import name is used as name.522-523- Here an example structure for a larger appliation::524-525- /myapplication526- /__init__.py527- /views528- /__init__.py529- /admin.py530- /frontend.py531-532- The `myapplication/__init__.py` can look like this::533-534- from flask import Flask535- from myapplication.views.admin import admin536- from myapplication.views.frontend import frontend537-538- app = Flask(__name__)539- app.register_module(admin, url_prefix='/admin')540- app.register_module(frontend)541-542- And here an example view module (`myapplication/views/admin.py`)::543-544- from flask import Module545-546- admin = Module(__name__)547-548- @admin.route('/')549- def index():550- pass551-552- @admin.route('/login')553- def login():554- pass555-556- For a gentle introduction into modules, checkout the557- :ref:`working-with-modules` section.558- """559-560- def __init__(self, import_name, name=None, url_prefix=None):561- if name is None:562- assert '.' in import_name, 'name required if package name ' \563- 'does not point to a submodule'564- name = import_name.rsplit('.', 1)[1]565- _PackageBoundObject.__init__(self, import_name)566- self.name = name567- self.url_prefix = url_prefix568- self._register_events = []569-570- def route(self, rule, **options):571- """Like :meth:`Flask.route` but for a module. The endpoint for the572- :func:`url_for` function is prefixed with the name of the module.573- """574- def decorator(f):575- self.add_url_rule(rule, f.__name__, f, **options)576- return f577- return decorator578-579- def add_url_rule(self, rule, endpoint, view_func=None, **options):580- """Like :meth:`Flask.add_url_rule` but for a module. The endpoint for581- the :func:`url_for` function is prefixed with the name of the module.582- """583- def register_rule(state):584- the_rule = rule585- if state.url_prefix:586- the_rule = state.url_prefix + rule587- state.app.add_url_rule(the_rule, '%s.%s' % (self.name, endpoint),588- view_func, **options)589- self._record(register_rule)590-591- def before_request(self, f):592- """Like :meth:`Flask.before_request` but for a module. This function593- is only executed before each request that is handled by a function of594- that module.595- """596- self._record(lambda s: s.app.before_request_funcs597- .setdefault(self.name, []).append(f))598- return f599-600- def before_app_request(self, f):601- """Like :meth:`Flask.before_request`. Such a function is executed602- before each request, even if outside of a module.603- """604- self._record(lambda s: s.app.before_request_funcs605- .setdefault(None, []).append(f))606- return f607-608- def after_request(self, f):609- """Like :meth:`Flask.after_request` but for a module. This function610- is only executed after each request that is handled by a function of611- that module.612- """613- self._record(lambda s: s.app.after_request_funcs614- .setdefault(self.name, []).append(f))615- return f616-617- def after_app_request(self, f):618- """Like :meth:`Flask.after_request` but for a module. Such a function619- is executed after each request, even if outside of the module.620- """621- self._record(lambda s: s.app.after_request_funcs622- .setdefault(None, []).append(f))623- return f624-625- def context_processor(self, f):626- """Like :meth:`Flask.context_processor` but for a module. This627- function is only executed for requests handled by a module.628- """629- self._record(lambda s: s.app.template_context_processors630- .setdefault(self.name, []).append(f))631- return f632-633- def app_context_processor(self, f):634- """Like :meth:`Flask.context_processor` but for a module. Such a635- function is executed each request, even if outside of the module.636- """637- self._record(lambda s: s.app.template_context_processors638- .setdefault(None, []).append(f))639- return f640-641- def app_errorhandler(self, code):642- """Like :meth:`Flask.errorhandler` but for a module. This643- handler is used for all requests, even if outside of the module.644-645- .. versionadded:: 0.4646- """647- def decorator(f):648- self._record(lambda s: s.app.errorhandler(code)(f))649- return f650- return decorator651-652- def _record(self, func):653- self._register_events.append(func)654-655-656-class ConfigAttribute(object):657- """Makes an attribute forward to the config"""658-659- def __init__(self, name):660- self.__name__ = name661-662- def __get__(self, obj, type=None):663- if obj is None:664- return self665- return obj.config[self.__name__]666-667- def __set__(self, obj, value):668- obj.config[self.__name__] = value669-670-671-class Config(dict):672- """Works exactly like a dict but provides ways to fill it from files673- or special dictionaries. There are two common patterns to populate the674- config.675-676- Either you can fill the config from a config file::677-678- app.config.from_pyfile('yourconfig.cfg')679-680- Or alternatively you can define the configuration options in the681- module that calls :meth:`from_object` or provide an import path to682- a module that should be loaded. It is also possible to tell it to683- use the same module and with that provide the configuration values684- just before the call::685-686- DEBUG = True687- SECRET_KEY = 'development key'688- app.config.from_object(__name__)689-690- In both cases (loading from any Python file or loading from modules),691- only uppercase keys are added to the config. This makes it possible to use692- lowercase values in the config file for temporary values that are not added693- to the config or to define the config keys in the same file that implements694- the application.695-696- Probably the most interesting way to load configurations is from an697- environment variable pointing to a file::698-699- app.config.from_envvar('YOURAPPLICATION_SETTINGS')700-701- In this case before launching the application you have to set this702- environment variable to the file you want to use. On Linux and OS X703- use the export statement::704-705- export YOURAPPLICATION_SETTINGS='/path/to/config/file'706-707- On windows use `set` instead.708-709- :param root_path: path to which files are read relative from. When the710- config object is created by the application, this is711- the application's :attr:`~flask.Flask.root_path`.712- :param defaults: an optional dictionary of default values713- """714-715- def __init__(self, root_path, defaults=None):716- dict.__init__(self, defaults or {})717- self.root_path = root_path718-719- def from_envvar(self, variable_name, silent=False):720- """Loads a configuration from an environment variable pointing to721- a configuration file. This basically is just a shortcut with nicer722- error messages for this line of code::723-724- app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])725-726- :param variable_name: name of the environment variable727- :param silent: set to `True` if you want silent failing for missing728- files.729- :return: bool. `True` if able to load config, `False` otherwise.730- """731- rv = os.environ.get(variable_name)732- if not rv:733- if silent:734- return False735- raise RuntimeError('The environment variable %r is not set '736- 'and as such configuration could not be '737- 'loaded. Set this variable and make it '738- 'point to a configuration file' %739- variable_name)740- self.from_pyfile(rv)741- return True742-743- def from_pyfile(self, filename):744- """Updates the values in the config from a Python file. This function745- behaves as if the file was imported as module with the746- :meth:`from_object` function.747-748- :param filename: the filename of the config. This can either be an749- absolute filename or a filename relative to the750- root path.751- """752- filename = os.path.join(self.root_path, filename)753- d = type(sys)('config')754- d.__file__ = filename755- execfile(filename, d.__dict__)756- self.from_object(d)757-758- def from_object(self, obj):759- """Updates the values from the given object. An object can be of one760- of the following two types:761-762- - a string: in this case the object with that name will be imported763- - an actual object reference: that object is used directly764-765- Objects are usually either modules or classes.766-767- Just the uppercase variables in that object are stored in the config768- after lowercasing. Example usage::769-770- app.config.from_object('yourapplication.default_config')771- from yourapplication import default_config772- app.config.from_object(default_config)773-774- You should not use this function to load the actual configuration but775- rather configuration defaults. The actual config should be loaded776- with :meth:`from_pyfile` and ideally from a location not within the777- package because the package might be installed system wide.778-779- :param obj: an import name or object780- """781- if isinstance(obj, basestring):782- obj = import_string(obj)783- for key in dir(obj):784- if key.isupper():785- self[key] = getattr(obj, key)786-787- def __repr__(self):788- return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))789-790-791-def _select_autoescape(filename):792- """Returns `True` if autoescaping should be active for the given793- template name.794- """795- if filename is None:796- return False797- return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))798-799-800-class Flask(_PackageBoundObject):801- """The flask object implements a WSGI application and acts as the central802- object. It is passed the name of the module or package of the803- application. Once it is created it will act as a central registry for804- the view functions, the URL rules, template configuration and much more.805-806- The name of the package is used to resolve resources from inside the807- package or the folder the module is contained in depending on if the808- package parameter resolves to an actual python package (a folder with809- an `__init__.py` file inside) or a standard module (just a `.py` file).810-811- For more information about resource loading, see :func:`open_resource`.812-813- Usually you create a :class:`Flask` instance in your main module or814- in the `__init__.py` file of your package like this::815-816- from flask import Flask817- app = Flask(__name__)818-819- .. admonition:: About the First Parameter820-821- The idea of the first parameter is to give Flask an idea what822- belongs to your application. This name is used to find resources823- on the file system, can be used by extensions to improve debugging824- information and a lot more.825-826- So it's important what you provide there. If you are using a single827- module, `__name__` is always the correct value. If you however are828- using a package, it's usually recommended to hardcode the name of829- your package there.830-831- For example if your application is defined in `yourapplication/app.py`832- you should create it with one of the two versions below::833-834- app = Flask('yourapplication')835- app = Flask(__name__.split('.')[0])836-837- Why is that? The application will work even with `__name__`, thanks838- to how resources are looked up. However it will make debugging more839- painful. Certain extensions can make assumptions based on the840- import name of your application. For example the Flask-SQLAlchemy841- extension will look for the code in your application that triggered842- an SQL query in debug mode. If the import name is not properly set843- up, that debugging information is lost. (For example it would only844- pick up SQL queries in `yourapplicaiton.app` and not845- `yourapplication.views.frontend`)846- """847-848- #: The class that is used for request objects. See :class:`~flask.Request`849- #: for more information.850- request_class = Request851-852- #: The class that is used for response objects. See853- #: :class:`~flask.Response` for more information.854- response_class = Response855-856- #: Path for the static files. If you don't want to use static files857- #: you can set this value to `None` in which case no URL rule is added858- #: and the development server will no longer serve any static files.859- static_path = '/static'860-861- #: The debug flag. Set this to `True` to enable debugging of the862- #: application. In debug mode the debugger will kick in when an unhandled863- #: exception ocurrs and the integrated server will automatically reload864- #: the application if changes in the code are detected.865- #:866- #: This attribute can also be configured from the config with the `DEBUG`867- #: configuration key. Defaults to `False`.868- debug = ConfigAttribute('DEBUG')869-870- #: The testing flask. Set this to `True` to enable the test mode of871- #: Flask extensions (and in the future probably also Flask itself).872- #: For example this might activate unittest helpers that have an873- #: additional runtime cost which should not be enabled by default.874- #:875- #: This attribute can also be configured from the config with the876- #: `TESTING` configuration key. Defaults to `False`.877- testing = ConfigAttribute('TESTING')878-879- #: If a secret key is set, cryptographic components can use this to880- #: sign cookies and other things. Set this to a complex random value881- #: when you want to use the secure cookie for instance.882- #:883- #: This attribute can also be configured from the config with the884- #: `SECRET_KEY` configuration key. Defaults to `None`.885- secret_key = ConfigAttribute('SECRET_KEY')886-887- #: The secure cookie uses this for the name of the session cookie.888- #:889- #: This attribute can also be configured from the config with the890- #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``891- session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')892-893- #: A :class:`~datetime.timedelta` which is used to set the expiration894- #: date of a permanent session. The default is 31 days which makes a895- #: permanent session survive for roughly one month.896- #:897- #: This attribute can also be configured from the config with the898- #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to899- #: ``timedelta(days=31)``900- permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME')901-902- #: Enable this if you want to use the X-Sendfile feature. Keep in903- #: mind that the server has to support this. This only affects files904- #: sent with the :func:`send_file` method.905- #:906- #: .. versionadded:: 0.2907- #:908- #: This attribute can also be configured from the config with the909- #: `USE_X_SENDFILE` configuration key. Defaults to `False`.910- use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')911-912- #: The name of the logger to use. By default the logger name is the913- #: package name passed to the constructor.914- #:915- #: .. versionadded:: 0.4916- logger_name = ConfigAttribute('LOGGER_NAME')917-918- #: The logging format used for the debug logger. This is only used when919- #: the application is in debug mode, otherwise the attached logging920- #: handler does the formatting.921- #:922- #: .. versionadded:: 0.3923- debug_log_format = (924- '-' * 80 + '\n' +925- '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +926- '%(message)s\n' +927- '-' * 80928- )929-930- #: Options that are passed directly to the Jinja2 environment.931- jinja_options = ImmutableDict(932- autoescape=_select_autoescape,933- extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']934- )935-936- #: Default configuration parameters.937- default_config = ImmutableDict({938- 'DEBUG': False,939- 'TESTING': False,940- 'SECRET_KEY': None,941- 'SESSION_COOKIE_NAME': 'session',942- 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),943- 'USE_X_SENDFILE': False,944- 'LOGGER_NAME': None,945- 'SERVER_NAME': None946- })947-948- def __init__(self, import_name):949- _PackageBoundObject.__init__(self, import_name)950-951- #: The configuration dictionary as :class:`Config`. This behaves952- #: exactly like a regular dictionary but supports additional methods953- #: to load a config from files.954- self.config = Config(self.root_path, self.default_config)955-956- #: Prepare the deferred setup of the logger.957- self._logger = None958- self.logger_name = self.import_name959-960- #: A dictionary of all view functions registered. The keys will961- #: be function names which are also used to generate URLs and962- #: the values are the function objects themselves.963- #: to register a view function, use the :meth:`route` decorator.964- self.view_functions = {}965-966- #: A dictionary of all registered error handlers. The key is967- #: be the error code as integer, the value the function that968- #: should handle that error.969- #: To register a error handler, use the :meth:`errorhandler`970- #: decorator.971- self.error_handlers = {}972-973- #: A dictionary with lists of functions that should be called at the974- #: beginning of the request. The key of the dictionary is the name of975- #: the module this function is active for, `None` for all requests.976- #: This can for example be used to open database connections or977- #: getting hold of the currently logged in user. To register a978- #: function here, use the :meth:`before_request` decorator.979- self.before_request_funcs = {}980-981- #: A dictionary with lists of functions that should be called after982- #: each request. The key of the dictionary is the name of the module983- #: this function is active for, `None` for all requests. This can for984- #: example be used to open database connections or getting hold of the985- #: currently logged in user. To register a function here, use the986- #: :meth:`before_request` decorator.987- self.after_request_funcs = {}988-989- #: A dictionary with list of functions that are called without argument990- #: to populate the template context. They key of the dictionary is the991- #: name of the module this function is active for, `None` for all992- #: requests. Each returns a dictionary that the template context is993- #: updated with. To register a function here, use the994- #: :meth:`context_processor` decorator.995- self.template_context_processors = {996- None: [_default_template_ctx_processor]997- }998-999- #: The :class:`~werkzeug.routing.Map` for this instance. You can use1000- #: this to change the routing converters after the class was created1001- #: but before any routes are connected. Example::1002- #:1003- #: from werkzeug import BaseConverter1004- #:1005- #: class ListConverter(BaseConverter):1006- #: def to_python(self, value):1007- #: return value.split(',')1008- #: def to_url(self, values):1009- #: return ','.join(BaseConverter.to_url(value)1010- #: for value in values)1011- #:1012- #: app = Flask(__name__)1013- #: app.url_map.converters['list'] = ListConverter1014- self.url_map = Map()1015-1016- if self.static_path is not None:1017- self.add_url_rule(self.static_path + '/<filename>',1018- build_only=True, endpoint='static')1019- if pkg_resources is not None:1020- target = (self.import_name, 'static')1021- else:1022- target = os.path.join(self.root_path, 'static')1023- self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {1024- self.static_path: target1025- })1026-1027- #: The Jinja2 environment. It is created from the1028- #: :attr:`jinja_options` and the loader that is returned1029- #: by the :meth:`create_jinja_loader` function.1030- self.jinja_env = self.create_jinja_environment()1031- self.init_jinja_globals()1032-1033- @property1034- def logger(self):1035- """A :class:`logging.Logger` object for this application. The1036- default configuration is to log to stderr if the application is1037- in debug mode. This logger can be used to (surprise) log messages.1038- Here some examples::1039-1040- app.logger.debug('A value for debugging')1041- app.logger.warning('A warning ocurred (%d apples)', 42)1042- app.logger.error('An error occoured')1043-1044- .. versionadded:: 0.31045- """1046- if self._logger and self._logger.name == self.logger_name:1047- return self._logger1048- with _logger_lock:1049- if self._logger and self._logger.name == self.logger_name:1050- return self._logger1051- from logging import getLogger, StreamHandler, Formatter, \1052- Logger, DEBUG1053- class DebugLogger(Logger):1054- def getEffectiveLevel(x):1055- return DEBUG if self.debug else Logger.getEffectiveLevel(x)1056- class DebugHandler(StreamHandler):1057- def emit(x, record):1058- StreamHandler.emit(x, record) if self.debug else None1059- handler = DebugHandler()1060- handler.setLevel(DEBUG)1061- handler.setFormatter(Formatter(self.debug_log_format))1062- logger = getLogger(self.logger_name)1063- logger.__class__ = DebugLogger1064- logger.addHandler(handler)1065- self._logger = logger1066- return logger1067-1068- def create_jinja_environment(self):1069- """Creates the Jinja2 environment based on :attr:`jinja_options`1070- and :meth:`create_jinja_loader`.1071-1072- .. versionadded:: 0.51073- """1074- return Environment(loader=self.create_jinja_loader(),1075- **self.jinja_options)1076-1077- def create_jinja_loader(self):1078- """Creates the Jinja loader. By default just a package loader for1079- the configured package is returned that looks up templates in the1080- `templates` folder. To add other loaders it's possible to1081- override this method.1082- """1083- if pkg_resources is None:1084- return FileSystemLoader(os.path.join(self.root_path, 'templates'))1085- return PackageLoader(self.import_name)1086-1087- def init_jinja_globals(self):1088- """Callde directly after the environment was created to inject1089- some defaults (like `url_for`, `get_flashed_messages` and the1090- `tojson` filter.1091-1092- .. versionadded:: 0.51093- """1094- self.jinja_env.globals.update(1095- url_for=url_for,1096- get_flashed_messages=get_flashed_messages1097- )1098- self.jinja_env.filters['tojson'] = _tojson_filter1099-1100- def update_template_context(self, context):1101- """Update the template context with some commonly used variables.1102- This injects request, session and g into the template context.1103-1104- :param context: the context as a dictionary that is updated in place1105- to add extra variables.1106- """1107- funcs = self.template_context_processors[None]1108- mod = _request_ctx_stack.top.request.module1109- if mod is not None and mod in self.template_context_processors:1110- funcs = chain(funcs, self.template_context_processors[mod])1111- for func in funcs:1112- context.update(func())1113-1114- def run(self, host='127.0.0.1', port=5000, **options):1115- """Runs the application on a local development server. If the1116- :attr:`debug` flag is set the server will automatically reload1117- for code changes and show a debugger in case an exception happened.1118-1119- .. admonition:: Keep in Mind1120-1121- Flask will supress any server error with a generic error page1122- unless it is in debug mode. As such to enable just the1123- interactive debugger without the code reloading, you ahve to1124- invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.1125- Setting ``use_debugger`` to `True` without being in debug mode1126- won't catch any exceptions because there won't be any to1127- catch.1128-1129- :param host: the hostname to listen on. set this to ``'0.0.0.0'``1130- to have the server available externally as well.1131- :param port: the port of the webserver1132- :param options: the options to be forwarded to the underlying1133- Werkzeug server. See :func:`werkzeug.run_simple`1134- for more information.1135- """1136- from werkzeug import run_simple1137- if 'debug' in options:1138- self.debug = options.pop('debug')1139- options.setdefault('use_reloader', self.debug)1140- options.setdefault('use_debugger', self.debug)1141- return run_simple(host, port, self, **options)1142-1143- def test_client(self):1144- """Creates a test client for this application. For information1145- about unit testing head over to :ref:`testing`.1146-1147- The test client can be used in a `with` block to defer the closing down1148- of the context until the end of the `with` block. This is useful if1149- you want to access the context locals for testing::1150-1151- with app.test_client() as c:1152- rv = c.get('/?vodka=42')1153- assert request.args['vodka'] == '42'1154-1155- .. versionchanged:: 0.41156- added support for `with` block usage for the client.1157- """1158- from werkzeug import Client1159- class FlaskClient(Client):1160- preserve_context = context_preserved = False1161- def open(self, *args, **kwargs):1162- if self.context_preserved:1163- _request_ctx_stack.pop()1164- self.context_preserved = False1165- kwargs.setdefault('environ_overrides', {}) \1166- ['flask._preserve_context'] = self.preserve_context1167- old = _request_ctx_stack.top1168- try:1169- return Client.open(self, *args, **kwargs)1170- finally:1171- self.context_preserved = _request_ctx_stack.top is not old1172- def __enter__(self):1173- self.preserve_context = True1174- return self1175- def __exit__(self, exc_type, exc_value, tb):1176- self.preserve_context = False1177- if self.context_preserved:1178- _request_ctx_stack.pop()1179- return FlaskClient(self, self.response_class, use_cookies=True)1180-1181- def open_session(self, request):1182- """Creates or opens a new session. Default implementation stores all1183- session data in a signed cookie. This requires that the1184- :attr:`secret_key` is set.1185-1186- :param request: an instance of :attr:`request_class`.1187- """1188- key = self.secret_key1189- if key is not None:1190- return Session.load_cookie(request, self.session_cookie_name,1191- secret_key=key)1192-1193- def save_session(self, session, response):1194- """Saves the session if it needs updates. For the default1195- implementation, check :meth:`open_session`.1196-1197- :param session: the session to be saved (a1198- :class:`~werkzeug.contrib.securecookie.SecureCookie`1199- object)1200- :param response: an instance of :attr:`response_class`1201- """1202- expires = None1203- if session.permanent:1204- expires = datetime.utcnow() + self.permanent_session_lifetime1205- session.save_cookie(response, self.session_cookie_name,1206- expires=expires, httponly=True)1207-1208- def register_module(self, module, **options):1209- """Registers a module with this application. The keyword argument1210- of this function are the same as the ones for the constructor of the1211- :class:`Module` class and will override the values of the module if1212- provided.1213- """1214- options.setdefault('url_prefix', module.url_prefix)1215- state = _ModuleSetupState(self, **options)1216- for func in module._register_events:1217- func(state)1218-1219- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):1220- """Connects a URL rule. Works exactly like the :meth:`route`1221- decorator. If a view_func is provided it will be registered with the1222- endpoint.1223-1224- Basically this example::1225-1226- @app.route('/')1227- def index():1228- pass1229-1230- Is equivalent to the following::1231-1232- def index():1233- pass1234- app.add_url_rule('/', 'index', index)1235-1236- If the view_func is not provided you will need to connect the endpoint1237- to a view function like so::1238-1239- app.view_functions['index'] = index1240-1241- .. versionchanged:: 0.21242- `view_func` parameter added.1243-1244- :param rule: the URL rule as string1245- :param endpoint: the endpoint for the registered URL rule. Flask1246- itself assumes the name of the view function as1247- endpoint1248- :param view_func: the function to call when serving a request to the1249- provided endpoint1250- :param options: the options to be forwarded to the underlying1251- :class:`~werkzeug.routing.Rule` object1252- """1253- if endpoint is None:1254- assert view_func is not None, 'expected view func if endpoint ' \1255- 'is not provided.'1256- endpoint = view_func.__name__1257- options['endpoint'] = endpoint1258- options.setdefault('methods', ('GET',))1259- self.url_map.add(Rule(rule, **options))1260- if view_func is not None:1261- self.view_functions[endpoint] = view_func1262-1263- def route(self, rule, **options):1264- """A decorator that is used to register a view function for a1265- given URL rule. Example::1266-1267- @app.route('/')1268- def index():1269- return 'Hello World'1270-1271- Variables parts in the route can be specified with angular1272- brackets (``/user/<username>``). By default a variable part1273- in the URL accepts any string without a slash however a different1274- converter can be specified as well by using ``<converter:name>``.1275-1276- Variable parts are passed to the view function as keyword1277- arguments.1278-1279- The following converters are possible:1280-1281- =========== ===========================================1282- `int` accepts integers1283- `float` like `int` but for floating point values1284- `path` like the default but also accepts slashes1285- =========== ===========================================1286-1287- Here some examples::1288-1289- @app.route('/')1290- def index():1291- pass1292-1293- @app.route('/<username>')1294- def show_user(username):1295- pass1296-1297- @app.route('/post/<int:post_id>')1298- def show_post(post_id):1299- pass1300-1301- An important detail to keep in mind is how Flask deals with trailing1302- slashes. The idea is to keep each URL unique so the following rules1303- apply:1304-1305- 1. If a rule ends with a slash and is requested without a slash1306- by the user, the user is automatically redirected to the same1307- page with a trailing slash attached.1308- 2. If a rule does not end with a trailing slash and the user request1309- the page with a trailing slash, a 404 not found is raised.1310-1311- This is consistent with how web servers deal with static files. This1312- also makes it possible to use relative link targets safely.1313-1314- The :meth:`route` decorator accepts a couple of other arguments1315- as well:1316-1317- :param rule: the URL rule as string1318- :param methods: a list of methods this rule should be limited1319- to (``GET``, ``POST`` etc.). By default a rule1320- just listens for ``GET`` (and implicitly ``HEAD``).1321- :param subdomain: specifies the rule for the subdomain in case1322- subdomain matching is in use.1323- :param strict_slashes: can be used to disable the strict slashes1324- setting for this rule. See above.1325- :param options: other options to be forwarded to the underlying1326- :class:`~werkzeug.routing.Rule` object.1327- """1328- def decorator(f):1329- self.add_url_rule(rule, None, f, **options)1330- return f1331- return decorator1332-1333- def errorhandler(self, code):1334- """A decorator that is used to register a function give a given1335- error code. Example::1336-1337- @app.errorhandler(404)1338- def page_not_found(error):1339- return 'This page does not exist', 4041340-1341- You can also register a function as error handler without using1342- the :meth:`errorhandler` decorator. The following example is1343- equivalent to the one above::1344-1345- def page_not_found(error):1346- return 'This page does not exist', 4041347- app.error_handlers[404] = page_not_found1348-1349- :param code: the code as integer for the handler1350- """1351- def decorator(f):1352- self.error_handlers[code] = f1353- return f1354- return decorator1355-1356- def template_filter(self, name=None):1357- """A decorator that is used to register custom template filter.1358- You can specify a name for the filter, otherwise the function1359- name will be used. Example::1360-1361- @app.template_filter()1362- def reverse(s):1363- return s[::-1]1364-1365- :param name: the optional name of the filter, otherwise the1366- function name will be used.1367- """1368- def decorator(f):1369- self.jinja_env.filters[name or f.__name__] = f1370- return f1371- return decorator1372-1373- def before_request(self, f):1374- """Registers a function to run before each request."""1375- self.before_request_funcs.setdefault(None, []).append(f)1376- return f1377-1378- def after_request(self, f):1379- """Register a function to be run after each request."""1380- self.after_request_funcs.setdefault(None, []).append(f)1381- return f1382-1383- def context_processor(self, f):1384- """Registers a template context processor function."""1385- self.template_context_processors[None].append(f)1386- return f1387-1388- def handle_http_exception(self, e):1389- """Handles an HTTP exception. By default this will invoke the1390- registered error handlers and fall back to returning the1391- exception as response.1392-1393- .. versionadded: 0.31394- """1395- handler = self.error_handlers.get(e.code)1396- if handler is None:1397- return e1398- return handler(e)1399-1400- def handle_exception(self, e):1401- """Default exception handling that kicks in when an exception1402- occours that is not catched. In debug mode the exception will1403- be re-raised immediately, otherwise it is logged and the handler1404- for a 500 internal server error is used. If no such handler1405- exists, a default 500 internal server error message is displayed.1406-1407- .. versionadded: 0.31408- """1409- handler = self.error_handlers.get(500)1410- if self.debug:1411- raise1412- self.logger.exception('Exception on %s [%s]' % (1413- request.path,1414- request.method1415- ))1416- if handler is None:1417- return InternalServerError()1418- return handler(e)1419-1420- def dispatch_request(self):1421- """Does the request dispatching. Matches the URL and returns the1422- return value of the view or error handler. This does not have to1423- be a response object. In order to convert the return value to a1424- proper response object, call :func:`make_response`.1425- """1426- req = _request_ctx_stack.top.request1427- try:1428- if req.routing_exception is not None:1429- raise req.routing_exception1430- return self.view_functions[req.endpoint](**req.view_args)1431- except HTTPException, e:1432- return self.handle_http_exception(e)1433-1434- def make_response(self, rv):1435- """Converts the return value from a view function to a real1436- response object that is an instance of :attr:`response_class`.1437-1438- The following types are allowed for `rv`:1439-1440- .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1441-1442- ======================= ===========================================1443- :attr:`response_class` the object is returned unchanged1444- :class:`str` a response object is created with the1445- string as body1446- :class:`unicode` a response object is created with the1447- string encoded to utf-8 as body1448- :class:`tuple` the response object is created with the1449- contents of the tuple as arguments1450- a WSGI function the function is called as WSGI application1451- and buffered as response object1452- ======================= ===========================================1453-1454- :param rv: the return value from the view function1455- """1456- if rv is None:1457- raise ValueError('View function did not return a response')1458- if isinstance(rv, self.response_class):1459- return rv1460- if isinstance(rv, basestring):1461- return self.response_class(rv)1462- if isinstance(rv, tuple):1463- return self.response_class(*rv)1464- return self.response_class.force_type(rv, request.environ)1465-1466- def preprocess_request(self):1467- """Called before the actual request dispatching and will1468- call every as :meth:`before_request` decorated function.1469- If any of these function returns a value it's handled as1470- if it was the return value from the view and further1471- request handling is stopped.1472- """1473- funcs = self.before_request_funcs.get(None, ())1474- mod = request.module1475- if mod and mod in self.before_request_funcs:1476- funcs = chain(funcs, self.before_request_funcs[mod])1477- for func in funcs:1478- rv = func()1479- if rv is not None:1480- return rv1481-1482- def process_response(self, response):1483- """Can be overridden in order to modify the response object1484- before it's sent to the WSGI server. By default this will1485- call all the :meth:`after_request` decorated functions.1486-1487- :param response: a :attr:`response_class` object.1488- :return: a new response object or the same, has to be an1489- instance of :attr:`response_class`.1490- """1491- ctx = _request_ctx_stack.top1492- mod = ctx.request.module1493- if not isinstance(ctx.session, _NullSession):1494- self.save_session(ctx.session, response)1495- funcs = ()1496- if mod and mod in self.after_request_funcs:1497- funcs = chain(funcs, self.after_request_funcs[mod])1498- if None in self.after_request_funcs:1499- funcs = chain(funcs, self.after_request_funcs[None])1500- for handler in funcs:1501- response = handler(response)1502- return response1503-1504- def wsgi_app(self, environ, start_response):1505- """The actual WSGI application. This is not implemented in1506- `__call__` so that middlewares can be applied without losing a1507- reference to the class. So instead of doing this::1508-1509- app = MyMiddleware(app)1510-1511- It's a better idea to do this instead::1512-1513- app.wsgi_app = MyMiddleware(app.wsgi_app)1514-1515- Then you still have the original application object around and1516- can continue to call methods on it.1517-1518- .. versionchanged:: 0.41519- The :meth:`after_request` functions are now called even if an1520- error handler took over request processing. This ensures that1521- even if an exception happens database have the chance to1522- properly close the connection.1523-1524- :param environ: a WSGI environment1525- :param start_response: a callable accepting a status code,1526- a list of headers and an optional1527- exception context to start the response1528- """1529- with self.request_context(environ):1530- try:1531- rv = self.preprocess_request()1532- if rv is None:1533- rv = self.dispatch_request()1534- response = self.make_response(rv)1535- except Exception, e:1536- response = self.make_response(self.handle_exception(e))1537- try:1538- response = self.process_response(response)1539- except Exception, e:1540- response = self.make_response(self.handle_exception(e))1541- return response(environ, start_response)1542-1543- def request_context(self, environ):1544- """Creates a request context from the given environment and binds1545- it to the current context. This must be used in combination with1546- the `with` statement because the request is only bound to the1547- current context for the duration of the `with` block.1548-1549- Example usage::1550-1551- with app.request_context(environ):1552- do_something_with(request)1553-1554- The object returned can also be used without the `with` statement1555- which is useful for working in the shell. The example above is1556- doing exactly the same as this code::1557-1558- ctx = app.request_context(environ)1559- ctx.push()1560- try:1561- do_something_with(request)1562- finally:1563- ctx.pop()1564-1565- The big advantage of this approach is that you can use it without1566- the try/finally statement in a shell for interactive testing:1567-1568- >>> ctx = app.test_request_context()1569- >>> ctx.bind()1570- >>> request.path1571- u'/'1572- >>> ctx.unbind()1573-1574- .. versionchanged:: 0.31575- Added support for non-with statement usage and `with` statement1576- is now passed the ctx object.1577-1578- :param environ: a WSGI environment1579- """1580- return _RequestContext(self, environ)1581-1582- def test_request_context(self, *args, **kwargs):1583- """Creates a WSGI environment from the given values (see1584- :func:`werkzeug.create_environ` for more information, this1585- function accepts the same arguments).1586- """1587- return self.request_context(create_environ(*args, **kwargs))1588-1589- def __call__(self, environ, start_response):1590- """Shortcut for :attr:`wsgi_app`."""1591- return self.wsgi_app(environ, start_response)1592-1593-1594-# context locals1595-_request_ctx_stack = LocalStack()1596-current_app = LocalProxy(lambda: _request_ctx_stack.top.app)1597-request = LocalProxy(lambda: _request_ctx_stack.top.request)1598-session = LocalProxy(lambda: _request_ctx_stack.top.session)1599-g = LocalProxy(lambda: _request_ctx_stack.top.g)