I'm using the login_required
decorator and another decorator which paginates output data. Is it important which one comes first?
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.
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.
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.
Multiple decorators can be chained in Python.
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.
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