Browse Source

request_init -> before_request and request_shutdown -> after_request

This fixes #9.
pull/1638/head
Armin Ronacher 15 years ago
parent
commit
fb2d2e446b
  1. 8
      docs/patterns.rst
  2. 14
      docs/tutorial.rst
  3. 4
      examples/flaskr/flaskr.py
  4. 4
      examples/minitwit/minitwit.py
  5. 25
      flask.py
  6. 4
      tests/flask_tests.py

8
docs/patterns.rst

@ -11,8 +11,8 @@ request and get the information of the currently logged in user. At the
end of the request, the database connection is closed again. end of the request, the database connection is closed again.
In Flask you can implement such things with the In Flask you can implement such things with the
:meth:`~flask.Flask.request_init` and :meth:`~flask.Flask.before_request` and
:meth:`~flask.Flask.request_shutdown` decorators in combination with the :meth:`~flask.Flask.after_request` decorators in combination with the
special :class:`~flask.g` object. special :class:`~flask.g` object.
@ -31,11 +31,11 @@ So here a simple example how you can use SQLite 3 with Flask::
def connect_db(): def connect_db():
return sqlite3.connect(DATABASE) return sqlite3.connect(DATABASE)
@app.request_init @app.before_request
def before_request(): def before_request():
g.db = connect_db() g.db = connect_db()
@app.request_shutdown @app.after_request
def after_request(response): def after_request(response):
g.db.close() g.db.close()
return response return response

14
docs/tutorial.rst

@ -225,21 +225,21 @@ but how can we elegantly do that for requests? We will need the database
connection in all our functions so it makes sense to initialize them connection in all our functions so it makes sense to initialize them
before each request and shut them down afterwards. before each request and shut them down afterwards.
Flask allows us to do that with the :meth:`~flask.Flask.request_init` and Flask allows us to do that with the :meth:`~flask.Flask.before_request` and
:meth:`~flask.Flask.request_shutdown` decorators:: :meth:`~flask.Flask.after_request` decorators::
@app.request_init @app.before_request
def before_request(): def before_request():
g.db = connect_db() g.db = connect_db()
@app.request_shutdown @app.after_request
def after_request(response): def after_request(response):
g.db.close() g.db.close()
return response return response
Functions marked with :meth:`~flask.Flask.request_init` are called before Functions marked with :meth:`~flask.Flask.before_request` are called before
a request and passed no arguments, functions marked with a request and passed no arguments, functions marked with
:meth:`~flask.Flask.request_shutdown` are called after a request and :meth:`~flask.Flask.after_request` are called after a request and
passed the response that will be sent to the client. They have to return passed the response that will be sent to the client. They have to return
that response object or a different one. In this case we just return it that response object or a different one. In this case we just return it
unchanged. unchanged.
@ -255,7 +255,7 @@ Step 5: The View Functions
-------------------------- --------------------------
Now that the database connections are working we can start writing the Now that the database connections are working we can start writing the
view functions. We will need for of them: view functions. We will need four of them:
Show Entries Show Entries
```````````` ````````````

4
examples/flaskr/flaskr.py

@ -41,13 +41,13 @@ def init_db():
db.commit() db.commit()
@app.request_init @app.before_request
def before_request(): def before_request():
"""Make sure we are connected to the database each request.""" """Make sure we are connected to the database each request."""
g.db = connect_db() g.db = connect_db()
@app.request_shutdown @app.after_request
def after_request(response): def after_request(response):
"""Closes the database again at the end of the request.""" """Closes the database again at the end of the request."""
g.db.close() g.db.close()

4
examples/minitwit/minitwit.py

@ -69,7 +69,7 @@ def gravatar_url(email, size=80):
(md5(email.strip().lower().encode('utf-8')).hexdigest(), size) (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)
@app.request_init @app.before_request
def before_request(): def before_request():
"""Make sure we are connected to the database each request and look """Make sure we are connected to the database each request and look
up the current user so that we know he's there. up the current user so that we know he's there.
@ -81,7 +81,7 @@ def before_request():
[session['user_id']], one=True) [session['user_id']], one=True)
@app.request_shutdown @app.after_request
def after_request(response): def after_request(response):
"""Closes the database again at the end of the request.""" """Closes the database again at the end of the request."""
g.db.close() g.db.close()

25
flask.py

@ -249,16 +249,16 @@ class Flask(object):
#: of the request before request dispatching kicks in. This #: of the request before request dispatching kicks in. This
#: can for example be used to open database connections or #: can for example be used to open database connections or
#: getting hold of the currently logged in user. #: getting hold of the currently logged in user.
#: To register a function here, use the :meth:`request_init` #: To register a function here, use the :meth:`before_request`
#: decorator. #: decorator.
self.request_init_funcs = [] self.before_request_funcs = []
#: a list of functions that are called at the end of the #: a list of functions that are called at the end of the
#: request. Tha function is passed the current response #: request. Tha function is passed the current response
#: object and modify it in place or replace it. #: object and modify it in place or replace it.
#: To register a function here use the :meth:`request_shtdown` #: To register a function here use the :meth:`after_request`
#: decorator. #: decorator.
self.request_shutdown_funcs = [] self.after_request_funcs = []
#: a list of functions that are called without arguments #: a list of functions that are called without arguments
#: to populate the template context. Each returns a dictionary #: to populate the template context. Each returns a dictionary
@ -509,14 +509,14 @@ class Flask(object):
return f return f
return decorator return decorator
def request_init(self, f): def before_request(self, f):
"""Registers a function to run before each request.""" """Registers a function to run before each request."""
self.request_init_funcs.append(f) self.before_request_funcs.append(f)
return f return f
def request_shutdown(self, f): def after_request(self, f):
"""Register a function to be run after each request.""" """Register a function to be run after each request."""
self.request_shutdown_funcs.append(f) self.after_request_funcs.append(f)
return f return f
def context_processor(self, f): def context_processor(self, f):
@ -583,19 +583,20 @@ class Flask(object):
def preprocess_request(self): def preprocess_request(self):
"""Called before the actual request dispatching and will """Called before the actual request dispatching and will
call every as :func:`request_init` decorated function. call every as :meth:`before_request` decorated function.
If any of these function returns a value it's handled as If any of these function returns a value it's handled as
if it was the return value from the view and further if it was the return value from the view and further
request handling is stopped. request handling is stopped.
""" """
for func in self.request_init_funcs: for func in self.before_request_funcs:
rv = func() rv = func()
if rv is not None: if rv is not None:
return rv return rv
def process_response(self, response): def process_response(self, response):
"""Can be overridden in order to modify the response object """Can be overridden in order to modify the response object
before it's sent to the WSGI server. before it's sent to the WSGI server. By default this will
call all the :meth:`after_request` decorated functions.
:param response: a :attr:`response_class` object. :param response: a :attr:`response_class` object.
:return: a new response object or the same, has to be an :return: a new response object or the same, has to be an
@ -604,7 +605,7 @@ class Flask(object):
session = _request_ctx_stack.top.session session = _request_ctx_stack.top.session
if session is not None: if session is not None:
self.save_session(session, response) self.save_session(session, response)
for handler in self.request_shutdown_funcs: for handler in self.after_request_funcs:
response = handler(response) response = handler(response)
return response return response

4
tests/flask_tests.py

@ -75,10 +75,10 @@ class BasicFunctionality(unittest.TestCase):
def test_request_processing(self): def test_request_processing(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
evts = [] evts = []
@app.request_init @app.before_request
def before_request(): def before_request():
evts.append('before') evts.append('before')
@app.request_shutdown @app.after_request
def after_request(response): def after_request(response):
response.data += '|after' response.data += '|after'
evts.append('after') evts.append('after')

Loading…
Cancel
Save