Skip to content
Myr

request_init -> before_request and request_shutdown -> after_request

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

This fixes #9.

authored by Armin Ronacher · committed by Armin Ronacher · parent 7b50150 · Browse files · 6 files+30 added−29 removed
This commit

State

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

Diff stats

6 files+30 added−29 removed

  • tests:+2 added−2 removed
  • other:+28 added−27 removed

6 files+30 added−29 removed

modified:docs/patterns.rst+4 added-4 removed
9 unmodified lines
10request and get the information of the currently logged in user. At the11end of the request, the database connection is closed again.1213In Flask you can implement such things with the14:meth:`~flask.Flask.request_init` and15:meth:`~flask.Flask.request_shutdown` decorators in combination with the14:meth:`~flask.Flask.before_request` and15:meth:`~flask.Flask.after_request` decorators in combination with the16special :class:`~flask.g` object.171819.. _database-pattern:
10 unmodified lines
3031 def connect_db():32 return sqlite3.connect(DATABASE)3334 @app.request_init34 @app.before_request35 def before_request():36 g.db = connect_db()3738 @app.request_shutdown38 @app.after_request39 def after_request(response):40 g.db.close()41 return response42
210 unmodified lines
modified:docs/tutorial.rst+7 added-7 removed
223 unmodified lines
224but how can we elegantly do that for requests? We will need the database225connection in all our functions so it makes sense to initialize them226before each request and shut them down afterwards.227228Flask allows us to do that with the :meth:`~flask.Flask.request_init` and229:meth:`~flask.Flask.request_shutdown` decorators::228Flask allows us to do that with the :meth:`~flask.Flask.before_request` and229:meth:`~flask.Flask.after_request` decorators::230231 @app.request_init231 @app.before_request232 def before_request():233 g.db = connect_db()234235 @app.request_shutdown235 @app.after_request236 def after_request(response):237 g.db.close()238 return response239240Functions marked with :meth:`~flask.Flask.request_init` are called before240Functions marked with :meth:`~flask.Flask.before_request` are called before241a request and passed no arguments, functions marked with242:meth:`~flask.Flask.request_shutdown` are called after a request and242:meth:`~flask.Flask.after_request` are called after a request and243passed the response that will be sent to the client. They have to return244that response object or a different one. In this case we just return it245unchanged.246
7 unmodified lines
254Step 5: The View Functions255--------------------------256257Now that the database connections are working we can start writing the258view functions. We will need for of them:258view functions. We will need four of them:259260Show Entries261````````````262
222 unmodified lines
modified:examples/flaskr/flaskr.py+2 added-2 removed
39 unmodified lines
40 db.cursor().executescript(f.read())41 db.commit()424344@app.request_init44@app.before_request45def before_request():46 """Make sure we are connected to the database each request."""47 g.db = connect_db()484950@app.request_shutdown50@app.after_request51def after_request(response):52 """Closes the database again at the end of the request."""53 g.db.close()54 return response
44 unmodified lines
modified:examples/minitwit/minitwit.py+2 added-2 removed
67 unmodified lines
68 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \69 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)707172@app.request_init72@app.before_request73def before_request():74 """Make sure we are connected to the database each request and look75 up the current user so that we know he's there.76 """
3 unmodified lines
80 g.user = query_db('select * from user where user_id = ?',81 [session['user_id']], one=True)828384@app.request_shutdown84@app.after_request85def after_request(response):86 """Closes the database again at the end of the request."""87 g.db.close()88 return response
162 unmodified lines
modified:tests/flask_tests.py+2 added-2 removed
73 unmodified lines
7475 def test_request_processing(self):76 app = flask.Flask(__name__)77 evts = []78 @app.request_init78 @app.before_request79 def before_request():80 evts.append('before')81 @app.request_shutdown81 @app.after_request82 def after_request(response):83 response.data += '|after'84 evts.append('after')85 return response
103 unmodified lines
modified:flask.py+13 added-12 removed
247 unmodified lines
248 #: a list of functions that should be called at the beginning249 #: of the request before request dispatching kicks in. This250 #: can for example be used to open database connections or251 #: getting hold of the currently logged in user.252 #: To register a function here, use the :meth:`request_init`252 #: To register a function here, use the :meth:`before_request`253 #: decorator.254 self.request_init_funcs = []254 self.before_request_funcs = []255256 #: a list of functions that are called at the end of the257 #: request. Tha function is passed the current response258 #: object and modify it in place or replace it.259 #: To register a function here use the :meth:`request_shtdown`259 #: To register a function here use the :meth:`after_request`260 #: decorator.261 self.request_shutdown_funcs = []261 self.after_request_funcs = []262263 #: a list of functions that are called without arguments264 #: to populate the template context. Each returns a dictionary265 #: that the template context is updated with.
242 unmodified lines
508 self.error_handlers[code] = f509 return f510 return decorator511512 def request_init(self, f):512 def before_request(self, f):513 """Registers a function to run before each request."""514 self.request_init_funcs.append(f)514 self.before_request_funcs.append(f)515 return f516517 def request_shutdown(self, f):517 def after_request(self, f):518 """Register a function to be run after each request."""519 self.request_shutdown_funcs.append(f)519 self.after_request_funcs.append(f)520 return f521522 def context_processor(self, f):523 """Registers a template context processor function."""
58 unmodified lines
582 return self.response_class.force_type(rv, request.environ)583584 def preprocess_request(self):585 """Called before the actual request dispatching and will586 call every as :func:`request_init` decorated function.586 call every as :meth:`before_request` decorated function.587 If any of these function returns a value it's handled as588 if it was the return value from the view and further589 request handling is stopped.590 """591 for func in self.request_init_funcs:591 for func in self.before_request_funcs:592 rv = func()593 if rv is not None:594 return rv595596 def process_response(self, response):597 """Can be overridden in order to modify the response object598 before it's sent to the WSGI server.598 before it's sent to the WSGI server. By default this will599 call all the :meth:`after_request` decorated functions.600601 :param response: a :attr:`response_class` object.602 :return: a new response object or the same, has to be an603 instance of :attr:`response_class`.604 """605 session = _request_ctx_stack.top.session606 if session is not None:607 self.save_session(session, response)607 for handler in self.request_shutdown_funcs:608 for handler in self.after_request_funcs:609 response = handler(response)610 return response611612 def wsgi_app(self, environ, start_response):
51 unmodified lines