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


Solution 1:

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='')

Solution 2:

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

from flask import Flask, request, send_from_directory
app = 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:

Solution 3:

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

Solution 4:

Even though this is an old answered question, I'm answering this because this post comes up pretty high in the Google results. While it's not covered in the documentation, if you read the API docs for the Flask Application object constructor it's covered. By passing the named parameter static_folder like so:

from flask import Flask
app = Flask(__name__,
            static_folder="/path/to/static",
            template_folder="/path/to/templates")

...you can define where static files are served from. Similarly, you can define a template_folder, the name of you static_url_path.