如何在请求* any *网页之前执行常用功能?

时间:2017-08-16 05:31:46

标签: python flask

让我们说我有以下

from flask import Flask, render_template
import config
import utils

app = Flask(__name__)

@app.route("/")
def index():
    # call utils.function_foo(app)
    return render_template("index.html")

@app.route("/about/")
def about():
    # call utils.function_foo(app)
    return render_template("about.html")

# ... more endpoint handling

if __name__ == "__main__":
    app.run(debug=True)

我想要做的是在每个路由功能有机会function_foo之前执行return

@app.before_request
def function_foo(app):
    # Something foo'ey.

不是解决方案,因为每次服务器获取任何 HTTP请求时都会调用function_foo

这意味着如果我请求 about 页面,并且它有30个图像,js文件,css文件等必须请求,那么function_foo将被调用31次在加载about页面之前。在这种情况下,我希望function_foo被调用一次,而不是31。

如果有人对此有所了解,那么我会非常感谢有关它的一些信息。

干杯!

1 个答案:

答案 0 :(得分:2)

如果你想在路线功能之前或之后调用一个函数,你可以编写自己的装饰器。

它接缝你不是真的想要那样:

  

我想要做的是在每个路由功能有机会返回之前执行function_foo

如果要在渲染之前调用function_foo,可以编写自己的渲染函数:

def my_rendering(*args, **kwargs):
    function_foo()
    return render_template(*args, **kwargs)
相关问题