[英]Gunicorn Flask Caching
我有一個使用 gunicorn 和 nginx 運行的 Flask 應用程序。 但是如果我更改數據庫中的值,應用程序在某些情況下無法在瀏覽器中更新。
我有一個具有以下命令的燒瓶腳本
from msldata import app, db, models
path = os.path.dirname(os.path.abspath(__file__))
manager = Manager(app)
@manager.command
def run_dev():
app.debug = True
if os.environ.get('PROFILE'):
from werkzeug.contrib.profiler import ProfilerMiddleware
app.config['PROFILE'] = True
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
if 'LISTEN_PORT' in app.config:
port = app.config['LISTEN_PORT']
else:
port = 5000
print app.config
app.run('0.0.0.0', port=port)
print app.config
@manager.command
def run_server():
from gunicorn.app.base import Application
from gunicorn.six import iteritems
# workers = multiprocessing.cpu_count() * 2 + 1
workers = 1
options = {
'bind': '0.0.0.0:5000',
}
class GunicornRunner(Application):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super(GunicornRunner, self).__init__()
def load_config(self):
config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value)
def load(self):
return self.application
GunicornRunner(app, options).run()
run_dev
,數據庫修改會更新run_server
除非重新啟動應用程序,否則不會看到修改gunicorn -c a.py app:app
一樣運行,則可以看到數據庫更新。a.py 內容
import multiprocessing
bind = "0.0.0.0:5000"
workers = multiprocessing.cpu_count() * 2 + 1
關於我遺漏了什么的任何建議..
我曾經/正在看到同樣的事情,只有在用燒瓶運行 gunicorn 時。 一種解決方法是將 Gunicorn max-requests 設置為 1。但是,如果由於每次請求后重新啟動工作程序的資源開銷,您有任何類型的負載,這不是一個真正的解決方案。 我通過讓 nginx 提供靜態內容,然后更改我的 Flask 應用程序以呈現模板並寫入靜態內容,然后將重定向返回到靜態文件來解決此問題。
我也遇到過這種情況。 在 Gunicorn 中與幾個工人一起運行燒瓶,燒瓶緩存將不再工作。
由於您已經在使用
app.config.from_object('default_config') (or similar filename)
只需將此添加到您的配置中:
CACHE_TYPE = "filesystem"
CACHE_THRESHOLD = 1000000 (some number your harddrive can manage)
CACHE_DIR = "/full/path/to/dedicated/cache/directory/"
我打賭你以前用過“simplecache”...
Flask-Caching
SimpleCache
不起作用 w。 工人 > 1 Gunicorn
使用版本 Flask 2.02 和 Flask-Caching 1.10.1 有類似問題。
在開發模式下一切正常,直到您使用超過 1 個工人的 gunicorn。 一個可能的原因是,在這種限制情況下, SimpleCache
在開發過程中只有一個進程/工作人員如此奇怪地工作。
我的代碼是:
app.config['CACHE_TYPE'] = 'SimpleCache' # a simple Python dictionary
app.config['SESSION_PERMANENT'] = False
cache = Cache(app)
Flask-Caching
解決方案使用FileSystemCache
,我現在的代碼:app.config['CACHE_TYPE'] = 'FileSystemCache'
app.config['CACHE_DIR'] = 'cache' # path to your server cache folder
app.config['CACHE_THRESHOLD'] = 100000 # number of 'files' before start auto-delete
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.