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
151 views
in Technique[技术] by (71.8m points)

python - can't initialize values before starting App in Flask

I'm playing with Flask a little, for my application I would require a global storage which is updated by a Thread running in the background on the server. I found this question about global context and the answer from Johan Gov seems to work if I init the server using /create explicitly:

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()

If I try to call the init automaticaly however, it fails as apparently no cache["foo"] is known.

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()

Why is this happening? How can I initialize global state before starting the Application?

question from:https://stackoverflow.com/questions/65858686/cant-initialize-values-before-starting-app-in-flask

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

1 Answer

0 votes
by (71.8m points)

You can use the Cache as your app property, i always use this when i want to avoid awkward global definitions, just define the cache like this:

# 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)

I even used relatively big objects like deep learning models using this method and had not problems at all.


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

...