所以这很尴尬。我在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)
有人想提供一个代码样本或这个网址?我知道这很简单。
如果只想移动静态文件的位置,那么最简单的方法是在构造函数中声明路径。在下面的示例中,我已经将模板和静态文件移动到名为
web
的子文件夹中。static_url_path=''
从URL中删除任何前面的路径(即。 默认值/static
)。static_folder='web/static'
会告诉Flask提供web/static
。template_folder='web/templates'
类似地,这会改变 模板文件夹。使用此方法,以下URL将返回一个CSS文件:
最后,这里是文件夹结构的快照,其中
flask_server.py
是烧瓶实例:你也可以,这是我最喜欢的,设置一个文件夹作为静态路径,这样每个人都可以访问里面的文件。
有了这个集合,您可以使用标准的HTML:
首选的方法是使用nginx或另一个web服务器来提供静态文件;它们将能够比Flask更有效地完成这项工作。
但是,您可以使用^{} 从目录发送文件,这在某些情况下非常方便:
不要对用户提供的路径使用
send_file
或send_static_file
。send_static_file
示例:相关问题 更多 >
编程相关推荐