如何在Flask中提供静态文件

本文翻译自:How to serve static files in Flask

So this is embarrassing. 所以这很尴尬。 I've got an application that I threw together in Flask and for now it is just serving up a single static HTML page with some links to CSS and JS. 我有一个在Flask放在一起的应用程序,现在它只提供一个静态HTML页面,其中包含指向CSS和JS的链接。 And I can't find where in the documentation Flask describes returning static files. 而且我找不到文档Flask描述返回静态文件的位置。 Yes, I could use render_template but I know the data is not templatized. 是的,我可以使用render_template但是我知道数据没有模板化。 I'd have thought send_file or url_for was the right thing, but I could not get those to work. 我以为send_fileurl_for是正确的事情,但我无法使它们正常工作。 In the meantime, I am opening the files, reading content, and rigging up a Response with appropriate mimetype: 同时,我正在打开文件,阅读内容,并使用适当的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.pa
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值