I have a simple flask app and I want to use @app.before_request, but somehow it does not work! I am sure I am not thinking correctly about this! apparently it will be called upon using something like:
return redirect(url_for('index'))
but i need it to be called for:
return render_template('index.html')
can anybody help?
The before_request decorator allows us to execute a function before any request. i.e, the function defined with the . before_request() decorator will execute before every request is made.
after_request(f) Register a function to run after each request to this object. The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent.
Before each request, before_request() functions are called. If one of these functions return a value, the other functions are skipped. The return value is treated as the response and the view function is not called.
If you would give some code maybe it will be better to understand your question, but if I understand it right you want to render template right before the request?
before_request
is used to call some function or do some action before the request. So basically it is for preparing your app to deal with the request which comes. Example: initialize database connection and put it in g
object for later access.
Example of before_request usage (like initialize DB for example) is:
@app.before_request
def before_request():
g.db = connect_db()
If you use it as @app.before_request
so it is decorator. Something more could be found in Flask docs
But another thing is why you want render_template
right before request? I think that you should render templates in the views not in this place. You let the request reach your app, your view and then render template there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With