With Flask, how can I serve robots.txt and sitemap.xml as static files? [duplicate]

拥有回忆 提交于 2019-11-29 23:01:09

Put robots.txt and sitemap.xml into your app's static directory and define this view:

from flask import Flask, request, send_from_directory

@app.route('/robots.txt')
@app.route('/sitemap.xml')
def static_from_root():
    return send_from_directory(app.static_folder, request.path[1:])
agf

Flask has built in support for serving static files.

Make a /static directory and put your files there. Then, when you instantiate Flask, specify the static_url_path parameter:

app = Flask(__name__, static_url_path='/')

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 calling render_template, you would at least avoid that problem.

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='')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!