相关疑难解决方法(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万
查看次数

python flask - 提供静态文件

我正在尝试使用flask来提供静态文件.我不知道如何使用url_for函数.生成动态内容的所有路由工作正常,我已导入url_for,但是当我有这个代码时:

@app.route('/')
def home():
    return url_for('static', filename='hi.html')
Run Code Online (Sandbox Code Playgroud)

随着我的'hi.html'文件(其中有一些基本的html)坐在目录静态中,我加载页面时得到的字面意思是:

/static/hi.html

我只是错误地使用url_for吗?

python flask

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

标签 统计

flask ×2

python ×2

static-files ×1