如何在Flas中提供静态文件

2024-04-19 22:13:36 发布

您现在位置:Python中文网/ 问答频道 /正文

所以这很尴尬。我在Flask中组装了一个应用程序,现在它只是提供一个静态HTML页面,其中包含一些CSS和JS的链接。我在文档中找不到Flask描述返回静态文件的位置。是的,我可以使用render_template,但我知道数据没有模板化。我本以为send_fileurl_for是正确的,但我不能让它们工作。同时,我正在打开文件,读取内容,并用适当的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.path.join(root_dir(), path)
    ext = os.path.splitext(path)[1]
    mimetype = mimetypes.get(ext, "text/html")
    content = get_file(complete_path)
    return Response(content, mimetype=mimetype)


if __name__ == '__main__':  # pragma: no cover
    app.run(port=80)

有人想提供一个代码样本或这个网址?我知道这很简单。


Tags: pathnoappflaskgetreturnosresponse
3条回答

如果只想移动静态文件的位置,那么最简单的方法是在构造函数中声明路径。在下面的示例中,我已经将模板和静态文件移动到名为web的子文件夹中。

app = Flask(__name__,
            static_url_path='', 
            static_folder='web/static',
            template_folder='web/templates')
  • static_url_path=''从URL中删除任何前面的路径(即。 默认值/static)。
  • static_folder='web/static'会告诉Flask提供 web/static
  • template_folder='web/templates'类似地,这会改变 模板文件夹。

使用此方法,以下URL将返回一个CSS文件:

<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">

最后,这里是文件夹结构的快照,其中flask_server.py是烧瓶实例:

Nested Static Flask Folders

你也可以,这是我最喜欢的,设置一个文件夹作为静态路径,这样每个人都可以访问里面的文件。

app = Flask(__name__, static_url_path='/static')

有了这个集合,您可以使用标准的HTML:

<link rel="stylesheet" type="text/css" href="/static/style.css">

首选的方法是使用nginx或另一个web服务器来提供静态文件;它们将能够比Flask更有效地完成这项工作。

但是,您可以使用^{}从目录发送文件,这在某些情况下非常方便:

from flask import Flask, request, send_from_directory

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

if __name__ == "__main__":
    app.run()

不要对用户提供的路径使用send_filesend_static_file

send_static_file示例:

from flask import Flask, request
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/')
def root():
    return app.send_static_file('index.html')

相关问题 更多 >