【问题标题】:Python decorators and Flask routes: Can I decorate a function call or only a function definition?Python 装饰器和 Flask 路由:我可以装饰函数调用还是只装饰函数定义?
【发布时间】:2015-10-27 17:06:39
【问题描述】:

我有一个 Flask 路由:

@app.route('/')
def index():
    return render_template('index.html')

我可以在别处定义我的函数并装饰函数调用吗?

from module import index    

@app.route('/')
index()

我对装饰器没有基本的了解,我也不确定标准行为是否存在特定于 Flask 的内容,因此在此先感谢您的澄清。

【问题讨论】:

    标签: python flask routes decorator


    【解决方案1】:

    在这种情况下你不能装饰函数调用,但你可以定义需要调用的新函数:

    from module import index    
    
    @app.route('/')
    def new_index()
        return index()
    

    或者更简单,就像@JoranBeasley 建议的那样:

    app.route("/")(index)
    

    【讨论】:

    • 或只是app.route("/",index)
    • @JoranBeasley 如果路由有参数会是什么样子? app.route('/profile/<profile_id>/', 'profile', profile, profile_id) 之类的东西?
    • 不......就像正常的app.route('/profile/<profile_id>/',profile_fn)我有时会做一个做这种事情的urls.py......但后来我发现自己只是重新创建django......
    • 我认为应该是app.route("/")(index)app.add_url_rule("/", "index", index)
    猜你喜欢
    • 2020-05-20
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2017-01-15
    • 2014-07-21
    • 2018-03-07
    • 2020-04-28
    • 2011-06-06
    相关资源
    最近更新 更多