相关疑难解决方法(0)

如何在Flask中提供静态文件

所以这很尴尬.我有一个应用程序,我把它放在一起,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)

python static-files flask

453
推荐指数
14
解决办法
53万
查看次数

如何使用 url_for 读取模板文件夹中的文件?

我试图读取print.html位于 path: 中的文件templates/print.html

所以,我曾经url_for()这样称呼它:

{{ url_for('templates', filename='print.html') }}
Run Code Online (Sandbox Code Playgroud)

但是,我收到如下回溯错误:

BuildError: ('templates', {'filename': 'print.html'}, None)

这有什么问题?

如果我使用{{ url_for('static', filename='print.html') }},它只是工作找到。但是,我尝试读取的static文件不在文件夹中,而是在文件夹中templates/print.html

如何使用url_for()读取文件夹print.html中的templates文件?谢谢。

python flask

2
推荐指数
1
解决办法
1701
查看次数

标签 统计

flask ×2

python ×2

static-files ×1