如何在Flask中提供静态文件
我有一个谷歌验证文件,需要把它放在我的根目录里。请问我该怎么在我的app.py文件中正确地提供这个文件并设置路径呢?我原以为只要把它放在静态目录里就可以了。
在我的app.py文件中:
import requests; requests = requests.session()
from flask import (
Flask,
g,
session,
request,
render_template,
abort,
json,
jsonify,
make_response
)
from jinja2 import TemplateNotFound
app = Flask(__name__)
...
@app.route('/ping')
def ping():
return "OK"
"""
Catch-All Route
first looks for templates in /templates/pages
then looks in /templates
finally renders 404.html with 404 status
"""
@app.route('/', defaults={'path': 'index'})
@app.route('/<path:path>')
def show_page(path):
if session.get('tracking_url'):
session['session_url'] = False
templates = [t.format(path=path) for t in 'pages/{path}.html', '{path}.html']
g.path = path
try:
return render_template(templates, **site_variables(path))
except TemplateNotFound:
return render_template('404.html', **site_variables(path)), 404
application = app
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
我尝试添加了这个,但没有成功:
@app.route('/myfile.html')
def myfile():
return send_from_directory('/static', 'myfile.html')
1 个回答
1
如果你有一个一次性的文件,Google会在根目录下查找这个文件,我建议你添加一个特定的路由:
from flask import send_from_directory
@app.route('/foobar_baz')
def google_check():
return send_from_directory(app.static_folder, 'foobar_baz')
在show_page(path)
里面,你可以自由地添加测试代码,试着用send_from_directory()
来提供path
,然后再去检查模板,当然,第二个filename
参数可以使用相对路径。