装饰器的顺序在Flask视图上是否重要? [英] Does the order of decorators matter on a Flask view?

查看:73
本文介绍了装饰器的顺序在Flask视图上是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用login_required装饰器和另一个对输出数据进行分页的装饰器.谁先出现重要吗?

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

推荐答案

尽管在这种情况下无论顺序如何都不会出现任何问题,但您可能希望login_required首先执行,这样就不会进行查询和分页的结果将被丢弃.

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.

装饰器将原始函数从下至上包装,因此,当调用该函数时,每个装饰器添加的包装器将从上到下执行. @login_required应该位于假定用户已登录的任何其他装饰器之下,以便其条件在其他装饰器之前评估.

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()必须始终是顶部,最外面的装饰器.否则,将为该路线注册一个不代表所有装饰器的功能.

@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.

这篇关于装饰器的顺序在Flask视图上是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆