I can serve the audio as long as they are under .. /project/static. But let's say I want to serve an audio called "tune.wav" from /home/name/Music. How do I do it?
<audio>
<source src="/static", filename="some.wav">
</audio>
The above snippet is from the template. Additionally what do I need to modify in the snippet?
Create flask route with send_file() or send_from_directory():
#app.route('/music/<path:filename>')
def download_file(filename):
return send_from_directory('/home/name/Music/', filename)
Your HTML code will look like this:
<audio>
<source src="/music/tune.wav">
</audio>
Related
This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 1 year ago.
I am trying to use Flask for the first time.
Currently, I am trying to show a local video on a website.
I created an HTML file that displays a video:
<source src="../video_1.mp4" type="video/mp4">
However, the video doesn't display- when the web page is open there is a black box.
Therefore, I changed the source line in my HTML to the following line:
When running the HTML code the video worked. But, when I am running the code from a python file the video doesn't work, and no error appears
from flask import Flask,redirect,url_for,render_template
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run()[enter image description here][1]
Please help me run the HTML file from my python file in a way that the video will display
[1]: https://i.stack.imgur.com/aBoNm.png
In your index.html file:
<video width="320" height="240" controls>
<source src="{{url_for('static', filename='myvideo.mp4')}}" type="video/mp4">
</video>
Also make sure to have a folder named static in your project and put your video inside it.
Like this
I have Flask website in which I want to add download button which downloads .csv file with scraped data.
In my html file I have this code:
<a href="cms_scrape.csv" ><button>Download!</button></a>
And only output I get is error: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
File is in its proper folder.
My folder structure:
└───Project
│ cms_scrape.csv
│
└───templates
index.html
You will need to specify some sort of route on the backend of your site.
For instance, somewhere in your flask site, you probably have a route #app.route('/') for your index. You will need a similar route for your file. That route will go out onto your file system and return the file itself.
#app.route('/csv_file')
def csv_file():
return flask.send_file('path/to/file/cms_scrape.csv',
attachment_filename='cms_scrape.csv',
as_attachment=True)
You will also need to modify your html to access a route and not the file name directly (unless you create your routes dynamically, of course):
<a href="/csv_file" ><button>Download!</button></a>
Not exactly sure about this but I think the tag has a download attribute you can use. Then you don't need the button.
Usage:
<a href="/path/to/file" download>
Source: https://www.w3schools.com/tags/att_a_download.asp
You can make links to files with the
{{ url_for('static', filename='filename.foo') }}
function inside your template. You have to store the file in a folder named 'static' which should be located in the directory where the main scipt is.
The link in your template should look like this:
<a href=" {{ url_for('static', filename='cms_scrape.csv') }} " download>Download!</a>
I would like to use a class Track to have a function playsound() and this should play the sound on a html template.
This is my class :
class Track:
def __init__(self, name, path):
self.name = name
self.path = path
def playsound(self):
# does something
Now I know that I will need javascript and ajax as well probably. But I'm still new to the concept and I would like to see how I would go about achieving that. The sound file should play onload and should simply be invoked when you type:
songname = Track('name', 'music/filename.ogg')
#app.route('/playSong')
def playSong():
return songname.play()
If there is no way this can be done in this way, or there is a much better way, I'd be happy to be enlightened. Thanks in advance!
You can keep the src of in HTML as
<audio controls>
<source src="http://127.0.0.1:5000/a" type="audio/wav"/>
</audio>
where http://127.0.0.1:5000/a is the url which send_file the audio
python code :
#app.route('/a')
def returnAudioFile():
path_to_audio_file = pwd+"\\question_folder\\audio.wav" #audio from project dir
return send_file(
path_to_audio_file,
mimetype="audio/wav",
as_attachment=True,
attachment_filename="test.wav")
If I understood the question correctly, you should put an <audio> HTML element in your template and go from there. Flask will only serve the rendered template, it can't play the sound directly.
This question already has an answer here:
Can't play HTML5 video using Flask
(1 answer)
Closed 7 years ago.
I have a simple flask server. I downloaded, using pafy, a video from a youtube link provided by the user.
#app.route('/')
def download():
return render_template('basic.html')
The basic.html template has a form that submits an action to download:
<form action="download_vid" method="post">
Link: <input type="text" name="download_path"><br>
<input type="submit" value="Submit">
</form>
I have another end point, /download_vid that looks like this.
#app.route('/download_vid', methods=['POST'])
def download_vid():
url = request.form['download_path']
v = pafy.new(url)
s = v.allstreams[len(v.allstreams)-1]
filename = s.download("static/test.mp4")
return redirect(url_for('done'))
The desired link is indeed downloaded as a .mp4 file in my static folder. I can watch it and I can also use it as a source for a tag in an HTML file, if I open it locally.
#app.route('/done')
def done():
return app.send_static_file('test.mp4')
From what I understand, 'send_static_file' serves files from the static directory. However, I get a 404 error when I run the server, even though the video is clearly there.
I have also tried a different version for done():
#app.route('/done')
def done():
return return render_template('vid.html')
Here, vid.html resides in templates and has a hard coded path to static/test.mp4. It is loaded after the download is complete. I do not have a 404 error in this case, but the tag don't do anything, it's just gray. If I open vid.html locally (double click on it), it works, it shows the video.
Can you please help me understand what is going on?
What I want to achieve is this:
Take an input from the user [ Done ]
Use that input to download a video [ Done ]
Serve that video back to the user [ ??? ]
I think you have something going on with file paths or file permissions.
Is the video being downloaded into static directory?
Is the static directory in the same directory, along with your main.py file?
Does your flask app have permissions to read the file?
I think the reason your file did not load in html template is because you referenced it as static/test.mp4 from an url - /done which translates the video path to be /done/static/test.mp4.
Instead of trying to push the file using Flask, you can redirect to the actual media file.
#app.route('/done')
def done():
return redirect('/static/test.mp4')
I'm trying to learn Flask and making a small app. So at first, I tested without a css file by using: (delay() gets the result from generator)
return Response(stream_template('login.html', data=delay()))
It works fine for me then now i want to implement new css, let's called it style.css and i put it in the static folder. In the html file I have:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"/>
The code will probably won't work as there is a problem with context and response, but it will work fine as a static return:
return render_template('login.html')
My Question is it it anyway that I can both have the generator to work (the delay() function) with the CSS in the static folder? I just spent couple hours on this problem but couldn't find an answer yet.
My stream_template:
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
# uncomment if you don't need immediate reaction
##rv.enable_buffering(5)
return rv
Thanks a lot
Quoting from the documentation:
Note that when you stream data, the request context is already gone the moment the function executes. Flask 0.9 provides you with a helper that can keep the request context around during the execution of the generator: ...
In your case, your code probably should be:
return Response(stream_with_context(stream_template('login.html', data=delay())))
or
return Response(stream_template('login.html', data=stream_with_context(delay())))