所以这很尴尬。我有一个我放在一起的应用程序,现在它只是提供一个静态HTML页面,其中包含一些指向CSS和JS的链接。而且我在文档中找不到描述返回静态文件的位置。是的,我可以使用,但我知道数据不是模板化的。我会想到或是正确的事情,但我无法让它们起作用。与此同时,我正在打开文件,阅读内容,并用适当的 mimetype 安装一个:Flask
Flask
render_template
send_file
url_for
Response
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)
有人想为此提供代码示例或 url?我知道这将是非常简单的。
在生产中,在应用程序前面配置 HTTP 服务器(Nginx、Apache 等),以处理来自静态文件夹的请求。专用的Web服务器非常擅长有效地提供静态文件,尽管您可能不会注意到与低音量的Flask相比有什么不同。/static
Flask 会自动创建一个路由,该路由将为定义 Flask 应用的 Python 模块旁边的文件夹下的任何路由提供服务。用于链接到静态文件:/static/<path:filename>
filename
static
url_for
url_for('static', filename='js/analytics.js')
您还可以使用 从您自己的路由中的目录提供文件。这将采用基目录和路径,并确保路径包含在目录中,从而可以安全地接受用户提供的路径。如果要在提供文件之前检查某些内容,例如登录用户具有权限,这可能很有用。send_from_directory
from flask import send_from_directory
@app.route('/reports/<path:path>')
def send_report(path):
return send_from_directory('reports', path)
请勿使用用户提供的路径。这将使您面临目录遍历攻击。 旨在安全地处理已知目录下用户提供的路径,如果路径尝试转义该目录,则会引发错误。send_file
send_static_file
send_from_directory
如果要在内存中生成文件而不将其写入文件系统,则可以将对象传递给 以像文件一样提供它。在这种情况下,您需要传递其他参数,因为它无法推断文件名或内容类型等内容。BytesIO
send_file
send_file
如果只想移动静态文件的位置,最简单的方法是在构造函数中声明路径。在下面的示例中,我已将模板和静态文件移动到名为 的子文件夹中。web
app = Flask(__name__,
static_url_path='',
static_folder='web/static',
template_folder='web/templates')
static_url_path=''
从 URL 中删除任何前面的路径(即/static
static_folder='web/static'
将文件夹中web/static
template_folder='web/templates'
同样,这会更改模板使用此方法,以下 URL 将返回一个 CSS 文件:
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
最后,这是文件夹结构的快照,其中是 Flask 实例:flask_server.py
您也可以(这是我最喜欢的)将文件夹设置为静态路径,以便每个人都可以访问其中的文件。
app = Flask(__name__, static_url_path='/static')
有了这个设置,你可以使用标准的 HTML:
<link rel="stylesheet" type="text/css" href="/static/style.css">
模板简介:该模板名称为【Python 如何在 Flask 中提供静态文件】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。