flask.py
This file
Path
flask.py
605 lines · 23.1 KiB · Python
Last changed by
Added testing documentationArmin Ronacherbefore adoption03148db
History of this fileTake it
Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 1–151# -*- coding: utf-8 -*-2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import os13import sys14import pkg_resources15from threading import localImproved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 16why, one step back16from contextlib import contextmanager17from jinja2 import Environment, PackageLoaderAdded testing documentationArmin Ronacherbefore adoption03148db
lines 18–19why, one step back18from werkzeug import Request as RequestBase, Response as ResponseBase, \19 LocalStack, LocalProxy, create_environ, cached_propertyInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 20–2520from werkzeug.routing import Map, Rule21from werkzeug.exceptions import HTTPException, InternalServerError22from werkzeug.contrib.securecookie import SecureCookie2324# utilities we import from Werkzeug and Jinja2 that are unused25# in the module but are exported as public interface.Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 26why, one step back26from werkzeug import abort, redirectInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 27–2927from jinja2 import Markup, escape2829Added testing documentationArmin Ronacherbefore adoption03148db
line 30why, one step back30class Request(RequestBase):Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 31–3231 """The request object used by default in flask. Remembers the32 matched endpoint and view arguments.Added testing documentationArmin Ronacherbefore adoption03148db
lines 33–36why, one step back3334 It is what ends up as :class:`~flask.request`. If you want to replace35 the request object used you can subclass this and set36 :attr:`~flask.Flask.request_class` to your subclass.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 37–3937 """3839 def __init__(self, environ):Added testing documentationArmin Ronacherbefore adoption03148db
line 40why, one step back40 RequestBase.__init__(self, environ)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 41–4441 self.endpoint = None42 self.view_args = None4344Added testing documentationArmin Ronacherbefore adoption03148db
line 45why, one step back45class Response(ResponseBase):Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 46–4746 """The response object that is used by default in flask. Works like the47 response object from Werkzeug but is set to have a HTML mimetype byAdded testing documentationArmin Ronacherbefore adoption03148db
lines 48–52why, one step back48 default. Quite often you don't have to create this object yourself because49 :meth:`~flask.Flask.make_response` will take care of that for you.5051 If you want to replace the response object used you can subclass this and52 set :attr:`~flask.Flask.request_class` to your subclass.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 53–8953 """54 default_mimetype = 'text/html'555657class _RequestGlobals(object):58 pass596061class _RequestContext(object):62 """The request context contains all request relevant information. It is63 created at the beginning of the request and pushed to the64 `_request_ctx_stack` and removed at the end of it. It will create the65 URL adapter and request object for the WSGI environment provided.66 """6768 def __init__(self, app, environ):69 self.app = app70 self.url_adapter = app.url_map.bind_to_environ(environ)71 self.request = app.request_class(environ)72 self.session = app.open_session(self.request)73 self.g = _RequestGlobals()74 self.flashes = None757677def url_for(endpoint, **values):78 """Generates a URL to the given endpoint with the method provided.7980 :param endpoint: the endpoint of the URL (name of the function)81 :param values: the variable arguments of the URL rule82 """83 return _request_ctx_stack.top.url_adapter.build(endpoint, values)848586def flash(message):87 """Flashes a message to the next request. In order to remove the88 flashed message from the session and to display it to the user,89 the template has to call :func:`get_flashed_messages`.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 90–91why, one step back9091 :param message: the message to be flashed.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 92–11092 """93 session['_flashes'] = (session.get('_flashes', [])) + [message]949596def get_flashed_messages():97 """Pulls all flashed messages from the session and returns them.98 Further calls in the same request to the function will return99 the same messages.100 """101 flashes = _request_ctx_stack.top.flashes102 if flashes is None:103 _request_ctx_stack.top.flashes = flashes = \104 session.pop('_flashes', [])105 return flashes106107108def render_template(template_name, **context):109 """Renders a template from the template folder with the given110 context.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 111–114why, one step back111112 :param template_name: the name of the template to be rendered113 :param context: the variables that should be available in the114 context of the template.115 """Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 116why, one step back116 current_app.update_template_context(context)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 117–122117 return current_app.jinja_env.get_template(template_name).render(context)118119120def render_template_string(source, **context):121 """Renders a template from the given template source string122 with the given context.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 123–127why, one step back123124 :param template_name: the sourcecode of the template to be125 rendered126 :param context: the variables that should be available in the127 context of the template.128 """Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 129why, one step back129 current_app.update_template_context(context)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 130–134130 return current_app.jinja_env.from_string(source).render(context)131132133class Flask(object):134 """The flask object implements a WSGI application and acts as the centralStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 135–150why, one step back135 object. It is passed the name of the module or package of the136 application. Once it is created it will act as a central registry for137 the view functions, the URL rules, template configuration and much more.138139 The name of the package is used to resolve resources from inside the140 package or the folder the module is contained in depending on if the141 package parameter resolves to an actual python package (a folder with142 an `__init__.py` file inside) or a standard module (just a `.py` file).143144 For more information about resource loading, see :func:`open_resource`.145146 Usually you create a :class:`Flask` instance in your main module or147 in the `__init__.py` file of your package like this::148149 from flask import Flask150 app = Flask(__name__)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 151–152151 """152Added testing documentationArmin Ronacherbefore adoption03148db
lines 153–155why, one step back153 #: the class that is used for request objects. See :class:`~flask.request`154 #: for more information.155 request_class = Request156Added testing documentationArmin Ronacherbefore adoption03148db
lines 157–159why, one step back157 #: the class that is used for response objects. See158 #: :class:`~flask.Response` for more information.159 response_class = ResponseInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 160–180160161 #: path for the static files. If you don't want to use static files162 #: you can set this value to `None` in which case no URL rule is added163 #: and the development server will no longer serve any static files.164 static_path = '/static'165166 #: if a secret key is set, cryptographic components can use this to167 #: sign cookies and other things. Set this to a complex random value168 #: when you want to use the secure cookie for instance.169 secret_key = None170171 #: The secure cookie uses this for the name of the session cookie172 session_cookie_name = 'session'173174 #: options that are passed directly to the Jinja2 environment175 jinja_options = dict(176 autoescape=True,177 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']178 )179180 def __init__(self, package_name):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 181–185why, one step back181 #: the debug flag. Set this to `True` to enable debugging of182 #: the application. In debug mode the debugger will kick in183 #: when an unhandled exception ocurrs and the integrated server184 #: will automatically reload the application if changes in the185 #: code are detected.186 self.debug = FalseStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 187–189why, one step back187188 #: the name of the package or module. Do not change this once189 #: it was set by the constructor.190 self.package_name = package_nameStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 191–195why, one step back191192 #: a dictionary of all view functions registered. The keys will193 #: be function names which are also used to generate URLs and194 #: the values are the function objects themselves.195 #: to register a view function, use the :meth:`route` decorator.196 self.view_functions = {}Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 197–202why, one step back197198 #: a dictionary of all registered error handlers. The key is199 #: be the error code as integer, the value the function that200 #: should handle that error.201 #: To register a error handler, use the :meth:`errorhandler`202 #: decorator.203 self.error_handlers = {}Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 204–210why, one step back204205 #: a list of functions that should be called at the beginning206 #: of the request before request dispatching kicks in. This207 #: can for example be used to open database connections or208 #: getting hold of the currently logged in user.209 #: To register a function here, use the :meth:`request_init`210 #: decorator.211 self.request_init_funcs = []Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 212–217why, one step back212213 #: a list of functions that are called at the end of the214 #: request. Tha function is passed the current response215 #: object and modify it in place or replace it.216 #: To register a function here use the :meth:`request_shtdown`217 #: decorator.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 218–224218 self.request_shutdown_funcs = []219 self.url_map = Map()220221 if self.static_path is not None:222 self.url_map.add(Rule(self.static_path + '/<filename>',223 build_only=True, endpoint='static'))224Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 225–227why, one step back225 #: the Jinja2 environment. It is created from the226 #: :attr:`jinja_options` and the loader that is returned227 #: by the :meth:`create_jinja_loader` function.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 228–242228 self.jinja_env = Environment(loader=self.create_jinja_loader(),229 **self.jinja_options)230 self.jinja_env.globals.update(231 url_for=url_for,232 get_flashed_messages=get_flashed_messages233 )234235 def create_jinja_loader(self):236 """Creates the Jinja loader. By default just a package loader for237 the configured package is returned that looks up templates in the238 `templates` folder. To add other loaders it's possible to239 override this method.240 """241 return PackageLoader(self.package_name)242Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 243–245why, one step back243 def update_template_context(self, context):244 """Update the template context with some commonly used variables.245 This injects request, session and g into the template context.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 246–248why, one step back246247 :param context: the context as a dictionary that is updated in place248 to add extra variables.Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 249–254why, one step back249 """250 reqctx = _request_ctx_stack.top251 context['request'] = reqctx.request252 context['session'] = reqctx.session253 context['g'] = reqctx.g254255 def run(self, host='localhost', port=5000, **options):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 256–258why, one step back256 """Runs the application on a local development server. If the257 :attr:`debug` flag is set the server will automatically reload258 for code changes and show a debugger in case an exception happened.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 259–265why, one step back259260 :param host: the hostname to listen on. set this to ``'0.0.0.0'``261 to have the server available externally as well.262 :param port: the port of the webserver263 :param options: the options to be forwarded to the underlying264 Werkzeug server. See :func:`werkzeug.run_simple`265 for more information.Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 266why, one step back266 """Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 267–277267 from werkzeug import run_simple268 if 'debug' in options:269 self.debug = options.pop('debug')270 if self.static_path is not None:271 options['static_files'] = {272 self.static_path: (self.package_name, 'static')273 }274 options.setdefault('use_reloader', self.debug)275 options.setdefault('use_debugger', self.debug)276 return run_simple(host, port, self, **options)277Added tests for minitwit. Testing with Flask is awesomeArmin Ronacherbefore adoptionf2dc38c
line 278why, one step back278 def test_client(self):Added testing documentationArmin Ronacherbefore adoption03148db
lines 279–281why, one step back279 """Creates a test client for this application. For information280 about unit testing head over to :ref:`testing`.281 """Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 282–285282 from werkzeug import Client283 return Client(self, self.response_class, use_cookies=True)284285 def open_resource(self, resource):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 286–302why, one step back286 """Opens a resource from the application's resource folder. To see287 how this works, consider the following folder structure::288289 /myapplication.py290 /schemal.sql291 /static292 /style.css293 /template294 /layout.html295 /index.html296297 If you want to open the `schema.sql` file you would do the298 following::299300 with app.open_resource('schema.sql') as f:301 contents = f.read()302 do_something_with(contents)Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 303–305why, one step back303304 :param resource: the name of the resource. To access resources within305 subfolders use forward slashes as separator.Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 306why, one step back306 """Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 307–309307 return pkg_resources.resource_stream(self.package_name, resource)308309 def open_session(self, request):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 310–312why, one step back310 """Creates or opens a new session. Default implementation stores all311 session data in a signed cookie. This requires that the312 :attr:`secret_key` is set.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 313–314why, one step back313314 :param request: an instance of :attr:`request_class`.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 315–321315 """316 key = self.secret_key317 if key is not None:318 return SecureCookie.load_cookie(request, self.session_cookie_name,319 secret_key=key)320321 def save_session(self, session, response):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 322–323why, one step back322 """Saves the session if it needs updates. For the default323 implementation, check :meth:`open_session`.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 324–328why, one step back324325 :param session: the session to be saved (a326 :class:`~werkzeug.contrib.securecookie.SecureCookie`327 object)328 :param request: an instance of :attr:`response_class`Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 329why, one step back329 """Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 330–332330 if session is not None:331 session.save_cookie(response, self.session_cookie_name)332Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3
line 333why, one step back333 def add_url_rule(self, rule, endpoint, **options):Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 334–342why, one step back334 """Connects a URL rule. Works exactly like the :meth:`route`335 decorator but does not register the view function for the endpoint.336337 Basically this example::338339 @app.route('/')340 def index():341 pass342Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3
line 343why, one step back343 Is equivalent to the following::Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 344–348why, one step back344345 def index():346 pass347 app.add_url_rule('index', '/')348 app.view_functions['index'] = indexHeavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 349–355why, one step back349350 :param rule: the URL rule as string351 :param endpoint: the endpoint for the registered URL rule. Flask352 itself assumes the name of the view function as353 endpoint354 :param options: the options to be forwarded to the underlying355 :class:`~werkzeug.routing.Rule` objectDocumented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
line 356why, one step back356 """Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3
line 357why, one step back357 options['endpoint'] = endpointDocumented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 358–360why, one step back358 options.setdefault('methods', ('GET',))359 self.url_map.add(Rule(rule, **options))360Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 361–367361 def route(self, rule, **options):362 """A decorator that is used to register a view function for a363 given URL rule. Example::364365 @app.route('/')366 def index():367 return 'Hello World'Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 368–370why, one step back368369 Variables parts in the route can be specified with angular370 brackets (``/user/<username>``). By default a variable partAdded testing documentationArmin Ronacherbefore adoption03148db
line 371why, one step back371 in the URL accepts any string without a slash however a differentStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 372–398why, one step back372 converter can be specified as well by using ``<converter:name>``.373374 Variable parts are passed to the view function as keyword375 arguments.376377 The following converters are possible:378379 =========== ===========================================380 `int` accepts integers381 `float` like `int` but for floating point values382 `path` like the default but also accepts slashes383 =========== ===========================================384385 Here some examples::386387 @app.route('/')388 def index():389 pass390391 @app.route('/<username>')392 def show_user(username):393 pass394395 @app.route('/post/<int:post_id>')396 def show_post(post_id):397 pass398Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 399–411why, one step back399 An important detail to keep in mind is how Flask deals with trailing400 slashes. The idea is to keep each URL unique so the following rules401 apply:402403 1. If a rule ends with a slash and is requested without a slash404 by the user, the user is automatically redirected to the same405 page with a trailing slash attached.406 2. If a rule does not end with a trailing slash and the user request407 the page with a trailing slash, a 404 not found is raised.408409 This is consistent with how web servers deal with static files. This410 also makes it possible to use relative link targets safely.411Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 412–414why, one step back412 The :meth:`route` decorator accepts a couple of other arguments413 as well:414Heavily improved documentationArmin Ronacherbefore adoption05f36c7
line 415why, one step back415 :param rule: the URL rule as stringStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 416why, one step back416 :param methods: a list of methods this rule should be limitedUpdated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 417–418why, one step back417 to (``GET``, ``POST`` etc.). By default a rule418 just listens for ``GET`` (and implicitly ``HEAD``).Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 419–422why, one step back419 :param subdomain: specifies the rule for the subdoain in case420 subdomain matching is in use.421 :param strict_slashes: can be used to disable the strict slashes422 setting for this rule. See above.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 423–424why, one step back423 :param options: other options to be forwarded to the underlying424 :class:`~werkzeug.routing.Rule` object.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 425–426425 """426 def decorator(f):Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3
line 427why, one step back427 self.add_url_rule(rule, f.__name__, **options)Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
line 428why, one step back428 self.view_functions[f.__name__] = fInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 429–438429 return f430 return decorator431432 def errorhandler(self, code):433 """A decorator that is used to register a function give a given434 error code. Example::435436 @app.errorhandler(404)437 def page_not_found():438 return 'This page does not exist', 404Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 439–446why, one step back439440 You can also register a function as error handler without using441 the :meth:`errorhandler` decorator. The following example is442 equivalent to the one above::443444 def page_not_found():445 return 'This page does not exist', 404446 app.error_handlers[404] = page_not_foundHeavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 447–448why, one step back447448 :param code: the code as integer for the handlerInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 449–496449 """450 def decorator(f):451 self.error_handlers[code] = f452 return f453 return decorator454455 def request_init(self, f):456 """Registers a function to run before each request."""457 self.request_init_funcs.append(f)458 return f459460 def request_shutdown(self, f):461 """Register a function to be run after each request."""462 self.request_shutdown_funcs.append(f)463 return f464465 def match_request(self):466 """Matches the current request against the URL map and also467 stores the endpoint and view arguments on the request object468 is successful, otherwise the exception is stored.469 """470 rv = _request_ctx_stack.top.url_adapter.match()471 request.endpoint, request.view_args = rv472 return rv473474 def dispatch_request(self):475 """Does the request dispatching. Matches the URL and returns the476 return value of the view or error handler. This does not have to477 be a response object. In order to convert the return value to a478 proper response object, call :func:`make_response`.479 """480 try:481 endpoint, values = self.match_request()482 return self.view_functions[endpoint](**values)483 except HTTPException, e:484 handler = self.error_handlers.get(e.code)485 if handler is None:486 return e487 return handler(e)488 except Exception, e:489 handler = self.error_handlers.get(500)490 if self.debug or handler is None:491 raise492 return handler(e)493494 def make_response(self, rv):495 """Converts the return value from a view function to a real496 response object that is an instance of :attr:`response_class`.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 497–512why, one step back497498 The following types are allowd for `rv`:499500 ======================= ===========================================501 :attr:`response_class` the object is returned unchanged502 :class:`str` a response object is created with the503 string as body504 :class:`unicode` a response object is created with the505 string encoded to utf-8 as body506 :class:`tuple` the response object is created with the507 contents of the tuple as arguments508 a WSGI function the function is called as WSGI application509 and buffered as response object510 ======================= ===========================================511512 :param rv: the return value from the view functionInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 513–536513 """514 if isinstance(rv, self.response_class):515 return rv516 if isinstance(rv, basestring):517 return self.response_class(rv)518 if isinstance(rv, tuple):519 return self.response_class(*rv)520 return self.response_class.force_type(rv, request.environ)521522 def preprocess_request(self):523 """Called before the actual request dispatching and will524 call every as :func:`request_init` decorated function.525 If any of these function returns a value it's handled as526 if it was the return value from the view and further527 request handling is stopped.528 """529 for func in self.request_init_funcs:530 rv = func()531 if rv is not None:532 return rv533534 def process_response(self, response):535 """Can be overridden in order to modify the response object536 before it's sent to the WSGI server.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 537–540why, one step back537538 :param response: a :attr:`response_class` object.539 :return: a new response object or the same, has to be an540 instance of :attr:`response_class`.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 541–553541 """542 session = _request_ctx_stack.top.session543 if session is not None:544 self.save_session(session, response)545 for handler in self.request_shutdown_funcs:546 response = handler(response)547 return response548549 def wsgi_app(self, environ, start_response):550 """The actual WSGI application. This is not implemented in551 `__call__` so that middlewares can be applied:552553 app.wsgi_app = MyMiddleware(app.wsgi_app)Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 554–558why, one step back554555 :param environ: a WSGI environment556 :param start_response: a callable accepting a status code,557 a list of headers and an optional558 exception context to start the response559 """Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 560why, one step back560 with self.request_context(environ):Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 561–566561 rv = self.preprocess_request()562 if rv is None:563 rv = self.dispatch_request()564 response = self.make_response(rv)565 response = self.process_response(response)566 return response(environ, start_response)Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 567–578why, one step back567568 @contextmanager569 def request_context(self, environ):570 """Creates a request context from the given environment and binds571 it to the current context. This must be used in combination with572 the `with` statement because the request is only bound to the573 current context for the duration of the `with` block.574575 Example usage::576577 with app.request_context(environ):578 do_something_with(request)Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 579–580why, one step back579580 :params environ: a WSGI environmentImproved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 581–584why, one step back581 """582 _request_ctx_stack.push(_RequestContext(self, environ))583 try:584 yieldInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 585–586585 finally:586 _request_ctx_stack.pop()Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 587–589why, one step back587588 def test_request_context(self, *args, **kwargs):589 """Creates a WSGI environment from the given values (seeHeavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 590–591why, one step back590 :func:`werkzeug.create_environ` for more information, this591 function accepts the same arguments).Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 592–593why, one step back592 """593 return self.request_context(create_environ(*args, **kwargs))Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 594–605594595 def __call__(self, environ, start_response):596 """Shortcut for :attr:`wsgi_app`"""597 return self.wsgi_app(environ, start_response)598599600# context locals601_request_ctx_stack = LocalStack()602current_app = LocalProxy(lambda: _request_ctx_stack.top.app)603request = LocalProxy(lambda: _request_ctx_stack.top.request)604session = LocalProxy(lambda: _request_ctx_stack.top.session)605g = LocalProxy(lambda: _request_ctx_stack.top.g)