亲宝软件园·资讯

展开

Flask中如何提供静态文件

小妮浅浅 人气:0

1、可以使用send_from_directory从目录发送文件,这在某些情况下非常方便。

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()

2、可以使用app.send_file或app.send_static_file,但强烈建议不要这样做。

因为它可能会导致用户提供的路径存在安全风险。

send_from_directory旨在控制这些风险。

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

知识点补充:

如何在Flask中提供静态文件

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)

加载全部内容

相关教程
猜你喜欢
用户评论