Skip to content
Myr

Merge branch 'new-request-dispatching' into blueprints

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parents a4ea315, 086ecdb · Browse files · 28 files+689 added−266 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

28 files+689 added−266 removed

  • tests:+45 added−33 removed
  • other:+644 added−233 removed

28 files+689 added−266 removed

modified:docs/deploying/others.rst+1 added-1 removed
70 unmodified lines
71`HTTP_HOST`. Werkzeug ships a fixer that will solve some common setups,72but you might want to write your own WSGI middleware for specific setups.7374The most common setup invokes the host being set from `X-Forwarded-Host`75and the remote address from `X-Forward-For`::75and the remote address from `X-Forwarded-For`::7677 from werkzeug.contrib.fixers import ProxyFix78 app.wsgi_app = ProxyFix(app.wsgi_app)79
19 unmodified lines
modified:docs/patterns/fabric.rst+5 added-5 removed
30 unmodified lines
31hosts. These hosts can be defined either in the fabfile or on the command32line. In this case we will add them to the fabfile.3334This is a basic first example that has the ability to upload the current35sourcecode to the server and install it into a already existing35sourcecode to the server and install it into a pre-existing36virtual environment::3738 from fabric.api import *39
12 unmodified lines
52 # upload the source tarball to the temporary folder on the server53 put('dist/%s.tar.gz' % dist, '/tmp/yourapplication.tar.gz')54 # create a place where we can unzip the tarball, then enter55 # that directory and unzip it56 run('mkdir yourapplication')56 run('mkdir /tmp/yourapplication')57 with cd('/tmp/yourapplication'):58 run('tar xzf /tmp/yourapplication.tar.gz')59 # now setup the package with our virtual environment's60 # python interpreter61 run('/var/www/yourapplication/env/bin/python setup.py install')59 # now setup the package with our virtual environment's60 # python interpreter61 run('/var/www/yourapplication/env/bin/python setup.py install')62 # now that all is set up, delete the folder again63 run('rm -rf /tmp/yourapplication /tmp/yourapplication.tar.gz')64 # and finally touch the .wsgi file so that mod_wsgi triggers65 # a reload of the application
131 unmodified lines
modified:docs/patterns/packages.rst+1 added-1 removed
55 unmodified lines
56 `__name__` variable will resolve to the correct package.572. all the view functions (the ones with a :meth:`~flask.Flask.route`58 decorator on top) have to be imported when in the `__init__.py` file.59 Not the object itself, but the module it is in. Import the view module60 *after the application object is created*.60 **after the application object is created**.6162Here's an example `__init__.py`::6364 from flask import Flask
225 unmodified lines
modified:docs/patterns/sqlalchemy.rst+4 added-6 removed
63 unmodified lines
64automatically remove database sessions at the end of the request for you::6566 from yourapplication.database import db_session6768 @app.after_request69 def shutdown_session(response):68 @app.teardown_request69 def shutdown_session(exception=None):70 db_session.remove()71 return response7172Here is an example model (put this into `models.py`, e.g.)::7374 from sqlalchemy import Column, Integer, String
63 unmodified lines
138each request. Put this into your application module::139140 from yourapplication.database import db_session141143 @app.after_request144 def shutdown_session(response):142 @app.teardown_request143 def shutdown_session(exception=None):144 db_session.remove()146 return response145146Here is an example table and model (put this into `models.py`)::147148 from sqlalchemy import Table, Column, Integer, String
66 unmodified lines
modified:docs/patterns/sqlite3.rst+28 added-4 removed
3 unmodified lines
4=========================56In Flask you can implement the opening of database connections at the7beginning of the request and closing at the end with the8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`8:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.teardown_request`9decorators in combination with the special :class:`~flask.g` object.1011So here is a simple example of how you can use SQLite 3 with Flask::12
8 unmodified lines
21 @app.before_request22 def before_request():23 g.db = connect_db()2425 @app.after_request26 def after_request(response):25 @app.teardown_request26 def teardown_request(exception):27 g.db.close()28 return response2829Connect on Demand30-----------------3132The downside of this approach is that this will only work if Flask33executed the before-request handlers for you. If you are attempting to34use the database from a script or the interactive Python shell you would35have to do something like this::3637 with app.test_request_context()38 app.preprocess_request()39 # now you can use the g.db object4041In order to trigger the execution of the connection code. You won't be42able to drop the dependency on the request context this way, but you could43make it so that the application connects when necessary::4445 def get_connection():46 db = getattr(g, '_db', None)47 if db is None:48 db = g._db = connect_db()49 return db5051Downside here is that you have to use ``db = get_connection()`` instead of52just being able to use ``g.db`` directly.5354.. _easy-querying:5556Easy Querying57-------------
54 unmodified lines
modified:docs/tutorial/dbcon.rst+8 added-23 removed
7 unmodified lines
8connection in all our functions so it makes sense to initialize them9before each request and shut them down afterwards.1011Flask allows us to do that with the :meth:`~flask.Flask.before_request`,12:meth:`~flask.Flask.after_request` and :meth:`~flask.Flask.teardown_request`13decorators. In debug mode, if an error is raised,14:meth:`~flask.Flask.after_request` won't be run, and you'll have access to the15db connection in the interactive debugger::12:meth:`~flask.Flask.teardown_request` and :meth:`~flask.Flask.teardown_request`13decorators::1415 @app.before_request16 def before_request():17 g.db = connect_db()1821 @app.after_request22 def after_request(response):23 g.db.close()24 return response2526If you want to guarantee that the connection is always closed in debug mode, you27can close it in a function decorated with :meth:`~flask.Flask.teardown_request`:2829 @app.before_request30 def before_request():31 g.db = connect_db()3219 @app.teardown_request20 def teardown_request(exception):21 g.db.close()2223Functions marked with :meth:`~flask.Flask.before_request` are called before24a request and passed no arguments. Functions marked with39:meth:`~flask.Flask.after_request` are called after a request and25:meth:`~flask.Flask.teardown_request` are called after a request and26passed the response that will be sent to the client. They have to return41that response object or a different one. In this case we just return it42unchanged.4344Functions marked with :meth:`~flask.Flask.teardown_request` get called after the27that response object or a different one. They are however not guaranteed28to be executed if an exception is raised, this is where functions marked with29:meth:`~flask.Flask.teardown_request` come in. They get called after the30response has been constructed. They are not allowed to modify the request, and31their return values are ignored. If an exception occurred while the request was47being processed, it is passed to each function; otherwise, None is passed in.32being processed, it is passed to each function; otherwise, `None` is passed in.3334We store our current database connection on the special :data:`~flask.g`50object that flask provides for us. This object stores information for one35object that Flask provides for us. This object stores information for one36request only and is available from within each function. Never store such37things on other objects because this would not work with threaded38environments. That special :data:`~flask.g` object does some magic behind39the scenes to ensure it does the right thing.
2 unmodified lines
modified:docs/tutorial/setup.rst+8 added-1 removed
68 unmodified lines
69 if __name__ == '__main__':70 app.run()7172With that out of the way you should be able to start up the application73without problems. When you head over to the server you will get an 40473without problems. Do this with the following command::7475 python flaskr.py7677You will see a message telling you that server has started along with78the address at which you can access it.7980When you head over to the server in your browser you will get an 40481page not found error because we don't have any views yet. But we will82focus on that a little later. First we should get the database working.8384.. admonition:: Externally Visible Server
6 unmodified lines
modified:docs/api.rst+11 added-42 removed
242 unmodified lines
243.. autofunction:: send_file244245.. autofunction:: send_from_directory246247.. autofunction:: safe_join248249.. autofunction:: escape250251.. autoclass:: Markup252 :members: escape, unescape, striptags
56 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.session352348 .. versionchanged:: 0.4349350 The request context is automatically popped at the end of the request351 for you. In debug mode the request context is kept around if352 exceptions happen so that interactive debuggers have a chance to353 introspect the data. With 0.4 this can also be forced for requests354 that did not fail and outside of `DEBUG` mode. By setting355 ``'flask._preserve_context'`` to `True` on the WSGI environment the356 context will not pop itself at the end of the request. This is used by357 the :meth:`~flask.Flask.test_client` for example to implement the358 deferred cleanup functionality.359360 You might find this helpful for unittests where you need the361 information from the context local around for a little longer. Make362 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in363 that situation, otherwise your unittests will leak memory.364353Signals354-------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/blinker419420.. _notes-on-proxies:421422Notes On Proxies423----------------424425Some of the objects provided by Flask are proxies to other objects. The426reason behind this is that these proxies are shared between threads and427they have to dispatch to the actual object bound to a thread behind the428scenes as necessary.429430Most of the time you don't have to care about that, but there are some431exceptions where it is good to know that this object is an actual proxy:432433- The proxy objects do not fake their inherited types, so if you want to434 perform actual instance checks, you have to do that on the instance435 that is being proxied (see `_get_current_object` below).436- if the object reference is important (so for example for sending437 :ref:`signals`)438439If you need to get access to the underlying object that is proxied, you440can use the :meth:`~werkzeug.local.LocalProxy._get_current_object` method::441442 app = current_app._get_current_object()443 my_signal.send(app)
modified:docs/config.rst+33 added-23 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
120 unmodified lines
239 even create your own script for sourcing that activates a virtualenv240 and exports the development configuration for you.241- Use a tool like `fabric`_ in production to push code and242 configurations separately to the production server(s). For some234 details about how to do that, head over to the :ref:`deploy` pattern.243 details about how to do that, head over to the244 :ref:`fabric-deployment` pattern.245246.. _fabric: http://fabfile.org/
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
modified:docs/extensiondev.rst+28 added-7 removed
180 unmodified lines
181182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185 self.app.after_request(self.after_request)185 self.app.teardown_request(self.teardown_request)186 self.app.before_request(self.before_request)187188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])
1 unmodified line
191 def before_request(self):192 ctx = _request_ctx_stack.top193 ctx.sqlite3_db = self.connect()194195 def after_request(self, response):195 def teardown_request(self, exception):196 ctx = _request_ctx_stack.top197 ctx.sqlite3_db.close()198 return response198199 def get_db(self):200 ctx = _request_ctx_stack.top201 if ctx is not None:
7 unmodified lines
209 SQLite.2102. We create a class for our extension that requires a supplied `app` object,211 sets a configuration for the database if it's not there212 (:meth:`dict.setdefault`), and attaches `before_request` and214 `after_request` handlers.213 `teardown_request` handlers.2143. Next, we define a `connect` function that opens a database connection.2154. Then we set up the request handlers we bound to the app above. Note here216 that we're attaching our database connection to the top request context via217 `_request_ctx_stack.top`. Extensions should use the top context and not the
44 unmodified lines
262263 def init_app(self, app):264 self.app = app265 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')267 self.app.after_request(self.after_request)266 self.app.teardown_request(self.teardown_request)267 self.app.before_request(self.before_request)268269 def connect(self):270 return sqlite3.connect(app.config['SQLITE3_DATABASE'])
1 unmodified line
272 def before_request(self):273 ctx = _request_ctx_stack.top274 ctx.sqlite3_db = self.connect()275277 def after_request(self, response):276 def teardown_request(self, exception):277 ctx = _request_ctx_stack.top278 ctx.sqlite3_db.close()280 return response279280 def get_db(self):281 ctx = _request_ctx_stack.top282 if ctx is not None:
6 unmodified lines
289and bind their app to the extension in another file::290291 manager.init_app(app)292293End-Of-Request Behavior294-----------------------295296Due to the change in Flask 0.7 regarding functions that are run at the end297of the request your extension will have to be extra careful there if it298wants to continue to support older versions of Flask. The following299pattern is a good way to support both::300301 def close_connection(response):302 ctx = _request_ctx_stack.top303 ctx.sqlite3_db.close()304 return response305306 if hasattr(app, 'teardown_request'):307 app.teardown_request(close_connection)308 else:309 app.after_request(close_connection)310311Strictly speaking the above code is wrong, because teardown functions are312passed the exception and typically don't return anything. However because313the return value is discarded this will just work assuming that the code314in between does not touch the passed parameter.315316Learn from Others317-----------------318319This documentation only touches the bare minimum for extension
64 unmodified lines
modified:docs/quickstart.rst+5 added
111 unmodified lines
112 :align: center113 :class: screenshot114 :alt: screenshot of debugger in action115116.. admonition:: Working With Other Debuggers117118 Debuggers interfere with each other. If you are using another debugger119 (e.g. PyDev or IntelliJ), you may need to set ``app.debug = False``.120121122Routing123-------124125Modern web applications have beautiful URLs. This helps people remember
625 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:docs/upgrading.rst+47 added
20 unmodified lines
2122Version 0.723-----------2425The following backwards incompatible changes exist from 0.6 to 0.72627Bug in Request Locals28`````````````````````2930Due to a bug in earlier implementations the request local proxies now31raise a :exc:`RuntimeError` instead of an :exc:`AttributeError` when they32are unbound. If you caught these exceptions with :exc:`AttributeError`33before, you should catch them with :exc:`RuntimeError` now.
14 unmodified lines
48New code::4950 return send_file(my_file_object, add_etags=False)5152.. _upgrading-to-new-teardown-handling:5354Upgrading to new Teardown Handling55``````````````````````````````````5657We streamlined the behavior of the callbacks for request handling. For58things that modify the response the :meth:`~flask.Flask.after_request`59decorators continue to work as expected, but for things that absolutely60must happen at the end of request we introduced the new61:meth:`~flask.Flask.teardown_request` decorator. Unfortunately that62change also made after-request work differently under error conditions.63It's not consistently skipped if exceptions happen whereas previously it64might have been called twice to ensure it is executed at the end of the65request.6667If you have database connection code that looks like this::6869 @app.after_request70 def after_request(response):71 g.db.close()72 return response7374You are now encouraged to use this instead::7576 @app.teardown_request77 def after_request(exception):78 g.db.close()7980On the upside this change greatly improves the internal code flow and81makes it easier to customize the dispatching and error handling. This82makes it now a lot easier to write unit tests as you can prevent closing83down of database connections for a while. You can take advantage of the84fact that the teardown callbacks are called when the response context is85removed from the stack so a test can query the database after request86handling::8788 with app.test_client() as client:89 resp = client.get('/')90 # g.db is still bound if there is such a thing9192 # and here it's gone9394Version 0.695-----------9697Flask 0.6 comes with a backwards incompatible change which affects the
87 unmodified lines
modified:examples/flaskr/flaskr.py+2 added-3 removed
45 unmodified lines
46 """Make sure we are connected to the database each request."""47 g.db = connect_db()484950@app.after_request51def after_request(response):50@app.teardown_request51def teardown_request(exception):52 """Closes the database again at the end of the request."""53 g.db.close()54 return response545556@app.route('/')57def show_entries():
40 unmodified lines
modified:examples/minitwit/minitwit.py+2 added-3 removed
80 unmodified lines
81 g.user = query_db('select * from user where user_id = ?',82 [session['user_id']], one=True)838485@app.after_request86def after_request(response):85@app.teardown_request86def teardown_request(exception):87 """Closes the database again at the end of the request."""88 g.db.close()89 return response899091@app.route('/')92def timeline():
155 unmodified lines
modified:flask/__init__.py+2 added-2 removed
17 unmodified lines
18from .app import Flask, Request, Response19from .config import Config20from .helpers import url_for, jsonify, json_available, flash, \21 send_file, send_from_directory, get_flashed_messages, \22 get_template_attribute, make_response22 get_template_attribute, make_response, safe_join23from .globals import current_app, g, request, session, _request_ctx_stack24from .ctx import has_request_context25from .module import Module26from .templating import render_template, render_template_string27from .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+105 added-52 removed
23 unmodified lines
24from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25 locked_cached_property, _tojson_filter, _endpoint_from_view_func26from .wrappers import Request, Response27from .config import ConfigAttribute, Config28from .ctx import _RequestContext28from .ctx import RequestContext29from .globals import _request_ctx_stack, request30from .session import Session, _NullSession31from .module import _ModuleSetupState32from .templating import DispatchingJinjaLoader, Environment, \33 _default_template_ctx_processor34from .signals import request_started, request_finished, got_request_exception34from .signals import request_started, request_finished, got_request_exception, \35 request_tearing_down3637# a lock used for logger initialization38_logger_lock = Lock()39
84 unmodified lines
124 #: Flask extensions (and in the future probably also Flask itself).125 #: For example this might activate unittest helpers that have an126 #: additional runtime cost which should not be enabled by default.127 #:128 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the129 #: default it's implicitly enabled.130 #:131 #: This attribute can also be configured from the config with the132 #: `TESTING` configuration key. Defaults to `False`.133 testing = ConfigAttribute('TESTING')134
62 unmodified lines
197 default_config = ImmutableDict({198 'DEBUG': False,199 'TESTING': False,200 'PROPAGATE_EXCEPTIONS': None,201 'PRESERVE_CONTEXT_ON_EXCEPTION': None,202 'SECRET_KEY': None,203 'SESSION_COOKIE_NAME': 'session',204 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),205 'USE_X_SENDFILE': False,
138 unmodified lines
344 return rv345 return self.testing or self.debug346347 @property348 def preserve_context_on_exception(self):349 """Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`350 configuration value in case it's set, otherwise a sensible default351 is returned.352353 .. versionadded:: 0.7354 """355 rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']356 if rv is not None:357 return rv358 return self.debug359360 @property361 def logger(self):362 """A :class:`logging.Logger` object for this application. The363 default configuration is to log to stderr if the application is364 in debug mode. This logger can be used to (surprise) log messages.
423 unmodified lines
788 self.before_request_funcs.setdefault(None, []).append(f)789 return f790791 def after_request(self, f):774 """Register a function to be run after each request."""792 """Register a function to be run after each request. Your function793 must take one parameter, a :attr:`response_class` object and return794 a new response object or the same (see :meth:`process_response`).795796 As of Flask 0.7 this function might not be executed at the end of the797 request in case an unhandled exception ocurred.798 """799 self.after_request_funcs.setdefault(None, []).append(f)800 return f801802 def teardown_request(self, f):803 """Register a function to be run at the end of each request,780 regardless of whether there was an exception or not.804 regardless of whether there was an exception or not. These functions805 are executed when the request context is popped, even if not an806 actual request was performed.807808 Example::809810 ctx = app.test_request_context()811 ctx.push()812 ...813 ctx.pop()814815 When ``ctx.pop()`` is executed in the above example, the teardown816 functions are called just before the request context moves from the817 stack of active contexts. This becomes relevant if you are using818 such constructs in tests.819820 Generally teardown functions must take every necesary step to avoid821 that they will fail. If they do execute code that might fail they822 will have to surround the execution of these code by try/except823 statements and log ocurring errors.824 """825 self.teardown_request_funcs.setdefault(None, []).append(f)826 return f827
22 unmodified lines
850 exists, a default 500 internal server error message is displayed.851852 .. versionadded: 0.3853 """854 exc_type, exc_value, tb = sys.exc_info()855856 got_request_exception.send(self, exception=e)857 handler = self.error_handlers.get(500)858859 if self.propagate_exceptions:860 # if we want to repropagate the exception, we can attempt to861 # raise it with the whole traceback in case we can do that862 # (the function was actually called from the except part)863 # otherwise, we just raise the error again864 if exc_value is e:865 raise exc_type, exc_value, tb866 else:814 raise867 raise e868869 self.logger.exception('Exception on %s [%s]' % (870 request.path,871 request.method872 ))
5 unmodified lines
878 """Does the request dispatching. Matches the URL and returns the879 return value of the view or error handler. This does not have to880 be a response object. In order to convert the return value to a881 proper response object, call :func:`make_response`.882883 .. versionchanged:: 0.7884 This no longer does the exception handling, this code was885 moved to the new :meth:`full_dispatch_request`.886 """887 req = _request_ctx_stack.top.request888 if req.routing_exception is not None:889 raise req.routing_exception890 rule = req.url_rule891 # if we provide automatic options for this URL and the892 # request came with the OPTIONS method, reply automatically893 if getattr(rule, 'provide_automatic_options', False) \894 and req.method == 'OPTIONS':895 return self.make_default_options_response()896 # otherwise dispatch to the handler for that endpoint897 return self.view_functions[rule.endpoint](**req.view_args)898899 def full_dispatch_request(self):900 """Dispatches the request and on top of that performs request901 pre and postprocessing as well as HTTP exception catching and902 error handling.903904 .. versionadded:: 0.7905 """906 try:831 if req.routing_exception is not None:832 raise req.routing_exception833 rule = req.url_rule834 # if we provide automatic options for this URL and the835 # request came with the OPTIONS method, reply automatically836 if getattr(rule, 'provide_automatic_options', False) \837 and req.method == 'OPTIONS':838 return self.make_default_options_response()839 # otherwise dispatch to the handler for that endpoint840 return self.view_functions[rule.endpoint](**req.view_args)907 request_started.send(self)908 rv = self.preprocess_request()909 if rv is None:910 rv = self.dispatch_request()911 except HTTPException, e:842 return self.handle_http_exception(e)912 rv = self.handle_http_exception(e)913 response = self.make_response(rv)914 response = self.process_response(response)915 request_finished.send(self, response=response)916 return response917918 def make_default_options_response(self):919 """This method is called to create the default `OPTIONS` response.920 This can be changed through subclassing to change the default
101 unmodified lines
1022 return response10231024 def do_teardown_request(self):1025 """Called after the actual request dispatching and will952 call every as :meth:`teardown_request` decorated function.1026 call every as :meth:`teardown_request` decorated function. This is1027 not actually called by the :class:`Flask` object itself but is always1028 triggered when the request context is popped. That way we have a1029 tighter control over certain resources under testing environments.1030 """1031 funcs = reversed(self.teardown_request_funcs.get(None, ()))1032 mod = request.module1033 if mod and mod in self.teardown_request_funcs:
2 unmodified lines
1036 for func in funcs:1037 rv = func(exc)1038 if rv is not None:1039 return rv1040 request_tearing_down.send(self)10411042 def request_context(self, environ):965 """Creates a request context from the given environment and binds966 it to the current context. This must be used in combination with967 the `with` statement because the request is only bound to the968 current context for the duration of the `with` block.1043 """Creates a :class:`~flask.ctx.RequestContext` from the given1044 environment and binds it to the current context. This must be used in1045 combination with the `with` statement because the request is only bound1046 to the current context for the duration of the `with` block.10471048 Example usage::10491050 with app.request_context(environ):
9 unmodified lines
1060 do_something_with(request)1061 finally:1062 ctx.pop()1063986 The big advantage of this approach is that you can use it without987 the try/finally statement in a shell for interactive testing:988989 >>> ctx = app.test_request_context()990 >>> ctx.bind()991 >>> request.path992 u'/'993 >>> ctx.unbind()9941064 .. versionchanged:: 0.31065 Added support for non-with statement usage and `with` statement1066 is now passed the ctx object.10671068 :param environ: a WSGI environment1069 """1001 return _RequestContext(self, environ)1070 return RequestContext(self, environ)10711072 def test_request_context(self, *args, **kwargs):1073 """Creates a WSGI environment from the given values (see1074 :func:`werkzeug.create_environ` for more information, this
26 unmodified lines
11011102 Then you still have the original application object around and1103 can continue to call methods on it.11041036 .. versionchanged:: 0.41037 The :meth:`after_request` functions are now called even if an1038 error handler took over request processing. This ensures that1039 even if an exception happens database have the chance to1040 properly close the connection.10411105 .. versionchanged:: 0.71043 The :meth:`teardown_request` functions get called at the very end of1044 processing the request. If an exception was thrown, it gets passed to1045 each teardown_request function.1106 The behavior of the before and after request callbacks was changed1107 under error conditions and a new callback was added that will1108 always execute at the end of the request, independent on if an1109 error ocurred or not. See :ref:`callbacks-and-errors`.11101111 :param environ: a WSGI environment1112 :param start_response: a callable accepting a status code,1113 a list of headers and an optional1114 exception context to start the response1115 """1116 with self.request_context(environ):1117 try:1054 request_started.send(self)1055 rv = self.preprocess_request()1056 if rv is None:1057 rv = self.dispatch_request()1058 response = self.make_response(rv)1118 response = self.full_dispatch_request()1119 except Exception, e:1120 response = self.make_response(self.handle_exception(e))1061 try:1062 response = self.process_response(response)1063 except Exception, e:1064 response = self.make_response(self.handle_exception(e))1065 finally:1066 self.do_teardown_request()1067 request_finished.send(self, response=response)1121 return response(environ, start_response)11221123 def __call__(self, environ, start_response):1124 """Shortcut for :attr:`wsgi_app`."""
1 unmodified line
modified:flask/config.py+2 added-2 removed
139 unmodified lines
140 - an actual object reference: that object is used directly141142 Objects are usually either modules or classes.143144 Just the uppercase variables in that object are stored in the config145 after lowercasing. Example usage::144 Just the uppercase variables in that object are stored in the config.145 Example usage::146147 app.config.from_object('yourapplication.default_config')148 from yourapplication import default_config149 app.config.from_object(default_config)
16 unmodified lines
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/helpers.py+31 added-10 removed
169 unmodified lines
170 any ``'admin.index'`` `index` of the `admin` module171 ==================== ======================= =============================172173 Variable arguments that are unknown to the target endpoint are appended174 to the generated URL as query arguments.174 to the generated URL as query arguments. If the value of a query argument175 is `None`, the whole pair is skipped.176177 For more information, head over to the :ref:`Quickstart <url-building>`.178179 :param endpoint: the endpoint of the URL (name of the function)
73 unmodified lines
253 :param with_categories: set to `True` to also receive categories.254 """255 flashes = _request_ctx_stack.top.flashes256 if flashes is None:256 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])257 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \258 if '_flashes' in session else []259 if not with_categories:260 return [x[1] for x in flashes]261 return flashes262
64 unmodified lines
327 # removed in Flask 1.0328 if not attachment_filename and not mimetype \329 and isinstance(filename, basestring):330 warn(DeprecationWarning('The filename support for file objects '329 'passed to send_file is not deprecated. Pass an '331 'passed to send_file is now deprecated. Pass an '332 'attach_filename if you want mimetypes to be guessed.'),333 stacklevel=2)334 if add_etags:335 warn(DeprecationWarning('In future flask releases etags will no '
58 unmodified lines
394 rv.headers.pop('x-sendfile', None)395 return rv396397398def safe_join(directory, filename):399 """Safely join `directory` and `filename`.400401 Example usage::402403 @app.route('/wiki/<path:filename>')404 def wiki_page(filename):405 filename = safe_join(app.config['WIKI_FOLDER'], filename)406 with open(filename, 'rb') as fd:407 content = fd.read() # Read and process the file content...408409 :param directory: the base directory.410 :param filename: the untrusted filename relative to that directory.411 :raises: :class:`~werkzeug.exceptions.NotFound` if the retsulting path412 would fall out of `directory`.413 """414 filename = posixpath.normpath(filename)415 for sep in _os_alt_seps:416 if sep in filename:417 raise NotFound()418 if os.path.isabs(filename) or filename.startswith('../'):419 raise NotFound()420 return os.path.join(directory, filename)421422423def send_from_directory(directory, filename, **options):424 """Send a file from a given directory with :func:`send_file`. This425 is a secure way to quickly expose static files from an upload folder426 or something similar.
19 unmodified lines
446 download.447 :param options: optional keyword arguments that are directly448 forwarded to :func:`send_file`.449 """423 filename = posixpath.normpath(filename)424 for sep in _os_alt_seps:425 if sep in filename:426 raise NotFound()427 if os.path.isabs(filename) or filename.startswith('../'):428 raise NotFound()429 filename = os.path.join(directory, filename)450 filename = safe_join(directory, filename)451 if not os.path.isfile(filename):452 raise NotFound()453 return send_file(filename, conditional=True, **options)454
94 unmodified lines
modified:flask/logging.py+2 added-1 removed
9 unmodified lines
10"""1112from __future__ import absolute_import1314from logging import getLogger, StreamHandler, Formatter, Logger, DEBUG14from logging import getLogger, StreamHandler, Formatter, getLoggerClass, DEBUG151617def create_logger(app):18 """Creates a logger for the given application. This logger works
1 unmodified line
20 level based on the application's debug flag. Furthermore this21 function also removes all attached handlers in case there was a22 logger with the log name before.23 """24 Logger = getLoggerClass()2526 class DebugLogger(Logger):27 def getEffectiveLevel(x):28 return DEBUG if app.debug else Logger.getEffectiveLevel(x)
15 unmodified lines
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:flask/wrappers.py+7 added-1 removed
79 unmodified lines
80 """81 if __debug__:82 _assert_have_json()83 if self.mimetype == 'application/json':84 request_charset = self.mimetype_params.get('charset')85 if request_charset is not None:86 j = json.loads(self.data, encoding=request_charset )87 else:84 return json.loads(self.data)88 j = json.loads(self.data)8990 return j919293class Response(ResponseBase):94 """The response object that is used by default in Flask. Works like the95 response object from Werkzeug but is set to have an HTML mimetype by96 default. Quite often you don't have to create this object yourself because
6 unmodified lines
modified:tests/flask_tests.py+45 added-33 removed
413 unmodified lines
414 rv = app.test_client().get('/').data415 assert 'after' in evts416 assert rv == 'request|after'417418 def test_after_request_errors(self):419 app = flask.Flask(__name__)420 called = []421 @app.after_request422 def after_request(response):423 called.append(True)424 return response425 @app.route('/')426 def fails():427 1/0428 rv = app.test_client().get('/')429 assert rv.status_code == 500430 assert 'Internal Server Error' in rv.data431 assert len(called) == 1432433 def test_after_request_handler_error(self):434 called = []435 app = flask.Flask(__name__)436 @app.after_request437 def after_request(response):438 called.append(True)439 1/0440 return response441 @app.route('/')442 def fails():443 1/0444 rv = app.test_client().get('/')445 assert rv.status_code == 500446 assert 'Internal Server Error' in rv.data447 assert len(called) == 1448418 def test_teardown_request_handler(self):419 called = []420 app = flask.Flask(__name__)421 @app.teardown_request
23 unmodified lines
445 assert rv.status_code == 200446 assert 'Response' in rv.data447 assert len(called) == 1448480449 def test_teardown_request_handler_error(self):450 called = []451 app = flask.Flask(__name__)452 @app.teardown_request
25 unmodified lines
478 assert rv.status_code == 500479 assert 'Internal Server Error' in rv.data480 assert len(called) == 2481514482 def test_before_after_request_order(self):483 called = []484 app = flask.Flask(__name__)485 @app.before_request
44 unmodified lines
530 rv = c.get('/error')531 assert rv.status_code == 500532 assert 'internal server error' == rv.data533534 def test_teardown_on_pop(self):535 buffer = []536 app = flask.Flask(__name__)537 @app.teardown_request538 def end_of_request(exception):539 buffer.append(exception)540541 ctx = app.test_request_context()542 ctx.push()543 assert buffer == []544 ctx.pop()545 assert buffer == [None]546547 def test_response_creation(self):548 app = flask.Flask(__name__)549 @app.route('/unicode')550 def from_unicode():
87 unmodified lines
638 app = flask.Flask(__name__)639 app.config.update(640 SERVER_NAME='localhost.localdomain:5000'641 )642643 @app.route('/')644 def index():645 return None646
131 unmodified lines
778 t = Thread(target=apprunner, args=(config_key,))779 t.start()780 t.join()781782 def test_max_content_length(self):783 app = flask.Flask(__name__)784 app.config['MAX_CONTENT_LENGTH'] = 64785 @app.before_request786 def always_first():787 flask.request.form['myfile']788 assert False789 @app.route('/accept', methods=['POST'])790 def accept_file():791 flask.request.form['myfile']792 assert False793 @app.errorhandler(413)794 def catcher(error):795 return '42'796797 c = app.test_client()798 rv = c.post('/accept', data={'myfile': 'foo' * 100})799 assert rv.data == '42'800801802class JSONTestCase(unittest.TestCase):803804 def test_json_body_encoding(self):805 app = flask.Flask(__name__)806 app.debug = True807 @app.route('/')808 def index():809 return flask.request.json810811 c = app.test_client()812 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),813 content_type='application/json; charset=iso-8859-15')814 assert resp.data == u'Hällo Wörld'.encode('utf-8')815816 def test_jsonify(self):817 d = dict(a=23, b=42, c=[1, 2, 3])818 app = flask.Flask(__name__)819 @app.route('/kw')
829 unmodified lines
modified:CHANGES+9 added-1 removed
36 unmodified lines
37 was incorrectly introduced in 0.6.38- Added `create_jinja_loader` to override the loader creation process.39- Implemented a silent flag for `config.from_pyfile`.40- Added `teardown_request` decorator, for functions that should run at the end41 of a request regardless of whether an exception occurred.41 of a request regardless of whether an exception occurred. Also the behavior42 for `after_request` was changed. It's now no longer executed when an exception43 is raised. See :ref:`upgrading-to-new-teardown-handling`44- Implemented :func:`flask.has_request_context`45- Deprecated `init_jinja_globals`. Override the46 :meth:`~flask.Flask.create_jinja_environment` method instead to47 achieve the same functionality.48- Added :func:`safe_join`49- The automatic JSON request data unpacking now looks at the charset50 mimetype parameter.51- Don't modify the session on :func:`flask.get_flashed_messages` if there52 are no messages in the session.53- `before_request` handlers are now able to abort requests with errors.5455Version 0.6.156-------------57
159 unmodified lines