所以这很尴尬.我有一个应用程序,我把它放在一起,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) 如何url_for在Flask中使用引用文件夹中的文件?例如,我在static文件夹中有一些静态文件,其中一些可能在子文件夹中,如static/bootstrap.
当我尝试提供文件时static/bootstrap,我收到错误.
<link rel=stylesheet type=text/css href="{{ url_for('static/bootstrap', filename='bootstrap.min.css') }}">
Run Code Online (Sandbox Code Playgroud)
我可以引用不在子文件夹中的文件,这有效.
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">
Run Code Online (Sandbox Code Playgroud)
引用静态文件的正确方法是什么url_for?如何使用url_for在任何级别生成静态文件的URL?