Working with a global singleton in Flask (WSGI), do I have to worry about race conditions?

喜夏-厌秋 提交于 2019-12-03 07:53:03

问题


The hello world demo for Flask is:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

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

What if I modified this like so:

from flask import Flask
app = Flask(__name__)

a = 1
b = 2
c = 3

@app.route("/")
def hello():
    a += 1
    b += a
    c += b
    return "Hello World!"

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

I understand WSGI application might have multiple threads. The hello function could be running on multiple threads at the same time, and then we'd have a race condition. Is this correct? If the above code is not thread safe, what can I do to make it thread safe?

Avoiding globals is a possible solution, but can you always avoid globals? What if I want something like a python object cache?


回答1:


You could use a lock:

from threading import Lock
from flask import Flask
app = Flask(__name__)

a = 1
b = 2
c = 3
lock = Lock()

@app.route("/")
def hello():
    with lock:
        a += 1
        b += a
        c += b
    return "Hello World!"

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



回答2:


You could try the Local class from werkzeug. Here's some info about it: Context Locals

Example:

from flask import Flask
from werkzeug.local import Local
app = Flask(__name__)
loc = Local()
loc.a = 1
loc.b = 2
loc.c = 3

@app.route("/")
def hello():
    loc.a += 1
    loc.b += loc.a
    loc.c += loc.b
    return "Hello World!"

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



回答3:


You might take a look at the g object that you can import directly from flask, keeps an object globally for that request. If you're using an event driven WSGI server (tornado, gevent, etc) you shouldn't have any issues.



来源:https://stackoverflow.com/questions/10181706/working-with-a-global-singleton-in-flask-wsgi-do-i-have-to-worry-about-race-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!