所以这很尴尬。我在Flask
中整合了一个应用程序,目前它只是提供一个静态超文本标记语言页面,其中包含一些指向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)
有人想为此提供代码示例或url吗?我知道这将非常简单。