[英]How to serve static file in Flask
I have a google verification file that I need to have in my root directory. 我的根目录中有一个Google验证文件。 How do I serve it and set up the route correctly in my app.py file? 我该如何提供服务并在我的app.py文件中正确设置路由? I thought just having it in the static directory would do the trick. 我认为仅将其放在静态目录中即可解决问题。
In my app.py file: 在我的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)
I've tried adding this but it didn't work: 我尝试添加它,但是没有用:
@app.route('/myfile.html')
def myfile():
return send_from_directory('/static', 'myfile.html')
For a one-off file that Google looks for in the root, I'd just add a specific route: 对于Google在根目录中查找的一次性文件,我只需添加一条特定路径:
from flask import send_from_directory
@app.route('/foobar_baz')
def google_check():
return send_from_directory(app.static_folder, 'foobar_baz')
You are free to add in test in show_page(path)
to try and serve path
with send_from_directory()
before you test for a template, of course; 您可以随意在show_page(path)
添加测试,以在测试模板之前尝试通过send_from_directory()
提供path
。 the second filename
argument can take relative paths. 第二个filename
参数可以采用相对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.