Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...