Flask Server not loading audio files

Issue

I have a simple flask setup on repl.it running with the code below.

#The flask server to keep bot alive
from flask import Flask
from threading import Thread

app = Flask('')

#Define served page HTML
@app.route('/')
def home():
    return """
    <body style="background-color:black;">
    <h1 style='color: red;'>TreesBot is Running on Port:8080</h1>
    <embed src="song.mp3" loop="true" autostart="true" width="2"
         height="0">
</div>
"""

#Make repl.it run the server on port 8080
def run():
  app.run(host='0.0.0.0',port=8080)

#Run it on a different thread from the main program
def keep_alive():
    t = Thread(target=run)
    t.start()

As you can see the HTML sets the page background, and an embedded .mp3 file for background music.
However when i try to load the .mp3 file with flask it gives me the following error in the console:

172.18.0.1 - - [29/Dec/2020 12:47:44] "GET /song.mp3 HTTP/1.1" 404 -

This 404 makes me think its not finding the file.
Can anyone see what Im doing wrong?

The full code repository is available here: https://repl.it/@MixtapeMessiah/Esoterica-v10#keep_alive.py

Thanks for any help you can provide.

Solution

Your flask application does not have the route for the

/song.mp3

you should create a route to it, check this: https://pythonprogramming.net/flask-send-file-tutorial/

In a nutshell, should be something like this:

from flask import send_file
#    ...
@app.route('/song.mp3')
def song_mp3():
    return send_file('song.mp3', attachment_filename='song.mp3')

Important to say that it’s wise to create a route for serving static files in Flask, and in production, let the web server (e.g. Nginx) handle this for you, so Flask can take care of the logic and does need to handle static files.

Answered By – Cristiano Araujo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published