【问题标题】:How to run Flask with Gunicorn and Varnish?如何使用 Gunicorn 和 Varnish 运行 Flask?
【发布时间】:2012-08-11 18:00:19
【问题描述】:

我正在使用 Flask 编写一个简单的 Web 应用程序,并将使用 Gunicorn 运行它。我想知道如何使用 Varnish 缓存此应用程序返回的页面。

通过关注this article,我已经能够将 Varnish 与同样在 Gunicorn 上运行的 Django 应用程序一起使用。说明包括使用一个额外的应用程序和一些中间件,但我不确定如何使用 Flask。

感谢您的建议!

【问题讨论】:

    标签: python caching flask varnish gunicorn


    【解决方案1】:

    基本上,您所要做的就是在渲染 Flask 视图时返回适当的缓存头。

    例如,这里有一个简单的视图,它呈现一个robots.txt 文件,并指定它应该被缓存30天:

    from flask import Flask, make_response, render_template
    app = Flask(__name__)
    @app.route('/robots.txt')
    def robots():
        response = make_response(render_template('robots.txt'))
        response.headers['Cache-Control'] = 'max-age=%d' % 60 * 60 * 24 * 30
        return response
    

    【讨论】:

    • 警告,如果你不想让 `"max-age=60" * 60 * 24 * 30 给出一个非常大的标题,你需要使用括号 'max-age=%d' % (60 * 60 * 24 * 30) ! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 2022-01-15
    • 1970-01-01
    • 2022-01-18
    • 2016-06-20
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多