Flask提供静态文件的操作是什么,有什么知识点
Admin 2022-05-28 群英技术资讯 1642 次浏览
这篇文章主要介绍“Flask提供静态文件的操作是什么,有什么知识点”,有一些人在Flask提供静态文件的操作是什么,有什么知识点的问题上存在疑惑,接下来小编就给大家来介绍一下相关的内容,希望对大家解答有帮助,有这个方面学习需要的朋友就继续往下看吧。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)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了在Python中如何让字典保持有序,文章基于python的相关资料展开详细内容,需要的小伙伴可以参考一下
这篇文章主要为大家介绍了python高阶函数使用教程示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
大部分程序和语言中的随机数,其实都只是伪随机。是由可确定的函数(常用线性同余),通过一个种子(常用时钟)产生的。直观来想,计算机就是一种确定的、可预测的的设备:一行行的代码是固定的,一步步的算法是固定的,一个个与非门是固定的。
这篇文章主要介绍了python-pandas创建Series数据类型的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
这篇文章主要介绍用python实现自动刷新网页,也就是我们在多次打开和关闭网页之后可以看到浏览数量自动增加,自动刷新网页的功能在很多网站设计中场景中都能应用到,下文有具体的实现方法,有需要的朋友可以参考。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008