所以这很尴尬。我在 Flask 中组装了一个应用程序,目前它仅提供一个静态 HTML 页面,其中包含一些指向 CSS 和 JS 的链接。我在文档 Flask 中找不到描述返回静态文件的位置。是的,我可以使用 render_template 但我知道数据没有模板化。我认为 send_file 或 url_for 是正确的,但我无法让它们工作。与此同时,我打开文件,读取内容,并使用适当的 mimetype 来设置 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)
有人想为此提供代码示例或网址吗?我知道这会非常简单。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您只想移动静态文件的位置,那么最简单的方法是在构造函数中声明路径。在下面的示例中,我已将模板和静态文件移动到名为
web的子文件夹中。app = Flask(__name__, static_url_path='', static_folder='web/static', template_folder='web/templates')static_url_path=''从 URL 中删除所有前面的路径。static_folder='web/static'提供在文件夹中找到的任何文件web/static作为静态文件。template_folder='web/templates'类似地,这会更改 模板文件夹。使用此方法,以下 URL 将返回 CSS 文件:
最后,这是文件夹结构的快照,其中
flask_server.py是 Flask 实例: