Gunicorn Flask 缓存

Lon*_*olf 9 python mod-wsgi nginx flask gunicorn

我有一个使用 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 Code Online (Sandbox Code Playgroud)
  1. 现在,如果我在调试模式下运行服务器,run_dev数据库修改就会更新
  2. 如果run_server使用,除非重新启动应用程序,否则不会看到修改
  3. 但是,如果我像这样运行gunicorn -c a.py app:app,数据库更新是可见的。

a.py内容

import multiprocessing

bind = "0.0.0.0:5000"
workers = multiprocessing.cpu_count() * 2 + 1
Run Code Online (Sandbox Code Playgroud)

关于我遗漏的地方的任何建议..

小智 1

我曾经/正在看到同样的事情,只有当用烧瓶运行gunicorn时。一种解决方法是将 Gunicorn max-requests 设置为 1。但是,如果您有任何类型的负载,那么这不是真正的解决方案,因为在每个请求后重新启动工作线程会产生资源开销。我通过让 nginx 提供静态内容,然后更改我的 Flask 应用程序来渲染模板并写入静态,然后返回到静态文件的重定向来解决这个问题。