如何在Flask中提供静态文件

时间:2014-04-29 14:35:06

标签: python flask

我有一个google验证文件,我需要在我的根目录中。如何在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 个答案:

答案 0 :(得分: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参数可以采用相对路径。