如何在Flask中提供静态文件

如何在Flask中提供静态文件

所以这很尴尬。我有一个应用程序,我把它放在一起,Flask现在它只是提供一个静态HTML页面,其中包含一些CSS和JS的链接。我无法在文档Flask中找到返回静态文件的位置。是的,我可以使用,render_template但我知道数据没有模板化。我曾经想过send_file或者url_for是对的,但是我无法让它们发挥作用。与此同时,我正在打开文件,阅读内容,并Response使用适当的mimetype来装配:

import os.pathfrom flask import Flask, Responseapp = Flask(__name__)app.config.from_object(__name__)def root_dir():  # pragma: no cover
    return os.path.abspath(os.path.dirname(__file__))def get_file(filename):  # pragma: no cover
    try:
        src = os.path.join(root_dir(), filename)
        # Figure out how flask returns static files
        # Tried:
        # - render_template
        # - send_file
        # This should not be so non-obvious
        return open(src).read()
    except IOError as exc:
        return str(exc)@app.route('/', methods=['GET'])def metrics():  # pragma: no cover
    content = get_file('jenkins_analytics.html')
    return Response(content, mimetype="text/html")@app.route('/', defaults={'path': ''})@app.route('/<path:path>')def get_resource(path): 
     # pragma: no cover
    mimetypes = {
        ".css": "text/css",
        ".html": "text/html",
        ".js": "application/javascript",
    }
    complete_path = os.path.join(root_dir(), path)
    ext = os.path.splitext(path)[1]
    mimetype = mimetypes.get(ext, "text/html")
    content = get_file(complete_path)
    return Response(content, mimetype=mimetype)if __name__ == '__main__':  # pragma: no cover
    app.run(port=80)

有人想为此提供代码示例或网址吗?我知道这很简单。


慕村9548890
浏览 2671回答 4
4回答

12345678_0001

你也可以,这是我的最爱,将文件夹设置为静态路径,以便所有人都可以访问里面的文件。app&nbsp;=&nbsp;Flask(__name__,&nbsp;static_url_path='/static')使用该集,您可以使用标准HTML:<link&nbsp;rel="stylesheet"&nbsp;type="text/css"&nbsp;href="/static/style.css">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python