简体   繁体   中英

How to serve static file in Flask

I have a google verification file that I need to have in my root directory. How do I serve it and set up the route correctly in my app.py file? I thought just having it in the static directory would do the trick.

In my app.py file:

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:

 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; the second filename argument can take relative paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM