阅读 183

Flask中提供静态文件的实例讲解

在本篇文章里小编给大家分享的是一篇关于Flask中提供静态文件的实例及相关知识点详解,有兴趣的朋友们可以跟着学习下。

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

1
2
3
4
5
6
7
8
9
10
11
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中提供静态文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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)

到此这篇关于Flask中提供静态文件的实例讲解的文章就介绍到这了

原文链接:https://www.py.cn/kuangjia/flask/32545.html


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐