Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call @app.before_request

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?

like image 423
Amin Avatar asked Jan 07 '13 06:01

Amin


People also ask

What does APP Before_request do?

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.

What is after_ request?

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.

What is before_ request in flask?

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.


1 Answers

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.

like image 121
Ignas Butėnas Avatar answered Sep 16 '22 20:09

Ignas Butėnas