Started work on new request dispatching. Unittests not yet updated
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 · parent e3f2dd8 · Browse files · 11 files·+436 added−153 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+436 added−153 removed
- tests:+4 added−1 removed
- other:+432 added−152 removed
Provenance
- Commit
e71a5ff- Tree
8bc2254- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e3f2dd8
11 files changed+436 added−153 removed
modified:docs/api.rst+9 added-42 removed
308 unmodified lines309 310 Useful Internals311 ----------------312 313+.. autoclass:: flask.ctx.RequestContext314+ :members:315+316 .. data:: _request_ctx_stack317 318 The internal :class:`~werkzeug.local.LocalStack` that is used to implement319 all the context local objects used in Flask. This is a documented29 unmodified lines349 ctx = _request_ctx_stack.top350 if ctx is not None:351 return ctx.session352 350- .. versionchanged:: 0.4351-352- The request context is automatically popped at the end of the request353- for you. In debug mode the request context is kept around if354- exceptions happen so that interactive debuggers have a chance to355- introspect the data. With 0.4 this can also be forced for requests356- that did not fail and outside of `DEBUG` mode. By setting357- ``'flask._preserve_context'`` to `True` on the WSGI environment the358- context will not pop itself at the end of the request. This is used by359- the :meth:`~flask.Flask.test_client` for example to implement the360- deferred cleanup functionality.361-362- You might find this helpful for unittests where you need the363- information from the context local around for a little longer. Make364- sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in365- that situation, otherwise your unittests will leak memory.366-353 Signals354 -------355 356 .. when modifying this list, also update the one in signals.rst29 unmodified lines386 It is sent *before* the standard exception handling kicks in and even387 in debug mode, where no exception handling happens. The exception388 itself is passed to the subscriber as `exception`.389 390+.. data:: request_tearing_down391+392+ This signal is sent when the application is tearing down the request.393+ This is always called, even if an error happened. No arguments are394+ provided.395+396 .. currentmodule:: None397 398 .. class:: flask.signals.Namespace399 9 unmodified lines409 do nothing but will fail with a :exc:`RuntimeError` for all other410 operations, including connecting.411 412 .. _blinker: http://pypi.python.org/pypi/blinker421-422-.. _notes-on-proxies:423-424-Notes On Proxies425-----------------426-427-Some of the objects provided by Flask are proxies to other objects. The428-reason behind this is that these proxies are shared between threads and429-they have to dispatch to the actual object bound to a thread behind the430-scenes as necessary.431-432-Most of the time you don't have to care about that, but there are some433-exceptions where it is good to know that this object is an actual proxy:434-435-- The proxy objects do not fake their inherited types, so if you want to436- perform actual instance checks, you have to do that on the instance437- that is being proxied (see `_get_current_object` below).438-- if the object reference is important (so for example for sending439- :ref:`signals`)440-441-If you need to get access to the underlying object that is proxied, you442-can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::443-444- app = current_app._get_current_object()445- my_signal.send(app)modified:docs/config.rst+31 added-22 removed
49 unmodified lines50 The following configuration values are used internally by Flask:51 52 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|53 54-=============================== =========================================55-``DEBUG`` enable/disable debug mode56-``TESTING`` enable/disable testing mode57-``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the58- propagation of exceptions. If not set or59- explicitly set to `None` this is60- implicitly true if either `TESTING` or61- `DEBUG` is true.62-``SECRET_KEY`` the secret key63-``SESSION_COOKIE_NAME`` the name of the session cookie64-``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as65- :class:`datetime.timedelta` object.66-``USE_X_SENDFILE`` enable/disable x-sendfile67-``LOGGER_NAME`` the name of the logger68-``SERVER_NAME`` the name of the server. Required for69- subdomain support (e.g.: ``'localhost'``)70-``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will71- reject incoming requests with a72- content length greater than this by73- returning a 413 status code.74-=============================== =========================================54+================================= =========================================55+``DEBUG`` enable/disable debug mode56+``TESTING`` enable/disable testing mode57+``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the58+ propagation of exceptions. If not set or59+ explicitly set to `None` this is60+ implicitly true if either `TESTING` or61+ `DEBUG` is true.62+``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in63+ debug mode the request context is not64+ popped on exceptions to enable debuggers65+ to introspect the data. This can be66+ disabled by this key. You can also use67+ this setting to force-enable it for non68+ debug execution which might be useful to69+ debug production applications (but also70+ very risky).71+``SECRET_KEY`` the secret key72+``SESSION_COOKIE_NAME`` the name of the session cookie73+``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as74+ :class:`datetime.timedelta` object.75+``USE_X_SENDFILE`` enable/disable x-sendfile76+``LOGGER_NAME`` the name of the logger77+``SERVER_NAME`` the name of the server. Required for78+ subdomain support (e.g.: ``'localhost'``)79+``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will80+ reject incoming requests with a81+ content length greater than this by82+ returning a 413 status code.83+================================= =========================================84 85 .. admonition:: More on ``SERVER_NAME``86 87 The ``SERVER_NAME`` key is used for the subdomain support. Because22 unmodified lines110 .. versionadded:: 0.6111 ``MAX_CONTENT_LENGTH``112 113 .. versionadded:: 0.7105- ``PROPAGATE_EXCEPTIONS``114+ ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``115 116 Configuring from Files117 ----------------------118 127 unmodified linesmodified:docs/contents.rst.inc+1 added
15 unmodified lines16 testing17 errorhandling18 config19 signals20+ reqcontext21 shell22 patterns/index23 deploying/index24 becomingbig29 unmodified linesadded:docs/reqcontext.rst+230 added
1+.. _request-context:2+3+The Request Context4+===================5+6+This document describes the behavior in Flask 0.7 which is mostly in line7+with the old behavior but has some small, subtle differences.8+9+One of the design ideas behind Flask is that there are two different10+“states” in which code is executed. The application setup state in which11+the application implicitly is on the module level. It starts when the12+:class:`Flask` object is instantiated, and it implicitly ends when the13+first request comes in. While the application is in this state a few14+assumptions are true:15+16+- the programmer can modify the application object safely.17+- no request handling happened so far18+- you have to have a reference to the application object in order to19+ modify it, there is no magic proxy that can give you a reference to20+ the application object you're currently creating or modifying.21+22+On the contrast, during request handling, a couple of other rules exist:23+24+- while a request is active, the context local objects25+ (:data:`flask.request` and others) point to the current request.26+- any code can get hold of these objects at any time.27+28+The magic that makes this works is internally referred in Flask as the29+“request context”.30+31+Diving into Context Locals32+--------------------------33+34+Say you have a utility function that returns the URL the user should be35+redirected to. Imagine it would always redirect to the URL's ``next``36+parameter or the HTTP referrer or the index page::37+38+ from flask import request, url_for39+40+ def redirect_url():41+ return request.args.get('next') or \42+ request.referrer or \43+ url_for('index')44+45+As you can see, it accesses the request object. If you try to run this46+from a plain Python shell, this is the exception you will see:47+48+>>> redirect_url()49+Traceback (most recent call last):50+ File "<stdin>", line 1, in <module>51+AttributeError: 'NoneType' object has no attribute 'request'52+53+That makes a lot of sense because we currently do not have a request we54+could access. So we have to make a request and bind it to the current55+context. The :attr:`~flask.Flask.test_request_context` method can create56+us a :class:`~flask.ctx.RequestContext`:57+58+>>> ctx = app.test_request_context('/?next=http://example.com/')59+60+This context can be used in two ways. Either with the `with` statement61+or by calling the :meth:`~flask.ctx.RequestContext.push` and62+:meth:`~flask.ctx.RequestContext.pop` methods:63+64+>>> ctx.push()65+66+From that point onwards you can work with the request object:67+68+>>> redirect_url()69+u'http://example.com/'70+71+Until you call `pop`:72+73+>>> ctx.pop()74+75+Because the request context is internally maintained as a stack you can76+push and pop multiple times. This is very handy to implement things like77+internal redirects.78+79+For more information of how to utilize the request context from the80+interactive Python shell, head over to the :ref:`shell` chapter.81+82+How the Context Works83+---------------------84+85+If you look into how the Flask WSGI application internally works, you will86+find a piece of code that looks very much like this::87+88+ def wsgi_app(self, environ):89+ with self.request_context(environ):90+ try:91+ response = self.full_dispatch_request()92+ except Exception, e:93+ response = self.make_response(self.handle_exception(e))94+ return response(environ, start_response)95+96+The method :meth:`~Flask.request_context` returns a new97+:class:`~flask.ctx.RequestContext` object and uses it in combination with98+the `with` statement to bind the context. Everything that is called from99+the same thread from this point onwards until the end of the `with`100+statement will have access to the request globals (:data:`flask.request`101+and others).102+103+The request context internally works like a stack: The topmost level on104+the stack is the current active request.105+:meth:`~flask.ctx.RequestContext.push` adds the context to the stack on106+the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the107+stack again. On popping the application's108+:func:`~flask.Flask.teardown_request` functions are also executed.109+110+.. _callbacks-and-errors:111+112+Callbacks and Errors113+--------------------114+115+What happens if an error occurs in Flask during request processing? This116+particular behavior changed in 0.7 because we wanted to make it easier to117+understand what is actually happening. The new behavior is quite simple:118+119+1. Before each request, :meth:`~flask.Flask.before_request` functions are120+ executed. If one of these functions return a response, the other121+ functions are no longer called. In any case however the return value122+ is treated as a replacement for the view's return value.123+124+2. If the :meth:`~flask.Flask.before_request` functions did not return a125+ response, the regular request handling kicks in and the view function126+ that was matched has the chance to return a response.127+128+3. The return value of the view is then converted into an actual response129+ object and handed over to the :meth:`~flask.Flask.after_request`130+ functions which have the chance to replace it or modify it in place.131+132+4. At the end of the request the :meth:`~flask.Flask.teardown_request`133+ functions are executed. This always happens, even in case of an134+ unhandled exception down the road.135+136+Now what happens on errors? In production mode if an exception is not137+caught, the 500 internal server handler is called. In development mode138+however the exception is not further processed and bubbles up to the WSGI139+server. That way things like the interactive debugger can provide helpful140+debug information.141+142+An important change in 0.7 is that the internal server error is now no143+longer post processed by the after request callbacks and after request144+callbacks are no longer guaranteed to be executed. This way the internal145+dispatching code looks cleaner and is easier to customize and understand.146+147+The new teardown functions are supposed to be used as a replacement for148+things that absolutely need to happen at the end of request.149+150+Teardown Callbacks151+------------------152+153+The teardown callbacks are special callbacks in that they are executed at154+at different point. Strictly speaking they are independent of the actual155+request handling as they are bound to the lifecycle of the156+:class:`~flask.ctx.RequestContext` object. When the request context is157+popped, the :meth:`~flask.Flask.teardown_request` functions are called.158+159+This is important to know if the life of the request context is prolonged160+by using the test client in a with statement of when using the request161+context from the command line::162+163+ with app.test_client() as client:164+ resp = client.get('/foo')165+ # the teardown functions are still not called at that point166+ # even though the response ended and you have the response167+ # object in your hand168+169+ # only when the code reaches this point the teardown functions170+ # are called. Alternatively the same thing happens if another171+ # request was triggered from the test client172+173+It's easy to see the behavior from the command line:174+175+>>> app = Flask(__name__)176+>>> @app.teardown_request177+... def after_request(exception=None):178+... print 'after request'179+... 180+>>> ctx = app.test_request_context()181+>>> ctx.push()182+>>> ctx.pop()183+after request184+185+.. _notes-on-proxies:186+187+Notes On Proxies188+----------------189+190+Some of the objects provided by Flask are proxies to other objects. The191+reason behind this is that these proxies are shared between threads and192+they have to dispatch to the actual object bound to a thread behind the193+scenes as necessary.194+195+Most of the time you don't have to care about that, but there are some196+exceptions where it is good to know that this object is an actual proxy:197+198+- The proxy objects do not fake their inherited types, so if you want to199+ perform actual instance checks, you have to do that on the instance200+ that is being proxied (see `_get_current_object` below).201+- if the object reference is important (so for example for sending202+ :ref:`signals`)203+204+If you need to get access to the underlying object that is proxied, you205+can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::206+207+ app = current_app._get_current_object()208+ my_signal.send(app)209+210+Context Preservation on Error211+-----------------------------212+213+If an error occurs or not, at the end of the request the request context214+is popped and all data associated with it is destroyed. During215+development however that can be problematic as you might want to have the216+information around for a longer time in case an exception occurred. In217+Flask 0.6 and earlier in debug mode, if an exception occurred, the218+request context was not popped so that the interactive debugger can still219+provide you with important information.220+221+Starting with Flask 0.7 you have finer control over that behavior by222+setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By223+default it's linked to the setting of ``DEBUG``. If the application is in224+debug mode the context is preserved, in production mode it's not.225+226+Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode227+as it will cause your application to leak memory on exceptions. However228+it can be useful during development to get the same error preserving229+behavior as in development mode when attempting to debug an error that230+only occurs under production settings.modified:docs/shell.rst+24 added-41 removed
1+.. _shell:2+3 Working with the Shell4 ======================5 6 .. versionadded:: 0.315 unmodified lines22 that these functions are not only there for interactive shell usage, but23 also for unittesting and other situations that require a faked request24 context.25 24-Diving into Context Locals26+Generally it's recommended that you read the :ref:`request-context`27+chapter of the documentation first.28+29+Creating a Request Context30 --------------------------31 27-Say you have a utility function that returns the URL the user should be28-redirected to. Imagine it would always redirect to the URL's ``next``29-parameter or the HTTP referrer or the index page::32+The easiest way to create a proper request context from the shell is by33+using the :attr:`~flask.Flask.test_request_context` method which creates34+us a :class:`~flask.ctx.RequestContext`:35 31- from flask import request, url_for36+>>> ctx = app.test_request_context()37 33- def redirect_url():34- return request.args.get('next') or \35- request.referrer or \36- url_for('index')38+Normally you would use the `with` statement to make this request object39+active, but in the shell it's easier to use the40+:meth:`~flask.ctx.RequestContext.push` and41+:meth:`~flask.ctx.RequestContext.pop` methods by hand:42 38-As you can see, it accesses the request object. If you try to run this39-from a plain Python shell, this is the exception you will see:40-41->>> redirect_url()42-Traceback (most recent call last):43- File "<stdin>", line 1, in <module>44-AttributeError: 'NoneType' object has no attribute 'request'45-46-That makes a lot of sense because we currently do not have a request we47-could access. So we have to make a request and bind it to the current48-context. The :attr:`~flask.Flask.test_request_context` method can create49-us a request context:50-51->>> ctx = app.test_request_context('/?next=http://example.com/')52-53-This context can be used in two ways. Either with the `with` statement54-(which unfortunately is not very handy for shell sessions). The55-alternative way is to call the `push` and `pop` methods:56-43 >>> ctx.push()44 59-From that point onwards you can work with the request object:45+From that point onwards you can work with the request object until you46+call `pop`:47 61->>> redirect_url()62-u'http://example.com/'63-64-Until you call `pop`:65-48 >>> ctx.pop()67->>> redirect_url()68-Traceback (most recent call last):69- File "<stdin>", line 1, in <module>70-AttributeError: 'NoneType' object has no attribute 'request'49 72-50 Firing Before/After Request51 ---------------------------52 53 By just creating a request context, you still don't have run the code that77-is normally run before a request. This probably results in your database78-being unavailable, the current user not being stored on the54+is normally run before a request. This might result in your database55+being unavailable if you are connecting to the database in a56+before-request callback or the current user not being stored on the57 :data:`~flask.g` object etc.58 59 This however can easily be done yourself. Just call60 :meth:`~flask.Flask.preprocess_request`:12 unmodified lines73 >>> app.process_response(app.response_class())74 <Response 0 bytes [200 OK]>75 >>> ctx.pop()76 77+The functions registered as :meth:`~flask.Flask.teardown_request` are78+automatically called when the context is popped. So this is the perfect79+place to automatically tear down resources that were needed by the request80+context (such as database connections).81 82+83 Further Improving the Shell Experience84 --------------------------------------85 86 If you like the idea of experimenting in a shell, create yourself a module7 unmodified linesmodified:docs/signals.rst+16 added
234 unmodified lines235 236 from flask import got_request_exception237 got_request_exception.connect(log_exception, app)238 239+.. data:: flask.request_tearing_down240+ :noindex:241+242+ This signal is sent when the request is tearing down. This is always243+ called, even if an exception is caused. Currently functions listening244+ to this signal are called after the regular teardown handlers, but this245+ is not something you can rely on.246+247+ Example subscriber::248+249+ def close_db_connection(sender):250+ session.close()251+252+ from flask import request_tearing_down253+ request_tearing_down.connect(close_db_connection, app)254+255 .. _blinker: http://pypi.python.org/pypi/blinkermodified:flask/__init__.py+1 added-1 removed
26 unmodified lines27 from .session import Session28 29 # the signals30 from .signals import signals_available, template_rendered, request_started, \31- request_finished, got_request_exception31+ request_finished, got_request_exception, request_tearing_down32 33 # only import json if it's available34 if json_available:35 from .helpers import jsonmodified:flask/app.py+88 added-42 removed
25 unmodified lines26 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \27 _tojson_filter, _endpoint_from_view_func28 from .wrappers import Request, Response29 from .config import ConfigAttribute, Config30-from .ctx import _RequestContext30+from .ctx import RequestContext31 from .globals import _request_ctx_stack, request32 from .session import Session, _NullSession33 from .module import _ModuleSetupState34 from .templating import _DispatchingJinjaLoader, \35 _default_template_ctx_processor36-from .signals import request_started, request_finished, got_request_exception36+from .signals import request_started, request_finished, got_request_exception, \37+ request_tearing_down38 39 # a lock used for logger initialization40 _logger_lock = Lock()41 84 unmodified lines126 #: Flask extensions (and in the future probably also Flask itself).127 #: For example this might activate unittest helpers that have an128 #: additional runtime cost which should not be enabled by default.129 #:130+ #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the131+ #: default it's implicitly enabled.132+ #:133 #: This attribute can also be configured from the config with the134 #: `TESTING` configuration key. Defaults to `False`.135 testing = ConfigAttribute('TESTING')136 57 unmodified lines194 default_config = ImmutableDict({195 'DEBUG': False,196 'TESTING': False,197 'PROPAGATE_EXCEPTIONS': None,198+ 'PRESERVE_CONTEXT_ON_EXCEPTION': None,199 'SECRET_KEY': None,200 'SESSION_COOKIE_NAME': 'session',201 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),202 'USE_X_SENDFILE': False,136 unmodified lines339 return rv340 return self.testing or self.debug341 342 @property343+ def preserve_context_on_exception(self):344+ """Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`345+ configuration value in case it's set, otherwise a sensible default346+ is returned.347+348+ .. versionadded:: 0.7349+ """350+ rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']351+ if rv is not None:352+ return rv353+ return self.debug354+355+ @property356 def logger(self):357 """A :class:`logging.Logger` object for this application. The358 default configuration is to log to stderr if the application is359 in debug mode. This logger can be used to (surprise) log messages.370 unmodified lines730 self.before_request_funcs.setdefault(None, []).append(f)731 return f732 733 def after_request(self, f):716- """Register a function to be run after each request. Your function734+ """Register a function to be run after each request. Your function735 must take one parameter, a :attr:`response_class` object and return736 a new response object or the same (see :meth:`process_response`).737+738+ As of Flask 0.7 this function might not be executed at the end of the739+ request in case an unhandled exception ocurred.740 """741 self.after_request_funcs.setdefault(None, []).append(f)742 return f743 744 def teardown_request(self, f):745 """Register a function to be run at the end of each request,725- regardless of whether there was an exception or not.746+ regardless of whether there was an exception or not. These functions747+ are executed when the request context is popped, even if not an748+ actual request was performed.749+750+ Example::751+752+ ctx = app.test_request_context()753+ ctx.push()754+ ...755+ ctx.pop()756+757+ When ``ctx.pop()`` is executed in the above example, the teardown758+ functions are called just before the request context moves from the759+ stack of active contexts. This becomes relevant if you are using760+ such constructs in tests.761+762+ Generally teardown functions must take every necesary step to avoid763+ that they will fail. If they do execute code that might fail they764+ will have to surround the execution of these code by try/except765+ statements and log ocurring errors.766 """767 self.teardown_request_funcs.setdefault(None, []).append(f)768 return f769 39 unmodified lines809 """Does the request dispatching. Matches the URL and returns the810 return value of the view or error handler. This does not have to811 be a response object. In order to convert the return value to a812 proper response object, call :func:`make_response`.813+814+ .. versionchanged:: 0.7815+ This no longer does the exception handling, this code was816+ moved to the new :meth:`full_dispatch_request`.817 """818 req = _request_ctx_stack.top.request819+ if req.routing_exception is not None:820+ raise req.routing_exception821+ rule = req.url_rule822+ # if we provide automatic options for this URL and the823+ # request came with the OPTIONS method, reply automatically824+ if getattr(rule, 'provide_automatic_options', False) \825+ and req.method == 'OPTIONS':826+ return self.make_default_options_response()827+ # otherwise dispatch to the handler for that endpoint828+ return self.view_functions[rule.endpoint](**req.view_args)829+830+ def full_dispatch_request(self):831+ """Dispatches the request and on top of that performs request832+ pre and postprocessing as well as HTTP exception catching and833+ error handling.834+ """835 try:776- if req.routing_exception is not None:777- raise req.routing_exception778- rule = req.url_rule779- # if we provide automatic options for this URL and the780- # request came with the OPTIONS method, reply automatically781- if getattr(rule, 'provide_automatic_options', False) \782- and req.method == 'OPTIONS':783- return self.make_default_options_response()784- # otherwise dispatch to the handler for that endpoint785- return self.view_functions[rule.endpoint](**req.view_args)836+ request_started.send(self)837+ rv = self.preprocess_request()838+ if rv is None:839+ rv = self.dispatch_request()840 except HTTPException, e:787- return self.handle_http_exception(e)841+ rv = self.handle_http_exception(e)842+ response = self.make_response(rv)843+ response = self.process_response(response)844+ request_finished.send(self, response=response)845+ return response846 847 def make_default_options_response(self):848 """This method is called to create the default `OPTIONS` response.849 This can be changed through subclassing to change the default101 unmodified lines951 return response952 953 def do_teardown_request(self):954 """Called after the actual request dispatching and will897- call every as :meth:`teardown_request` decorated function.955+ call every as :meth:`teardown_request` decorated function. This is956+ not actually called by the :class:`Flask` object itself but is always957+ triggered when the request context is popped. That way we have a958+ tighter control over certain resources under testing environments.959 """960 funcs = reversed(self.teardown_request_funcs.get(None, ()))961 mod = request.module962 if mod and mod in self.teardown_request_funcs:2 unmodified lines965 for func in funcs:966 rv = func(exc)967 if rv is not None:968 return rv969+ request_tearing_down.send(self)970 971 def request_context(self, environ):910- """Creates a request context from the given environment and binds911- it to the current context. This must be used in combination with912- the `with` statement because the request is only bound to the913- current context for the duration of the `with` block.972+ """Creates a :class:`~flask.ctx.RequestContext` from the given973+ environment and binds it to the current context. This must be used in974+ combination with the `with` statement because the request is only bound975+ to the current context for the duration of the `with` block.976 977 Example usage::978 979 with app.request_context(environ):15 unmodified lines995 is now passed the ctx object.996 997 :param environ: a WSGI environment998 """937- return _RequestContext(self, environ)999+ return RequestContext(self, environ)1000 1001 def test_request_context(self, *args, **kwargs):1002 """Creates a WSGI environment from the given values (see1003 :func:`werkzeug.create_environ` for more information, this26 unmodified lines1030 1031 Then you still have the original application object around and1032 can continue to call methods on it.1033 972- .. versionchanged:: 0.4973- The :meth:`after_request` functions are now called even if an974- error handler took over request processing. This ensures that975- even if an exception happens database have the chance to976- properly close the connection.977-1034 .. versionchanged:: 0.7979- The :meth:`teardown_request` functions get called at the very end of980- processing the request. If an exception was thrown, it gets passed to981- each teardown_request function.1035+ The behavior of the before and after request callbacks was changed1036+ under error conditions and a new callback was added that will1037+ always execute at the end of the request, independent on if an1038+ error ocurred or not. See :ref:`callbacks-and-errors`.1039 1040 :param environ: a WSGI environment1041 :param start_response: a callable accepting a status code,1042 a list of headers and an optional1043 exception context to start the response1044 """1045 with self.request_context(environ):1046 try:990- request_started.send(self)991- rv = self.preprocess_request()992- if rv is None:993- rv = self.dispatch_request()994- response = self.make_response(rv)1047+ response = self.full_dispatch_request()1048 except Exception, e:1049 response = self.make_response(self.handle_exception(e))997- try:998- response = self.process_response(response)999- except Exception, e:1000- response = self.make_response(self.handle_exception(e))1001- finally:1002- self.do_teardown_request()1003- request_finished.send(self, response=response)1050 return response(environ, start_response)1051 1052 def __call__(self, environ, start_response):1053 """Shortcut for :attr:`wsgi_app`."""1 unmodified linemodified:flask/ctx.py+31 added-4 removed
49 unmodified lines50 """51 return _request_ctx_stack.top is not None52 53 54-class _RequestContext(object):54+class RequestContext(object):55 """The request context contains all request relevant information. It is56 created at the beginning of the request and pushed to the57 `_request_ctx_stack` and removed at the end of it. It will create the58 URL adapter and request object for the WSGI environment provided.59+60+ Do not attempt to use this class directly, instead use61+ :meth:`~flask.Flask.test_request_context` and62+ :meth:`~flask.Flask.request_context` to create this object.63+64+ When the request context is popped, it will evaluate all the65+ functions registered on the application for teardown execution66+ (:meth:`~flask.Flask.teardown_request`).67+68+ The request context is automatically popped at the end of the request69+ for you. In debug mode the request context is kept around if70+ exceptions happen so that interactive debuggers have a chance to71+ introspect the data. With 0.4 this can also be forced for requests72+ that did not fail and outside of `DEBUG` mode. By setting73+ ``'flask._preserve_context'`` to `True` on the WSGI environment the74+ context will not pop itself at the end of the request. This is used by75+ the :meth:`~flask.Flask.test_client` for example to implement the76+ deferred cleanup functionality.77+78+ You might find this helpful for unittests where you need the79+ information from the context local around for a little longer. Make80+ sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in81+ that situation, otherwise your unittests will leak memory.82 """83 84 def __init__(self, app, environ):85 self.app = app10 unmodified lines96 except HTTPException, e:97 self.request.routing_exception = e98 99 def push(self):77- """Binds the request context."""100+ """Binds the request context to the current context."""101 _request_ctx_stack.push(self)102 103 # Open the session at the moment that the request context is104 # available. This allows a custom open_session method to use the2 unmodified lines107 if self.session is None:108 self.session = _NullSession()109 110 def pop(self):88- """Pops the request context."""111+ """Pops the request context and unbinds it by doing that. This will112+ also trigger the execution of functions registered by the113+ :meth:`~flask.Flask.teardown_request` decorator.114+ """115+ self.app.do_teardown_request()116 _request_ctx_stack.pop()117 118 def __enter__(self):119 self.push()5 unmodified lines125 # access the request object in the interactive shell. Furthermore126 # the context can be force kept alive for the test client.127 # See flask.testing for how this works.128 if not self.request.environ.get('flask._preserve_context') and \102- (tb is None or not self.app.debug):129+ (tb is None or not self.app.preserve_context_on_exception):130 self.pop()modified:flask/signals.py+1 added
45 unmodified lines46 # the API documentation in docs/api.rst as well as docs/signals.rst47 template_rendered = _signals.signal('template-rendered')48 request_started = _signals.signal('request-started')49 request_finished = _signals.signal('request-finished')50+request_tearing_down = _signals.signal('request-tearing-down')51 got_request_exception = _signals.signal('got-request-exception')modified:tests/flask_tests.py+4 added-1 removed
782 unmodified lines783 t.join()784 785 def test_max_content_length(self):786 app = flask.Flask(__name__)787- app.debug = True787 app.config['MAX_CONTENT_LENGTH'] = 64788+ @app.before_request789+ def always_first():790+ flask.request.form['myfile']791+ assert False792 @app.route('/accept', methods=['POST'])793 def accept_file():794 flask.request.form['myfile']795 assert False826 unmodified lines