简体   繁体   中英

How to run Flask with Gunicorn and Varnish?

I'm writing a simple web application with Flask and will run it using Gunicorn. I'd like to know how to cache the pages returned by this application using Varnish.

I've been able to use Varnish with a Django application, also running on Gunicorn, by following this article . The instructions included using one extra application and some middleware, but I'm not sure how to do it with Flask.

Thanks for your suggestions!

Basically, all you have to do is return the appropriate cache headers when you render your Flask views.

For instance, here is a simple view which renders a robots.txt file, and specifies that it should be cached for 30 days:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM