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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With