【问题标题】:Serving static files from static folder with Flask [duplicate]使用 Flask 从静态文件夹提供静态文件 [重复]
【发布时间】:2019-09-19 20:29:48
【问题描述】:

我正在尝试使用 Flask 提供静态 mp3 文件,因此我可以将这些 mp3 文件嵌入 HTML 音频块中。我似乎在正确设置路径时遇到了问题,但我不完全确定我的问题是在我的 python 还是 html 中。

我的项目大纲:

music
    app.py
    static
        button.js
        MDF.mp3
    templates
        button.html

我在 app.py 中的应用初始化看起来像

app = Flask(__name__, static_url_path="", static_folder="static")

app.py 中的路由是这样的

@app.route("/<path:filename>")
def upload1():
    return send_static_file("MDF.mp3")

我的默认路线:

@app.route("/", methods=["GET"])
def home():
    return render_template("button.html", title="Music Box", name="MyName", song1=songList[0], song2=songList[1], song3=songList[2])

我的 button.html 看起来像

<!DOCTYPE html>
<html lang=en-US xml: lang"en-US">
<body>
    <o1>
        <li> {{song1}}</li>
        <audio controls>
            src=upload1():
            Your browser does not support the <code>audio</code> element.
        </audio>
        <li> {{song2}}</li>
        <audio controls>
            src=upload2():
            Your browser does not support the <code>audio</code> element.
        <li> {{song3}}</li>
        <audio controls>
            src=upload3():
            Your browser does not support the <code>audio</code> element.
    </ol>

    <script src="/static/button.js"></script>
</body>
</html>

我得到的错误代码是

10.245.81.226 - - [01/May/2019 04:25:08] "GET / HTTP/1.1" 404 -
10.245.81.226 - - [01/May/2019 04:25:08] "GET /static/button.js HTTP/1.1" 404 -
10.245.81.226 - - [01/May/2019 04:25:08] "GET /favicon.ico HTTP/1.1" 404 -

【问题讨论】:

  • 您遇到错误了吗?如果是这样,请包括完整的堆栈跟踪。
  • @SuperShoot 我已将我的错误代码添加到原始帖子中。

标签: python flask


【解决方案1】:

如果您在static 文件夹中有音频文件,您可以像其他静态文件一样使用url_for 在模板中访问它们。提供静态文件的文档可以在in this URL找到。

这里我展示了一个在模板中获取音频文件 URL 的示例。我已将 Flask 应用程序中的文件列表传递给模板。

目录结构:

├── app.py
├── static
│   ├── demo1.mp3
│   ├── demo2.mp3
│   └── demo3.mp3
└── templates
    ├── audio.html

app.py:

from flask import Flask, render_template


app = Flask(__name__, static_folder='static')

@app.route('/')
def index():
    audio_files = ["demo1.mp3", "demo2.mp3", "demo3.mp3"]
    return render_template('audio.html', audio_files=audio_files)

audio.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Audio Example</title>
  </head>
  <body>
    <h2>Serving audio files from Flask</h2>
   {% for file in audio_files %}
    <audio controls>
      <source src={{ url_for('static', filename=file) }} type="audio/mpeg">
    </audio>
    {% endfor %}
    <p>Click on play icon to play</p>
  </body>
</html>

输出:

【讨论】:

  • 如果您事先不知道文件名并且它们是动态的,该怎么办。如何获取静态文件夹中所有可用文件的列表。
  • 嗨 Vineeth,您可以为此创建一个新问题。我认为您可以使用os.listdir(app.static_folder) 列出静态文件夹的文件。