Static files in Flask - robot.txt, sitemap.xml (mod_wsgi)


Is there any clever solution to store static files in Flask's application root directory. robots.txt and sitemap.xml are expected to be found in /, so my idea was to create routes for them:

@app.route('/sitemap.xml', methods=['GET'])
def sitemap():
  response = make_response(open('sitemap.xml').read())
  response.headers["Content-type"] = "text/plain"
  return response

There must be something more convenient :)

2/27/2019 12:25:48 PM

Accepted Answer

The best way is to set static_url_path to root url

from flask import Flask

app = Flask(__name__, static_folder='static', static_url_path='')
6/12/2013 7:22:19 PM

@vonPetrushev is right, in production you'll want to serve static files via nginx or apache, but for development it's nice to have your dev environment simple having your python app serving up the static content as well so you don't have to worry about changing configurations and multiple projects. To do that, you'll want to use the SharedDataMiddleware.

from flask import Flask
app = Flask(__name__)
Your app setup and code
if app.config['DEBUG']:
    from werkzeug import SharedDataMiddleware
    import os
    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
      '/': os.path.join(os.path.dirname(__file__), 'static')

This example assumes your static files are in the folder "static", adjust to whatever fits your environment.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow