【问题标题】:File not found by rendering a html using flask使用烧瓶渲染 html 找不到文件
【发布时间】:2020-05-02 07:13:52
【问题描述】:

我在使用烧瓶方面非常新,并且有一个基本问题:如何提供对使用烧瓶访问静态文件(例如图像)呈现的 HTML 的访问。这是我的玩具示例:

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

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

test.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_flask-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)

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

http://127.0.0.1:5001/ 上运行(按 CTRL+C 退出)

到目前为止一切顺利,但在 chrome 中,http://127.0.0.1:5001/test/ 看起来像:

我已经看过How to serve static files in Flask,因为问题听起来很相似。但我实际上对建议的 send_from_directory 如何在这里为我提供帮助感到完全困惑。

有人可以帮忙吗?

【问题讨论】:

  • &lt;img src="{{ url_for('static', filename='logo.svg') }}" id="logo"&gt;工作?
  • 很遗憾没有

标签: python html flask


【解决方案1】:

试试

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

而不是

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

.. 指向父目录,/static 进入静态目录。

【讨论】:

    【解决方案2】:

    您应该在初始化应用程序时删除static_url_path 参数:

    app = flask.Flask(__name__)
    

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

    作为@roganjosh cmets,这应该可以在模板中使用:

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

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


    更新:重新。评论

    所以我猜一个空字符串默认为当前的应用程序目录,或者你需要/

    总是很好地调查实际的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 路径。

    在这里坚持使用默认值肯定更容易,并且两者都不定义。

    【讨论】:

    • 不错的地方,我错过了我手机上略读的那一点。所以我猜一个空字符串默认为当前的应用程序目录,或者你需要/(如果出于某种奇怪的原因,你想要一个目录中的所有内容?)?无法测试atm
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2023-04-07
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多