muddyfish
muddyfish

Reputation: 3650

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.

Upvotes: 3

Views: 1509

Answers (2)

davidism
davidism

Reputation: 127180

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).

Upvotes: 6

Adi Levin
Adi Levin

Reputation: 5233

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')

Upvotes: 4

Related Questions