简体   繁体   中英

Generate a static page from a Jinja template and serve it with Flask

I want to create a page that once generated will remain static so my server doesn't waste resources regenerating content. I know about memoizing but was wondering if Flask provides a built-in or different method for this.

You can use Flask-Cache .

Start by creating the Cache instance:

from flask import Flask
from flask.ext.cache import Cache
application = Flask(__name__)
cache = Cache(application, config={'CACHE_TYPE': 'simple'})

Notice that the CACHE_TYPE = 'simple' uses a python dictionary for caching. Alternatively, you can use memcached or redis and get greater scalability. Or, you can use CACHE_TYPE = 'filesystem' and cache to the file system.

Then decorate your view functions:

@cache.cached(timeout=100000)
def viewfunc():
    return render_template('viewtemplate.html')

render_template produces a string. A string can be saved to a file. Flask can serve files .

# generate the page at some point
import os
out = render_template('page.html', one=2, cat='>dog')
with open(os.path.join(app.instance_path, 'page.html') as f:
    f.write(out)

# serve it some other time
from flask import send_from_directory
return send_from_directory(app.instance_path, 'page.html')

This example just puts the file in the instance folder (make sure that exists first) and hard codes the file name. In your real app I assume you would know where you want to save the files and what you want to call them.

If you find yourself doing this a lot, Flask-Cache will be a better choice, as it handles storing and loading the cached data for you and can save to more efficient backends (or the filesystem still).

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