Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 534
biesiad Avatar asked Nov 21 '10 19:11

biesiad


2 Answers

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='')
like image 124
dns Avatar answered Oct 19 '22 21:10

dns


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:
like image 71
bebbi Avatar answered Oct 19 '22 20:10

bebbi