如何在 Flask 中提供静态文件 [英] How to serve static files in Flask

查看:36
本文介绍了如何在 Flask 中提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这很尴尬.我有一个应用程序,我把它放在 Flask 中,现在它只是提供一个单一的静态 HTML 页面,其中包含一些指向 CSS 和 JS 的链接.而且我在文档 Flask 中找不到描述返回静态文件的地方.是的,我可以使用 render_template 但我知道数据不是模板化的.我原以为 send_fileurl_for 是正确的,但我无法让它们工作.与此同时,我正在打开文件,阅读内容,并使用适当的 mimetype 设置 Response:

So this is embarrassing. I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation Flask describes returning static files. Yes, I could use render_template but I know the data is not templatized. I'd have thought send_file or url_for was the right thing, but I could not get those to work. In the meantime, I am opening the files, reading content, and rigging up a Response with appropriate mimetype:

import os.path

from flask import Flask, Response


app = 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)

有人想为此提供代码示例或网址吗?我知道这将非常简单.

Someone want to give a code sample or url for this? I know this is going to be dead simple.

推荐答案

首选方法是使用 NGINX 或其他 Web 服务器来提供静态文件;他们将能够比 Flask 更有效地做到这一点.

The preferred method is to use NGINX or another web server to serve static files; they'll be able to do it more efficiently than Flask.

但是,您可以使用 send_from_directory 从目录发送文件,这在某些情况下非常方便:

However, you can use send_from_directory to send files from a directory, which can be pretty convenient in some situations:

from flask import Flask, request, send_from_directory

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

if __name__ == "__main__":
    app.run()

或者,您可以使用 app.send_fileapp.send_static_file,但强烈建议不要这样做,因为它可能导致安全风险用户提供的路径;send_from_directory 旨在控制这些风险.

Alternatively, you could use app.send_file or app.send_static_file, but this is highly discouraged as it can lead to security risks with user-supplied paths; send_from_directory was designed to control those risks.

这篇关于如何在 Flask 中提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆