3

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.

davidism
  • 121,510
  • 29
  • 395
  • 339
muddyfish
  • 3,530
  • 30
  • 37

2 Answers2

6

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

davidism
  • 121,510
  • 29
  • 395
  • 339
4

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')
Adi Levin
  • 5,165
  • 1
  • 17
  • 26
  • 2
    See this discussion about ["infinite timeout"](http://stackoverflow.com/questions/17938711/how-can-i-configure-flask-cache-with-infinite-timeout) with Flask-Cache. – Jérôme Mar 25 '16 at 16:05