使用flask呈现html时未找到文件

2024-04-25 09:14:13 发布

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

我对使用flask非常陌生,有一个基本问题:如何提供对HTML的访问,该HTML是使用flask访问静态文件(如图像)呈现的。下面是我的玩具示例:

我想在网站上呈现logo.svg。该项目的结构如下:

Project 
 |
 + -- static
      |
      + -- logo.svg
 + -- templates
      |
      + -- test.html
 + -- run_flask.py

html如下所示

<!DOCTYPE>

<html>

    <head>

      <title>demo</title>

      <style>
        body {
          font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
          font-size: 14px;
        }

      </style>
    </head>

    <body>
        <img src="./static/logo.svg" id="logo">
    </body>

</html>

我的run\u-py脚本包含:

import flask
from flask import render_template, send_from_directory
from flask_cors import CORS

app = flask.Flask(__name__, static_url_path='')
CORS(app)
app.config["DEBUG"] = True

@app.route('/<string:page_name>/')
def render_static(page_name):
    return render_template('%s.html' % page_name)

app.run(port=5001)

现在运行脚本时,控制台输出为:

Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)

到目前为止还不错,但在chrome中,http://127.0.0.1:5001/test/看起来像:

enter image description here

我已经看过了How to serve static files in Flask,因为问题听起来很相似。但实际上,我完全搞不懂建议的send_from_目录如何在这里帮助我

有人能帮忙吗


Tags: runnamefromsvgtestimportappflask
2条回答

试一试

<img src="../static/logo.svg" id="logo">

而不是

<img src="./static/logo.svg" id="logo">

..将其指向父目录,/static进入static目录

初始化应用程序时,应删除static_url_path参数:

app = flask.Flask(__name__)

默认情况下,flask将在子目录static/中查找任何静态文件。您的目录结构符合此要求

作为@roganjosh注释,这应该在模板中使用:

<img src="{{ url_for('static', filename='logo.svg') }}" id="logo">

作为调试步骤,您可以在浏览器中加载http://127.0.0.1:5001/static/logo.svg,这应该可以正确显示


更新:重新设置。评论

So I guess an empty string defaults to the current app directory or would you need / for that

始终很好地调查实际source code

:param static_url_path: can be used to specify a different path for the
                        static files on the web.  Defaults to the name
                        of the `static_folder` folder.
:param static_folder: the folder with static files that should be served
                      at `static_url_path`.  Defaults to the ``'static'``
                      folder in the root path of the application.

您可能正在寻找的是static_folder,它控制基于服务器的目录static_url_path影响前端上可用静态文件的URL路径

在这里只使用默认值显然更容易,而且两个都不定义

相关问题 更多 >