Skip to content
Myr

flask.py

This file

Path

flask.py

605 lines · 23.1 KiB · Python

Last changed by

Added testing documentationArmin Ronacherbefore adoption03148db

History of this file

Take it

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 1–15
1# -*- coding: utf-8 -*-
2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import os13import sys14import pkg_resources15from threading import local

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 16why, one step back
16from contextlib import contextmanager

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 17
17from jinja2 import Environment, PackageLoader

Added testing documentationArmin Ronacherbefore adoption03148db

lines 18–19why, one step back
18from werkzeug import Request as RequestBase, Response as ResponseBase, \
19 LocalStack, LocalProxy, create_environ, cached_property

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 20–25
20from werkzeug.routing import Map, Rule
21from 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 back
26from werkzeug import abort, redirect

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 27–29
27from jinja2 import Markup, escape
2829

Added testing documentationArmin Ronacherbefore adoption03148db

line 30why, one step back
30class Request(RequestBase):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 31–32
31 """The request object used by default in flask. Remembers the
32 matched endpoint and view arguments.

Added testing documentationArmin Ronacherbefore adoption03148db

lines 33–36why, one step back
33
34 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–39
37 """
3839 def __init__(self, environ):

Added testing documentationArmin Ronacherbefore adoption03148db

line 40why, one step back
40 RequestBase.__init__(self, environ)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 41–44
41 self.endpoint = None
42 self.view_args = None4344

Added testing documentationArmin Ronacherbefore adoption03148db

line 45why, one step back
45class Response(ResponseBase):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 46–47
46 """The response object that is used by default in flask. Works like the
47 response object from Werkzeug but is set to have a HTML mimetype by

Added testing documentationArmin Ronacherbefore adoption03148db

lines 48–52why, one step back
48 default. Quite often you don't have to create this object yourself because
49 :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–89
53 """
54 default_mimetype = 'text/html'555657class _RequestGlobals(object):58 pass596061class _RequestContext(object):62 """The request context contains all request relevant information. It is63 created at the beginning of the request and pushed to the64 `_request_ctx_stack` and removed at the end of it. It will create the65 URL adapter and request object for the WSGI environment provided.66 """6768 def __init__(self, app, environ):69 self.app = app70 self.url_adapter = app.url_map.bind_to_environ(environ)71 self.request = app.request_class(environ)72 self.session = app.open_session(self.request)73 self.g = _RequestGlobals()74 self.flashes = None757677def url_for(endpoint, **values):78 """Generates a URL to the given endpoint with the method provided.7980 :param endpoint: the endpoint of the URL (name of the function)81 :param values: the variable arguments of the URL rule82 """83 return _request_ctx_stack.top.url_adapter.build(endpoint, values)848586def flash(message):87 """Flashes a message to the next request. In order to remove the88 flashed message from the session and to display it to the user,89 the template has to call :func:`get_flashed_messages`.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 90–91why, one step back
90
91 :param message: the message to be flashed.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 92–110
92 """
93 session['_flashes'] = (session.get('_flashes', [])) + [message]949596def get_flashed_messages():97 """Pulls all flashed messages from the session and returns them.98 Further calls in the same request to the function will return99 the same messages.100 """101 flashes = _request_ctx_stack.top.flashes102 if flashes is None:103 _request_ctx_stack.top.flashes = flashes = \104 session.pop('_flashes', [])105 return flashes106107108def render_template(template_name, **context):109 """Renders a template from the template folder with the given110 context.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 111–114why, one step back
111
112 :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.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 115
115 """

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 116why, one step back
116 current_app.update_template_context(context)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 117–122
117 return current_app.jinja_env.get_template(template_name).render(context)
118119120def render_template_string(source, **context):121 """Renders a template from the given template source string122 with the given context.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 123–127why, one step back
123
124 :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.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 128
128 """

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 129why, one step back
129 current_app.update_template_context(context)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 130–134
130 return current_app.jinja_env.from_string(source).render(context)
131132133class Flask(object):134 """The flask object implements a WSGI application and acts as the central

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 135–150why, one step back
135 object. It is passed the name of the module or package of the
136 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–152
151 """
152

Added testing documentationArmin Ronacherbefore adoption03148db

lines 153–155why, one step back
153 #: the class that is used for request objects. See :class:`~flask.request`
154 #: for more information.155 request_class = Request

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 156
156

Added testing documentationArmin Ronacherbefore adoption03148db

lines 157–159why, one step back
157 #: the class that is used for response objects. See
158 #: :class:`~flask.Response` for more information.159 response_class = Response

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 160–180
160
161 #: 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 back
181 #: the debug flag. Set this to `True` to enable debugging of
182 #: 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.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 186
186 self.debug = False

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 187–189why, one step back
187
188 #: the name of the package or module. Do not change this once189 #: it was set by the constructor.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 190
190 self.package_name = package_name

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 191–195why, one step back
191
192 #: 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.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 196
196 self.view_functions = {}

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 197–202why, one step back
197
198 #: 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.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 203
203 self.error_handlers = {}

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 204–210why, one step back
204
205 #: 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.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 211
211 self.request_init_funcs = []

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 212–217why, one step back
212
213 #: 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–224
218 self.request_shutdown_funcs = []
219 self.url_map = Map()220221 if self.static_path is not None:222 self.url_map.add(Rule(self.static_path + '/<filename>',223 build_only=True, endpoint='static'))224

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 225–227why, one step back
225 #: the Jinja2 environment. It is created from the
226 #: :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–242
228 self.jinja_env = Environment(loader=self.create_jinja_loader(),
229 **self.jinja_options)230 self.jinja_env.globals.update(231 url_for=url_for,232 get_flashed_messages=get_flashed_messages233 )234235 def create_jinja_loader(self):236 """Creates the Jinja loader. By default just a package loader for237 the configured package is returned that looks up templates in the238 `templates` folder. To add other loaders it's possible to239 override this method.240 """241 return PackageLoader(self.package_name)242

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 243–245why, one step back
243 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 back
246
247 :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 back
249 """
250 reqctx = _request_ctx_stack.top251 context['request'] = reqctx.request252 context['session'] = reqctx.session253 context['g'] = reqctx.g254

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 255
255 def run(self, host='localhost', port=5000, **options):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 256–258why, one step back
256 """Runs the application on a local development server. If the
257 :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 back
259
260 :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 back
266 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 267–277
267 from werkzeug import run_simple
268 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)277

Added tests for minitwit. Testing with Flask is awesomeArmin Ronacherbefore adoptionf2dc38c

line 278why, one step back
278 def test_client(self):

Added testing documentationArmin Ronacherbefore adoption03148db

lines 279–281why, one step back
279 """Creates a test client for this application. For information
280 about unit testing head over to :ref:`testing`.281 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 282–285
282 from werkzeug import Client
283 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 back
286 """Opens a resource from the application's resource folder. To see
287 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 back
303
304 :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 back
306 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 307–309
307 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 back
310 """Creates or opens a new session. Default implementation stores all
311 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 back
313
314 :param request: an instance of :attr:`request_class`.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 315–321
315 """
316 key = self.secret_key317 if key is not None:318 return SecureCookie.load_cookie(request, self.session_cookie_name,319 secret_key=key)320321 def save_session(self, session, response):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 322–323why, one step back
322 """Saves the session if it needs updates. For the default
323 implementation, check :meth:`open_session`.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 324–328why, one step back
324
325 :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 back
329 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 330–332
330 if session is not None:
331 session.save_cookie(response, self.session_cookie_name)332

Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3

line 333why, one step back
333 def add_url_rule(self, rule, endpoint, **options):

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 334–342why, one step back
334 """Connects a URL rule. Works exactly like the :meth:`route`
335 decorator but does not register the view function for the endpoint.336337 Basically this example::338339 @app.route('/')340 def index():341 pass342

Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3

line 343why, one step back
343 Is equivalent to the following::

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 344–348why, one step back
344
345 def index():346 pass347 app.add_url_rule('index', '/')348 app.view_functions['index'] = index

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 349–355why, one step back
349
350 :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` object

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

line 356why, one step back
356 """

Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3

line 357why, one step back
357 options['endpoint'] = endpoint

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 358–360why, one step back
358 options.setdefault('methods', ('GET',))
359 self.url_map.add(Rule(rule, **options))360

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 361–367
361 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 back
368
369 Variables parts in the route can be specified with angular370 brackets (``/user/<username>``). By default a variable part

Added testing documentationArmin Ronacherbefore adoption03148db

line 371why, one step back
371 in the URL accepts any string without a slash however a different

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 372–398why, one step back
372 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 pass398

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 399–411why, one step back
399 An important detail to keep in mind is how Flask deals with trailing
400 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.411

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 412–414why, one step back
412 The :meth:`route` decorator accepts a couple of other arguments
413 as well:414

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

line 415why, one step back
415 :param rule: the URL rule as string

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 416why, one step back
416 :param methods: a list of methods this rule should be limited

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 417–418why, one step back
417 to (``GET``, ``POST`` etc.). By default a rule
418 just listens for ``GET`` (and implicitly ``HEAD``).

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 419–422why, one step back
419 :param subdomain: specifies the rule for the subdoain in case
420 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 back
423 :param options: other options to be forwarded to the underlying
424 :class:`~werkzeug.routing.Rule` object.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 425–426
425 """
426 def decorator(f):

Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3

line 427why, one step back
427 self.add_url_rule(rule, f.__name__, **options)

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

line 428why, one step back
428 self.view_functions[f.__name__] = f

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 429–438
429 return f
430 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', 404

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 439–446why, one step back
439
440 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_found

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 447–448why, one step back
447
448 :param code: the code as integer for the handler

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 449–496
449 """
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 back
497
498 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 function

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 513–536
513 """
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 back
537
538 :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–553
541 """
542 session = _request_ctx_stack.top.session543 if session is not None:544 self.save_session(session, response)545 for handler in self.request_shutdown_funcs:546 response = handler(response)547 return response548549 def wsgi_app(self, environ, start_response):550 """The actual WSGI application. This is not implemented in551 `__call__` so that middlewares can be applied:552553 app.wsgi_app = MyMiddleware(app.wsgi_app)

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 554–558why, one step back
554
555 :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 response

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 559
559 """

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 560why, one step back
560 with self.request_context(environ):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 561–566
561 rv = self.preprocess_request()
562 if rv is None:563 rv = self.dispatch_request()564 response = self.make_response(rv)565 response = self.process_response(response)566 return response(environ, start_response)

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 567–578why, one step back
567
568 @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 back
579
580 :params environ: a WSGI environment

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 581–584why, one step back
581 """
582 _request_ctx_stack.push(_RequestContext(self, environ))583 try:584 yield

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 585–586
585 finally:
586 _request_ctx_stack.pop()

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 587–589why, one step back
587
588 def test_request_context(self, *args, **kwargs):589 """Creates a WSGI environment from the given values (see

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 590–591why, one step back
590 :func:`werkzeug.create_environ` for more information, this
591 function accepts the same arguments).

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 592–593why, one step back
592 """
593 return self.request_context(create_environ(*args, **kwargs))

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 594–605
594
595 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)