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

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


The best way is to set static_url_path to root url

from flask import Flaskapp = Flask(__name__, static_folder='static', static_url_path='')


@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 Flaskapp = 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.


The cleanest answer to this question is the answer to this (identical) question:

from flask import Flask, request, send_from_directoryapp = Flask(__name__, static_folder='static')    @app.route('/robots.txt')@app.route('/sitemap.xml')def static_from_root():    return send_from_directory(app.static_folder, request.path[1:])

To summarize:

  • as David pointed out, with the right config it's ok to serve a few static files through prod
  • looking for /robots.txt shouldn't result in a redirect to /static/robots.txt. (In Seans answer it's not immediately clear how that's achieved.)
  • it's not clean to add static files into the app root folder
  • finally, the proposed solution looks much cleaner than the adding middleware approach: