所以这很尴尬.我有一个应用程序,我把它放在一起,Flask现在它只是提供一个静态HTML页面,其中包含一些CSS和JS的链接.我无法在文档Flask中找到返回静态文件的位置.是的,我可以使用,render_template但我知道数据没有模板化.我曾经想过send_file或者url_for是对的,但是我无法让它们发挥作用.与此同时,我正在打开文件,阅读内容,并Response使用适当的mimetype来装配:
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: …Run Code Online (Sandbox Code Playgroud) 我有一个玩具REST应用程序,其结构如下:
- client/
- css/
- js/
- index.html
- server/
- app.py
... some other files which I use in app.py
Run Code Online (Sandbox Code Playgroud)
app.py 是一个烧瓶restful端点,看起来像这样:
app = flask.Flask('some-name')
# a lot of API end points, which look in this way
@app.route('/api/something', methods=['GET'])
def func_1():
...
Run Code Online (Sandbox Code Playgroud)
现在我想提供我的静态索引html.所以看了这个,这个和这个,我想我可以通过添加以下几行轻松地提供它:
@app.route('/')
def home():
# but neither with this line
return app.send_static_file('../client/index.html')
# nor with this
return flask.render_template(flask.url_for('static', filename='../client/index.html'))
Run Code Online (Sandbox Code Playgroud)
我看不到我的html文件(日志告诉我:) 127.0.0.1 - - [some day] "GET / HTTP/1.1" 404 - …