我想使用 Flask 的 SimpleCahce 框架从后台进程设置缓存变量。即:
from rq import Queue
from worker import conn
from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()
app = Flask(__name__)
q = Queue(connection=conn)
# background process to be run. located in a seperate file
def test():
for i in range(10):
cache.set("value", i, 3600)
time.sleep(1)
@app.route('/')
def home():
cache.clear()
q.empty()
q.enqueue(test, timeout=1000)
return jsonify({'state':"running"})
@app.route('/current_value')
def get_value():
return jsonify({'value':cache.get("value")})
但是,这将始终返回 null
。我在使用 Redis 之前已经这样做了,但是在 SimpleCache 不允许的后台进程中设置缓存吗?还是我只是做错了什么?
最佳答案
Werkzeug's SimpleCache isn't thread safe.它不打算被其他线程或进程使用,因为它没有实现锁定。
此外,文档似乎暗示缓存存储在进程内存中,这使得从辅助进程更改主进程的缓存变得相当困难。
关于python - 在 Flask 中从后台进程设置缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36871643/