This question already has an answer here:
I've read on quiet a few places that serving static files should be left to the server, for example in a couple of the answers on this SO question. But I use the OpenShift PaaS, and can't figure out how to modify the .htaccess file there.
I came across this piece of code that serves the sitemap from a template. I did that on my app for both the sitemap, and robots.txt, like so -
@app.route("/sitemap.xml")
def sitemap_xml():
response= make_response(render_template("sitemap.xml"))
response.headers['Content-Type'] = 'application/xml'
return response
@app.route("/robots.txt")
def robots_txt():
return render_template("robots.txt")
Is there any harm in this, or is my approach okay?
The best way is to set static_url_path to root url
Put
robots.txt
andsitemap.xml
into your app'sstatic
directory and define this view:Flask has built in support for serving static files.
Make a
/static
directory and put your files there. Then, when you instantiateFlask
, specify thestatic_url_path
parameter:The default is to serve static files from the
/static/
path, but you want them served from/
so they are where expected.See the Flask API Docs for more info.
In addition to overhead and unnecessary code, the problem with your approach is if / when one of the files you want to serve contains something that looks like a template tag to
render_template
-- you can cause a rendering error. If you were to read the file into memory (once, not inside the method) then use that string as the body of the response without callingrender_template
, you would at least avoid that problem.