Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of decorators matter on a Flask view?

I'm using the login_required decorator and another decorator which paginates output data. Is it important which one comes first?

like image 237
shalbafzadeh Avatar asked Jan 28 '15 23:01

shalbafzadeh


People also ask

What order are decorators executed in Python?

During the definition, decorators are evaluated from bottom to top meanwhile during the execution (which is the most important part in general) they are evaluated from top to bottom.

How do decorators work in Flask?

Understanding Flask decoratorsA decorator is a function that takes in another function as a parameter and then returns a function. This is possible because Python gives functions special status. A function can be used as a parameter and a return value, while also being assigned to a variable.

Which of the following should be the outermost view decorator while working in Flask?

route should always be the outermost view decorator. Only an authenticated user will be able to access the /dashboard route. We can configure Flask-Login to redirect unauthenticated users to a login page, return an HTTP 401 status or anything else we'd like it to do with them.

Is decorators can be chained?

Multiple decorators can be chained in Python.


1 Answers

While there probably won't be any problem in this case no matter what the order, you probably want login_required to execute first so that you don't make queries and paginate results that will just get thrown away.

Decorators wrap the original function bottom to top, so when the function is called the wrapper added by each decorator executes top to bottom. @login_required should be below any other decorators that assume the user is logged in so that its condition is evaluated before those others.

@app.route() must always be the top, outermost decorator. Otherwise the route will be registered for a function that does not represent all the decorators.


The broader answer is that it depends on what each of the decorators are doing. You need to think about the flow of your program and whether it would make logical sense for one to come before the other.

like image 166
davidism Avatar answered Sep 17 '22 17:09

davidism