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
Related
this is my rule.html
<!DOCTYPE html>
<html>
<head>
<title>rules</title>
</head>
<body>
<H1>Have fun and enjoy {{name}}</H1>
<p>So there are some rules that will help you to play this game.</p>
</body>
</html>
this one is home page html code. Please help, I saw tutorials but not getting anything.
<!DOCTYPE html>
<html>
<head>
<title> Home</title>
</head>
<body>
<h1>Welcome to guess the game!!</h1>
<form method="post" action="/rule">
<h3>So, what is your name":</h3>
<input type="text" name="user">
<input type="submit" value="submit" >
</form>
</body>
this one is my python code.
from flask import Flask,render_template, request, redirect, url_for
app= Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/rule', methods=["POST","GET"])
def rule():
if request.method=="POST":
user=request.form["user"]
print(user)
return redirect(url_for("user",usr=user))
else:
return render_template("rule.html")
#app.route("/<usr>")
def user(usr):
return render_template("rule.html",name=usr)
if __name__ == '__main__':
app.run(debug=True)
sorry for so many codes. but i need help.
and my os is window 8.1, python -> 3.7.1, flask->1.1.1,werkzeug->1.0.1
error page
When I look at your error page, your browser seems to try to access D:/rule - this should not be served by the file system, but by Flask.
You need to access your app e.g. as localhost:5000/home.html and then it should work.
For me it looks like you directly access the html file in your browser from the file system.
First, you need to run your app, with something like python main.py, where main.py is the file name of your app.
Then enter the URL, which you see in the console plus append the home.html - it should work then.
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
I have a basic HTML file which looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
I am receiving the file in python and storing it as a string. I want to know, is there a way I can write this out to a web browser?
The file is on my computer, so my goal is not to save it as an html file and then execute it, but rather execute this from within python to the browser.
I know that with JavaScript I can use Document.write() to inject content to a webpage, but that is already being done in the browser. I want to achieve something similar.
You can use flask, a simple Python web framework, to serve the string:
Using flask (pip install flask):
import flask
app = flask.Flask(__name__)
s = """
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
"""
#app.route('/')
def home():
return s
if __name__ == '__main__':
app.debug = True
app.run()
Now, can you navigate to 127:0.0.1:5000 or the equivalent IP and port specified when the app is run.
You could do the following:
html = """<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>"""
with open('html_file.html', 'w') as f:
f.write(html)
import webbrowser, os
webbrowser.open('file://' + os.path.realpath('html_file.html'))
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
I am trying to serve static files from Flask, but said static file contains an image which is not showing up. Here is my flask code:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return app.send_static_file("somefile.html")
if __name__ == '__main__':
app.run(debug = True)
And here is my html file "somefile.html" which is in the "static" sub-directory under the directory which holds the above code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div> this is some garbage text </div>
<img id="ansvg" src="./ppnow.svg">
</body>
</html>
The graphic is sitting in the same "static" subdirectory as somefile.html.
If I drag the html file directly into the browser, no problem, I get the graphic, but if I run the flask server and point to localhost:5000 then the graphics doesn't show up (though the text does).
What's going on? Thank you.
You are serving the HTML page under the root URL, /. The browser will then load all relative URLs based of the root url.
Your image is thus going to be loaded as /ppnow.svg, not /static/ppnow.sgv.
You could fix the link to the image, or you could alter the base URL with a <base> tag:
<base href="/static/">
Note that without a domain name (an absolute URL) the base tag may be ignored by IE.