Skip to content
Myr

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

11 files+436 added−153 removed

modified:docs/api.rst+9 added-42 removed
308 unmodified lines
309310Useful Internals311----------------312313.. autoclass:: flask.ctx.RequestContext314 :members:315316.. data:: _request_ctx_stack317318 The internal :class:`~werkzeug.local.LocalStack` that is used to implement319 all the context local objects used in Flask. This is a documented
29 unmodified lines
349 ctx = _request_ctx_stack.top350 if ctx is not None:351 return ctx.session352350 .. versionchanged:: 0.4351352 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.361362 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.366353Signals354-------355356.. when modifying this list, also update the one in signals.rst
29 unmodified lines
386 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`.389390.. data:: request_tearing_down391392 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.395396.. currentmodule:: None397398.. class:: flask.signals.Namespace399
9 unmodified lines
409 do nothing but will fail with a :exc:`RuntimeError` for all other410 operations, including connecting.411412.. _blinker: http://pypi.python.org/pypi/blinker421422.. _notes-on-proxies:423424Notes On Proxies425----------------426427Some of the objects provided by Flask are proxies to other objects. The428reason behind this is that these proxies are shared between threads and429they have to dispatch to the actual object bound to a thread behind the430scenes as necessary.431432Most of the time you don't have to care about that, but there are some433exceptions where it is good to know that this object is an actual proxy:434435- 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`)440441If you need to get access to the underlying object that is proxied, you442can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::443444 app = current_app._get_current_object()445 my_signal.send(app)
modified:docs/config.rst+31 added-22 removed
49 unmodified lines
50The following configuration values are used internally by Flask:5152.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|5354=============================== =========================================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================================= =========================================8485.. admonition:: More on ``SERVER_NAME``8687 The ``SERVER_NAME`` key is used for the subdomain support. Because
22 unmodified lines
110.. versionadded:: 0.6111 ``MAX_CONTENT_LENGTH``112113.. versionadded:: 0.7105 ``PROPAGATE_EXCEPTIONS``114 ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``115116Configuring from Files117----------------------118
127 unmodified lines
modified:docs/contents.rst.inc+1 added
15 unmodified lines
16 testing17 errorhandling18 config19 signals20 reqcontext21 shell22 patterns/index23 deploying/index24 becomingbig
29 unmodified lines
added:docs/reqcontext.rst+230 added
1.. _request-context:23The Request Context4===================56This document describes the behavior in Flask 0.7 which is mostly in line7with the old behavior but has some small, subtle differences.89One of the design ideas behind Flask is that there are two different10“states” in which code is executed. The application setup state in which11the application implicitly is on the module level. It starts when the12:class:`Flask` object is instantiated, and it implicitly ends when the13first request comes in. While the application is in this state a few14assumptions are true:1516- 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.2122On the contrast, during request handling, a couple of other rules exist:2324- 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.2728The magic that makes this works is internally referred in Flask as the29“request context”.3031Diving into Context Locals32--------------------------3334Say you have a utility function that returns the URL the user should be35redirected to. Imagine it would always redirect to the URL's ``next``36parameter or the HTTP referrer or the index page::3738 from flask import request, url_for3940 def redirect_url():41 return request.args.get('next') or \42 request.referrer or \43 url_for('index')4445As you can see, it accesses the request object. If you try to run this46from a plain Python shell, this is the exception you will see:4748>>> redirect_url()49Traceback (most recent call last):50 File "<stdin>", line 1, in <module>51AttributeError: 'NoneType' object has no attribute 'request'5253That makes a lot of sense because we currently do not have a request we54could access. So we have to make a request and bind it to the current55context. The :attr:`~flask.Flask.test_request_context` method can create56us a :class:`~flask.ctx.RequestContext`:5758>>> ctx = app.test_request_context('/?next=http://example.com/')5960This context can be used in two ways. Either with the `with` statement61or by calling the :meth:`~flask.ctx.RequestContext.push` and62:meth:`~flask.ctx.RequestContext.pop` methods:6364>>> ctx.push()6566From that point onwards you can work with the request object:6768>>> redirect_url()69u'http://example.com/'7071Until you call `pop`:7273>>> ctx.pop()7475Because the request context is internally maintained as a stack you can76push and pop multiple times. This is very handy to implement things like77internal redirects.7879For more information of how to utilize the request context from the80interactive Python shell, head over to the :ref:`shell` chapter.8182How the Context Works83---------------------8485If you look into how the Flask WSGI application internally works, you will86find a piece of code that looks very much like this::8788 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)9596The method :meth:`~Flask.request_context` returns a new97:class:`~flask.ctx.RequestContext` object and uses it in combination with98the `with` statement to bind the context. Everything that is called from99the same thread from this point onwards until the end of the `with`100statement will have access to the request globals (:data:`flask.request`101and others).102103The request context internally works like a stack: The topmost level on104the stack is the current active request.105:meth:`~flask.ctx.RequestContext.push` adds the context to the stack on106the very top, :meth:`~flask.ctx.RequestContext.pop` removes it from the107stack again. On popping the application's108:func:`~flask.Flask.teardown_request` functions are also executed.109110.. _callbacks-and-errors:111112Callbacks and Errors113--------------------114115What happens if an error occurs in Flask during request processing? This116particular behavior changed in 0.7 because we wanted to make it easier to117understand what is actually happening. The new behavior is quite simple:1181191. 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.1231242. 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.1271283. 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.1311324. 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.135136Now what happens on errors? In production mode if an exception is not137caught, the 500 internal server handler is called. In development mode138however the exception is not further processed and bubbles up to the WSGI139server. That way things like the interactive debugger can provide helpful140debug information.141142An important change in 0.7 is that the internal server error is now no143longer post processed by the after request callbacks and after request144callbacks are no longer guaranteed to be executed. This way the internal145dispatching code looks cleaner and is easier to customize and understand.146147The new teardown functions are supposed to be used as a replacement for148things that absolutely need to happen at the end of request.149150Teardown Callbacks151------------------152153The teardown callbacks are special callbacks in that they are executed at154at different point. Strictly speaking they are independent of the actual155request handling as they are bound to the lifecycle of the156:class:`~flask.ctx.RequestContext` object. When the request context is157popped, the :meth:`~flask.Flask.teardown_request` functions are called.158159This is important to know if the life of the request context is prolonged160by using the test client in a with statement of when using the request161context from the command line::162163 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 hand168169 # 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 client172173It's easy to see the behavior from the command line:174175>>> 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()183after request184185.. _notes-on-proxies:186187Notes On Proxies188----------------189190Some of the objects provided by Flask are proxies to other objects. The191reason behind this is that these proxies are shared between threads and192they have to dispatch to the actual object bound to a thread behind the193scenes as necessary.194195Most of the time you don't have to care about that, but there are some196exceptions where it is good to know that this object is an actual proxy:197198- 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`)203204If you need to get access to the underlying object that is proxied, you205can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::206207 app = current_app._get_current_object()208 my_signal.send(app)209210Context Preservation on Error211-----------------------------212213If an error occurs or not, at the end of the request the request context214is popped and all data associated with it is destroyed. During215development however that can be problematic as you might want to have the216information around for a longer time in case an exception occurred. In217Flask 0.6 and earlier in debug mode, if an exception occurred, the218request context was not popped so that the interactive debugger can still219provide you with important information.220221Starting with Flask 0.7 you have finer control over that behavior by222setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By223default it's linked to the setting of ``DEBUG``. If the application is in224debug mode the context is preserved, in production mode it's not.225226Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode227as it will cause your application to leak memory on exceptions. However228it can be useful during development to get the same error preserving229behavior as in development mode when attempting to debug an error that230only occurs under production settings.
modified:docs/shell.rst+24 added-41 removed
1.. _shell:23Working with the Shell4======================56.. versionadded:: 0.3
15 unmodified lines
22that these functions are not only there for interactive shell usage, but23also for unittesting and other situations that require a faked request24context.2524Diving into Context Locals26Generally it's recommended that you read the :ref:`request-context`27chapter of the documentation first.2829Creating a Request Context30--------------------------3127Say you have a utility function that returns the URL the user should be28redirected to. Imagine it would always redirect to the URL's ``next``29parameter or the HTTP referrer or the index page::32The easiest way to create a proper request context from the shell is by33using the :attr:`~flask.Flask.test_request_context` method which creates34us a :class:`~flask.ctx.RequestContext`:3531 from flask import request, url_for36>>> ctx = app.test_request_context()3733 def redirect_url():34 return request.args.get('next') or \35 request.referrer or \36 url_for('index')38Normally you would use the `with` statement to make this request object39active, but in the shell it's easier to use the40:meth:`~flask.ctx.RequestContext.push` and41:meth:`~flask.ctx.RequestContext.pop` methods by hand:4238As you can see, it accesses the request object. If you try to run this39from a plain Python shell, this is the exception you will see:4041>>> redirect_url()42Traceback (most recent call last):43 File "<stdin>", line 1, in <module>44AttributeError: 'NoneType' object has no attribute 'request'4546That makes a lot of sense because we currently do not have a request we47could access. So we have to make a request and bind it to the current48context. The :attr:`~flask.Flask.test_request_context` method can create49us a request context:5051>>> ctx = app.test_request_context('/?next=http://example.com/')5253This context can be used in two ways. Either with the `with` statement54(which unfortunately is not very handy for shell sessions). The55alternative way is to call the `push` and `pop` methods:5643>>> ctx.push()4459From that point onwards you can work with the request object:45From that point onwards you can work with the request object until you46call `pop`:4761>>> redirect_url()62u'http://example.com/'6364Until you call `pop`:6548>>> ctx.pop()67>>> redirect_url()68Traceback (most recent call last):69 File "<stdin>", line 1, in <module>70AttributeError: 'NoneType' object has no attribute 'request'497250Firing Before/After Request51---------------------------5253By just creating a request context, you still don't have run the code that77is normally run before a request. This probably results in your database78being unavailable, the current user not being stored on the54is normally run before a request. This might result in your database55being unavailable if you are connecting to the database in a56before-request callback or the current user not being stored on the57:data:`~flask.g` object etc.5859This however can easily be done yourself. Just call60:meth:`~flask.Flask.preprocess_request`:
12 unmodified lines
73>>> app.process_response(app.response_class())74<Response 0 bytes [200 OK]>75>>> ctx.pop()7677The functions registered as :meth:`~flask.Flask.teardown_request` are78automatically called when the context is popped. So this is the perfect79place to automatically tear down resources that were needed by the request80context (such as database connections).818283Further Improving the Shell Experience84--------------------------------------8586If you like the idea of experimenting in a shell, create yourself a module
7 unmodified lines
modified:docs/signals.rst+16 added
234 unmodified lines
235236 from flask import got_request_exception237 got_request_exception.connect(log_exception, app)238239.. data:: flask.request_tearing_down240 :noindex:241242 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.246247 Example subscriber::248249 def close_db_connection(sender):250 session.close()251252 from flask import request_tearing_down253 request_tearing_down.connect(close_db_connection, app)254255.. _blinker: http://pypi.python.org/pypi/blinker
modified:flask/__init__.py+1 added-1 removed
26 unmodified lines
27from .session import Session2829# the signals30from .signals import signals_available, template_rendered, request_started, \31 request_finished, got_request_exception31 request_finished, got_request_exception, request_tearing_down3233# only import json if it's available34if json_available:35 from .helpers import json
modified:flask/app.py+88 added-42 removed
25 unmodified lines
26from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \27 _tojson_filter, _endpoint_from_view_func28from .wrappers import Request, Response29from .config import ConfigAttribute, Config30from .ctx import _RequestContext30from .ctx import RequestContext31from .globals import _request_ctx_stack, request32from .session import Session, _NullSession33from .module import _ModuleSetupState34from .templating import _DispatchingJinjaLoader, \35 _default_template_ctx_processor36from .signals import request_started, request_finished, got_request_exception36from .signals import request_started, request_finished, got_request_exception, \37 request_tearing_down3839# a lock used for logger initialization40_logger_lock = Lock()41
84 unmodified lines
126 #: 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 lines
194 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 lines
339 return rv340 return self.testing or self.debug341342 @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.347348 .. versionadded:: 0.7349 """350 rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']351 if rv is not None:352 return rv353 return self.debug354355 @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 lines
730 self.before_request_funcs.setdefault(None, []).append(f)731 return f732733 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`).737738 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 f743744 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.749750 Example::751752 ctx = app.test_request_context()753 ctx.push()754 ...755 ctx.pop()756757 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.761762 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 lines
809 """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`.813814 .. 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)829830 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 response846847 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 default
101 unmodified lines
951 return response952953 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 lines
965 for func in funcs:966 rv = func(exc)967 if rv is not None:968 return rv969 request_tearing_down.send(self)970971 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.976977 Example usage::978979 with app.request_context(environ):
15 unmodified lines
995 is now passed the ctx object.996997 :param environ: a WSGI environment998 """937 return _RequestContext(self, environ)999 return RequestContext(self, environ)10001001 def test_request_context(self, *args, **kwargs):1002 """Creates a WSGI environment from the given values (see1003 :func:`werkzeug.create_environ` for more information, this
26 unmodified lines
10301031 Then you still have the original application object around and1032 can continue to call methods on it.1033972 .. 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.9771034 .. 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`.10391040 :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)10511052 def __call__(self, environ, start_response):1053 """Shortcut for :attr:`wsgi_app`."""
1 unmodified line
modified:flask/ctx.py+31 added-4 removed
49 unmodified lines
50 """51 return _request_ctx_stack.top is not None525354class _RequestContext(object):54class 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.5960 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.6364 When the request context is popped, it will evaluate all the65 functions registered on the application for teardown execution66 (:meth:`~flask.Flask.teardown_request`).6768 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.7778 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 """8384 def __init__(self, app, environ):85 self.app = app
10 unmodified lines
96 except HTTPException, e:97 self.request.routing_exception = e9899 def push(self):77 """Binds the request context."""100 """Binds the request context to the current context."""101 _request_ctx_stack.push(self)102103 # Open the session at the moment that the request context is104 # available. This allows a custom open_session method to use the
2 unmodified lines
107 if self.session is None:108 self.session = _NullSession()109110 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()117118 def __enter__(self):119 self.push()
5 unmodified lines
125 # 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 lines
46# the API documentation in docs/api.rst as well as docs/signals.rst47template_rendered = _signals.signal('template-rendered')48request_started = _signals.signal('request-started')49request_finished = _signals.signal('request-finished')50request_tearing_down = _signals.signal('request-tearing-down')51got_request_exception = _signals.signal('got-request-exception')
modified:tests/flask_tests.py+4 added-1 removed
782 unmodified lines
783 t.join()784785 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 False
826 unmodified lines