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
Related
I am building a website with flask on python. I am new to web development.
I built an HTML page, and now I need it's contents - number of buttons on the page for example - to be possibly different and automatic on each launch of app.py (the flask app running the website). Let's say that the number will be random between 1-10, a number generated in the app.py.
Does this mean that I need to change the HTML on every app.py launch, this by using python and editing the text file "index.html"? Is this bad practice and not a good way of achieving the goal? Are there other better methods to launch an input-dependent HTML page?
Thanks!
Code example:
def change_HTML_page(path,num):
# here read the text file in path, which is an HTML file, page description.
# inside in some place add more rows to describe buttons,
# as many as num.
# Add rows like this one <input type="button" id="i_bnutton" value="i" onclick="change_button_appearence(this)" />
# save text file afer the change
num_of_buttons = randint(0, 10)
page_path = r"docs/pages/index.html"
change_HTML_page(page_path, num_of_buttons);
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Best way is to pass the num_of_buttons inside the html render command and constract all input buttons with a jinja loop inside your html.
Your code should look like below:
FLASK:
#app.route('/')
def index():
num_of_buttons = randint(0, 10)
return render_template('index.html', num_of_buttons=num_of_buttons)
if __name__ == '__main__':
app.run(debug=True)
And inside your HTML:
{% for i in range(0,num_of_buttons) %}
<input type="button" id="{{i}}_bnutton" value="{{i}}" onclick="change_button_appearence(this)" />
{% endfor %}
I was trying to display photos and pdf files in a django project using <embed> but pdf file is not displaying
Here is what i was doing
This is view function
#login_required
def view_documents(request):
students = Student.objects.filter(user=request.user)
return render(request, 'student/view_documents.html',{'students':students})
and then I used for tag in template
{% for student in students %}
#lines of code
{% endfor %}
and to display the pdf file i have used
<embed src="{{student.adhar_card_pdf.url}}" width="800px" height="400px" type="application/pdf"/>
but it was showing some kind of error like localhost refused to connect
i also used iframe
<iframe src="{{student.adhar_card_pdf.url}}" style="width:718px; height:700px;" frameborder="0"></iframe>
But image is displaying in the browser using same code without any error
<embed src="{{student.photo_jpg.url}}" width="230px" height="250px" />
Why pdf file is not displaying ?? Please help me
Thanx in advance.
Edited: In console it is showing -- Refused to display '' in a frame because it set 'X-Frame-Options' to 'deny'.
This is how it is displaying pdf
X_FRAME_OPTIONS = 'SAMEORIGIN'
Insert the above line in settings.py just before the MIDDLEWARE section
and for the file path in embed tag write path as
{{student.file.get.photo_jpg.url}}
And then give a hard reset in Chrome or any browser you are using.
It worked for me I hope it works for you as well.
This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 4 years ago.
I'm pretty new to python, even less experienced with flask, and I cannot figure out this issue. I have the following simple web page with jQuery functionality that works great when I double click the file and open it in a browser:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#updateBtn").on("click", function() {
text = "<h2>The div has been updated!</h2>";
$("#jQuery_div").html(text);
});
});
</script>
<div>
<h1>This is a non-jQuery div</h1>
</div>
<div id="jQuery_div">
<h2>This div should update with jQuery</h2>
</div>
<button id="updateBtn">update</button>
</body>
</html>
However, when flask delivers the web page on localhost:5000, the jQuery functionality is no longer present. My python is as follows:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def render():
return render_template("jquery_test.html")
if __name__ == "__main__":
app.run(port=5000, debug=True)
My app's file tree is:
/AJAX_practice
ajax_practice.py
/templates
jquery-3.3.1.js
jquery_test.html
I was trying to follow this tutorial when I couldn't get the "echo" button to work. In my efforts to debug, I have slowly chipped away and drastically simplified the program to the above code to see why I cannot get my jQuery to work through flask. I am still at a loss. I am running the flask app by pressing F5 in IDLE, with no errors in Python 2.7.13 Shell, and the Terminal (from which I started IDLE with $ sudo idle) showing:
my ip - - [date and time] "GET / HTTP/1.1" 200 -
my ip - - [date and time] "GET /jquery-3.3.1.js HTTP/1.1" 404 -
From this, my best guess is that flask cannot find the jquery.3.3.1.js file, though I have tried putting it everywhere in the file tree with no luck. I cannot use the script src to https for jQuery dependencies, as my server will eventually be on a non-internet connected LAN. Am I on the right track? If so, how does flask find and/or navigate jQuery dependencies? Can anyone point me towards some documentation that might help my fundamental understanding of this issue?
Any help on this matter would be greatly appreciated.
You are trying to serve JavaScript file from templates folder. Add a static folder and use that to serve static content.
in your case create a directory structure like "static/js/jquery.min.js"
and then add script reference like this
<script src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
See this :
http://exploreflask.com/en/latest/static.html
If you don't want to keep it in "static" folder and use another local directory you can use send_from_directory as shown in this example :
https://stackoverflow.com/a/20648053/2118215
This has always worked for me with Flask in the past:
<script src="{{ url_for('static', filename='jquery-3.3.1.js') }}"></script>
'static' is the name of the folder it's in (and the 'static' folder is in the root of my project). You can edit this to suit your preferred structure and naming, so change 'static' to 'templates' if that's where you'd rather keep your jquery file, although I would recommend keeping it in a separate folder from your HTML templates, purely in the interests of keeping your project well organised.
I believe the path to jquery should be /templates/jquery-3.3.1.js
On me flask server when i serve jquery it has the full path from the home directory: /static/js/jquery.min.js
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 just for learning how to serve a video with the blobstore without it takes all the screen the video, for example
here I imported Video as video_model
class ViewVideo(webapp.Reque...,blobstore_handlers.BlobstoreDownloadHandler):
def get(self):
video_id = self.request.get('video_id')
video_instance = None
if video_id:
video_instance = video_model().get_video_content(video_id)
self.response.headers['Content-Type'] = 'video/mp4'
self.send_blob(video_instance.content.key())
class Video(db.Model):
content = blobstore.BlobReferenceProperty()
title = db.StringProperty()
def get_video(self,video_id):
return Video.get_by_id(video_id)
def get_video_content(self,content):
query_str = "SELECT * FROM Video WHERE content =:content"
return db.GqlQuery(query_str,content=content).get()
Where the video_id came from a url given, but as you see I put it directly in send_blob() function and this one when I tested it takes all the screen just to see the video, I was wondering how can I serve the video from my application without happening this, I was thinking embedded HTML but I can't figure it out how the source will be
Any help will be grateful
If it lacks of content to answer the question I will edit it
Without HTML5, it's a tricky mess. With HTML5, it becomes easy & elegant. Serve to the user's browser, as part of whatever page you're serving, the following HTML (5) snippet:
<video width="320" height="240" controls>
<source src="/getmp4?video_id=whatever" type="video/mp4">
Your browser does not support the video tag: please upgrade it!
</video>
and use that ViewVideo handler to serve only the /getmp4 URL, not the URL that your user directly gets via their browser.
The 320, 240, and the choice to show controls, are all optional, of course -- as even more is the use of whatever for the video id!-)