提问者:小点点

在Flask中启动应用程序之前无法初始化值


我玩了一点烧瓶,对于我的应用程序,我需要一个全局存储,由服务器上后台运行的线程更新。我发现这个关于全局上下文的问题,如果我显式地使用 /create初始化服务器,Johan Gov的答案似乎是有效的:

from flask import Flask
from flask.json import jsonify
app = Flask(__name__)

cache = {}

@app.route("/create")
def create():
    cache['foo'] = 0
    return jsonify(cache['foo'])

@app.route("/increment")
def increment():
    cache['foo'] = cache['foo'] + 1
    return jsonify(cache['foo'])

@app.route("/read")
def read():
    return jsonify(cache['foo'])

if __name__ == '__main__':
    app.run()

但是,如果我尝试自动调用init,它会失败,因为显然没有已知的缓存[“foo”]

from flask import Flask
from flask.json import jsonify
app = Flask(__name__)

cache = {}

def create():        #create does not have a route anymore
    cache['foo'] = 0

@app.route("/increment")
def increment():
    cache['foo'] = cache['foo'] + 1
    return jsonify(cache['foo'])

@app.route("/read")
def read():
    return jsonify(cache['foo'])

if __name__ == '__main__':
    create()    #initialize by default
    app.run()

为什么会这样?如何在启动应用程序之前初始化全局状态?


共2个答案

匿名用户

您可以将缓存用作应用程序属性,我总是在希望避免尴尬的全局定义时使用此属性,只需如下定义缓存:

# here u create a "cache" attribute for the app.
app.cache = {}
app.cache['foo'] = 0

# then after that when calling in a route:
# notice that we don't need the global keyword since we are using the app.
@app.route("/increment")
def increment():
    app.cache = app.cache + 1
    return jsonify(app.cache)

我甚至使用了相对较大的对象,比如使用这种方法的深度学习模型,并且没有任何问题。

匿名用户

Tbh,上面的代码为我工作,没有任何变化,我能够读取和增量计数器。

使用global变量尝试下面的代码

from flask import Flask
from flask.json import jsonify

app = Flask(__name__)

cache = {}


def create():  # create does not have a route anymore
    global cache
    cache['foo'] = 0


@app.route("/increment")
def increment():
    global cache
    cache['foo'] = cache['foo'] + 1
    return jsonify(cache['foo'])


@app.route("/read")
def read():
    return jsonify(cache['foo'])


if __name__ == '__main__':
    create()  # initialize by default
    app.run()