问题
I am attempting to serve static mp3 files with Flask so I can embed these mp3 files in an HTML audio block. I seem to be having an issue setting up the path correctly but I am not entirely sure if my problem is in my python or html.
An outline of my project:
music
app.py
static
button.js
MDF.mp3
templates
button.html
My app initialization in app.py looks like
app = Flask(__name__, static_url_path="", static_folder="static")
The route in app.py looks like
@app.route("/<path:filename>")
def upload1():
return send_static_file("MDF.mp3")
My default route:
@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])
And my button.html looks like
<!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>
The error code I get is
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 -
回答1:
If you have audio files in the static
folder you can access them in templates using url_for
as like other static files. Documentation of serving static files can be found in this URL.
Here I am showing an example of getting audio files URL in templates. I have passed the list of files from Flask app to the templates.
Directory structure:
├── 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>
Output:
来源:https://stackoverflow.com/questions/55933447/serving-static-files-from-static-folder-with-flask