I am building a simple website and I am trying to get an image onto the page using Flask. All i get is the broken image symbol on the page tho.
Here is the server code...
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def homePage():
return render_template("HomePage.html")
if __name__ == "__main__":
app.run(debug=True)
And here is HomePage.html...
<!DOCTYPE html>
<style>
</style>
<html>
<head>
</head>
<body>
<img href="{{ url_for('static', filename='testing.png') }}" />
</body>
</html>
<script>
</script>
My file structure is as followed...
-Web
-static
-testing.png
-templates
-HomePage.html
server.py
Now, if i actually inspect through chrome, I can see the img tag gets converted to
<img href="/static/testing.png">
and if I right click this in chrome and open it in a new tab the image appears, But is still doesn't show on my web page.
For img tag use src attribute rather than href attribute.
In HomePage.html change the following line:
<img href="{{ url_for('static', filename='testing.png') }}" />
to
<img src="{{ url_for('static', filename='testing.png') }}" />
Reference:
MDN's documentation on img tag attributes
Related
This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 1 year ago.
I have been trying for the last 45 minutes to figure out how to get my favicon on my flask page.
Here is my current code:
from flask import Flask, render_template, send_from_directory, url_for
import os
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route("/store")
def store():
return render_template("store.html")
#app.route("/games")
def games():
return render_template("games.html")
#app.route("/americanstudios")
def americanstudios():
return render_template("as.html")
#app.route("/pear")
def pear():
return render_template("pear.html")
#app.route("/favicon.ico")
def fav():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', minetype='image/vnd.microsof.icon')
if __name__ == "__main__":
app.run(debug=True)
With the base html being this:
<!DOCTYPE html>
<html>
<title>{% block title %}{% endblock %}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font- awesome.min.css">
<head>
<link rel="shortcut icon" href="{{ url_for('static',filename='favicon.ico') }}">
</head>
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Raleway", Arial, Helvetica, sans-serif}
</style>
<body class="w3-light-grey">
<!-- Navigation Bar -->
<div class="w3-bar w3-white w3-large">
</i>newtech
Store
Games
American Studios
PEAR Electronics
Log In
</body>
<div class="w3-main" style="margin-left:250px">
<div class="w3-row w3-padding-64">
<div class="w3-twothird w3-container">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</html>
And this is index.html
{% extends "base.html" %}
{% block title %}newtech inc.{% endblock %}
{% block content %}
<h1 class="w3-text-teal">Home</h1>
<p>Welcome to newtech inc, where we have the coolest new items for all purposes. Whether it's a new movie to watch, or a fun game, or maybe something else, we're here for you.</p>
{% endblock %}
The only line in head in base.html should load my favicon from the static folder as the favicon for the page. But for some reason, the favicon stays as the default favicon for the index page and all other pages.
My favicon is a 64 X 64 .ico file
And it is located in my static folder
And yes the static folder is in the same directory as main.py
But even with all of this the favicon still does not show up.
And yes I am running the correct main.py
Also tried this
Yet no luck. Can anyone help me?
to look for network error, you would need to look at the network tab of the dev tools. it shows that your get for favicon.ico is failing with 404. fix? add static folder to your app (refer 1 in code), and the add get for favicon and return the file - refer 2 in code.
from flask import Flask,render_template,send_from_directory
app = Flask(__name__, static_folder='static') # 1 ( either add here or add through some os join)
import os
#app.route("/")
def home():
return render_template("index.html")
#app.route("/static/favicon.ico") # 2 add get for favicon
def fav():
print(os.path.join(app.root_path, 'static'))
return send_from_directory(app.static_folder, 'favicon.ico') # for sure return the file
if __name__=="__main__":
app.run(debug=True)
the folder structure will be like :
Did you check out the Flask documentation already? They recommend a slightly different reference than what you have there:
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/?highlight=favicon
I'm new in python / flask, so I'm probably not solving the issue the way it should be solved... Considering this, the question is:
I have a flask def(), which gets a POST from an HTML, and returns the text "File successfully processed".
What I want is for the "File successfully processed" to have the style in my styles.css file.
PS.: I already have an index.html which works great with the styles.css. The code in index.html is:
<head>
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='css/styles.css') }}">
</head>
So, how do I apply this styles.css to the return "File successfully processed"?
#app.route("/run_ctb", methods=["GET", "POST"])
def web_run_ctb():
if request.method == "POST":
return "<p>File successfully processed<p>"
That styles sheet is currently only applying to your index.html template. You should create a template for your "/run_ctb" page, for example called run_ctb.html which would look like:
<head>
<link rel= "stylesheet" type= "text/css" href= "{{
url_for('static',filename='css/styles.css') }}">
</head>
<body>
<p>File successfully processed<p>
</body>
Then you can just have your route function render the template:
#app.route("/run_ctb", methods=["GET", "POST"])
def web_run_ctb():
if request.method == "POST":
return render_template('run_ctb.html')
As of title, I'm trying to load an HTML page into an HTML frame using Flask.
When I open the frameset.html page on a Firefox tab (substituting {{src}} with index.html of course), the frameset behaves correctly.
However, whenever I run the python code, the loaded HTML page is correctly divided between the frames, but there is no trace of the index.html page in any of it.
main.py
from flask import Flask, render_template, request
app = Flask(__name__)
page = 'index.html'
#app.route('/')
def home():
return render_template('frameset.html', src=page)
app.run()
frameset.html
<html>
<frameset rows="10%,80%,*">
<frame src=''>
<frameset cols='20%,40%,40%'>
<frame src=''>
<frame src='{{src}}'>
<frame src='' name="output">
</frameset>
<frame src=''>
</frameset>
</html>
index.html
<html>
<head>
<title>HOME</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
<style type="text/css">
.container {
max-width: 500px;
padding-top: 100px;
}
</style>
</head>
<body>
<div class="container">
GENO stats
</html>
How can I solve this problem? The code I wrote here is just to test the functionality of the framesets.
create another route at #app.route('index.html') rendering index.html the template, make sure the index.html file is in the templates folder
like this:
#app.route('/index.html')
def index():
return render_template('index.html')
resources need to be served from either the templates folder or the static folder in flask, you can't have a resource and have it automatically served as that would be incredibly insecure, since any user then will have access to your entire server by simply changing the link.
I have a basic Flask app with the following structure :
from flask import Flask
from flask import render_template
app = Flask(__name__,template_folder='E:\Programming\Python Projects\Flask')
#app.route('/')
def index():
return render_template('hello.html')
#app.route('/route/')
def route1():
return render_template('route1.html')
app.run(debug = True,port = 8080,host = '0.0.0.0')
hello.html :
<!DOCTYPE html>
<html>
<head>
<title>Rendered!!</title>
</head>
<body>
<h1>
The template has been rendered!!!<br>
Route No. 1
</h1>
</body>
</html>
route1.html :
<!DOCTYPE html>
<html>
<head>
<title>Route No. 1</title>
</head>
<body>
<h2>
This is the first route!!!<br>
Hello World!!!
</h2>
<iframe src="https://www.youtube.com/embed/YQHsXMglC9A" width="853" height="480" frameborder="0" allowfullscreen></iframe>
</body>
</html>
When I open localhost:8080 it works fine.
But when I click on the link, it says :
The address wasn’t understood
Firefox doesn’t know how to open this address, because one of the following protocols (localhost) isn’t associated with any program or is not allowed in this context.
It works fine when I type the address localhost:8080/route manually in the address bar.
Also, it works fine when opened in a new tab.
I need help!!!
Thank You !!!
You should use from flask import render_template, url_for
and in the template:
<h1>
The template has been rendered!!!<br>
Route No. 1
</h1>
Just let Flask and Jinja2 make the URL's for you...
*It seems that you forgot the trailing slash at the link.
Should be localhost:8080/route/
But its far better to use url_for as it avoids this type of problem
This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 6 years ago.
I reduced the code for this to, I think, minimum while trying to get it to work:
The python:
#!/usr/bin/env python
from functools import wraps
from flask import Flask, render_template, session, request, redirect, url_for
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
#app.route('/')
def index():
return render_template('index_test.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
The html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
The image is in the static folder.
And it gives this error:
"GET /bulboff.gif HTTP/1.1" 404
when the page is accessed.
I've tried several things like setting the Flask default paths, without the url_for, etc, but, still no image.
What am I missing?
According to the flask document:
To generate URLs for static files, use the special static endpoint
name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
In your case, use <img src="{{ url_for('static', filename='bulboff.gif') }}">
If You put image in the static folder, You should use something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}static/bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
Alternatively, You could change application's code and add following:
#app.route('/bulboff.gif')
def bulboff():
return open('static/bulboff.gif').read()
<img src="{{url_for('static', filename='bulboff.gif')}}" />
Try that. Your filename could be a path from the static folder. So like if you have filename = \some\path\img.png it will look for the img in static\some\ath\img