Got 404 error while using Flask framework - python

I was trying to run my html code using flask framework. When I tried to run the python script, it showed 404 error in the browser
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
python script:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name = user)
if __name__ == '__main__':
app.run(debug = True)
What is the reason of this error?

The code works fine.
Make sure that you keep the html file in templates folder. My folder structure is like this:
flask_app
├── hello.py
└── templates
└── hello.html
And also visiting the http://127.0.0.1:5000/ will cause the error as you did not define any view for root path.
While visiting the indexed path http://127.0.0.1:5000/hello/arsho I got the expected view:

Use jinja to print your name
<html>
<body>
<h1>Hello {{name}}</h1>
</body>
</html>
Go throught the flask quickstart

Related

Python 3.8.5 Flask giving internal server error with WSGI application when template is called using render_template in VS Code - 500 server error [duplicate]

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 2 years ago.
I have been following a YouTube tutorial made by Corey Schafer using Flask. I have reached the 2nd tutorial about using html templates, but that is the only place I have reached. This is the program I am running called hello.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
app.run()
This is the HTML file I have been using, called home.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask Template Example</title>
</head>
<body>
<div>
<p>{{ message }}</p>
</div>
</body>
</html>
Whenever I try to run my code, I always get the error jinja2.exceptions.TemplateNotFound: template.html. I've tried to look at all possible solutions, but none have seemed to work. How could I fix this? I'm on a Windows 64-bit machine.
By default un Flask, the template folder is templates/. If home.html is in the same directory as app.py, you need to set template_folder.
Here is how to fix your app.py:
from flask import Flask, render_template
app = Flask(__name__, template_folder='./')
#app.route('/')
def home():
return render_template('home.html')
app.run()
To use the default template location (which is recommended), this is the file structure you would need to have:
app.py
templates
└── home.html

AngularJS directives don't seem to work with Python Flask

Even though my issue might be a common one, I couldn't find a clear answer for it.
I'm a beginner with AngularJS and there is a very simple code that is not working, and actually all my directives doesn't work.
Here is my small project
/templates
-index.html
-header.html
-script.js
mainapp.py
In index.html there is
<!DOCTYPE html>
<html data-ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div data-ng-include="'header.html'"></div>
</body>
</html>
in header.html
<div> I'm supposed to see this </div>
And mainapp.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def mainpage():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Nothing in script.js
When I'm running mainapp.py I'm expecting to see "I'm supposed to see this" but I don't because the directives doesn't seem to be working. However if I'm trying the html code alone (on Plunker for example) it's working fine.
I assume there is configuration that I need to do but I have no idea what, any ideas? (and if someone could provide an explanation for why it's not working that would be great)
Note that using data- before my directives doesn't change the issue.
Thanks
The issue has to do with how Flask handles static files vs. templates. The header.html file is really a static file in your situation, not a Flask template.
Change your directory structure to:
├── mainapp.py
├── static
│   └── partials
│   └── header.html
└── templates
└── index.html
Then update the ng-include to:
<div data-ng-include="'header.html'"></div>
If this were me, I wouldn't even use a "templates" directory. Just serve up a your index.html file from the static directory so that when an end user hits the main / route, Angular takes over. Then, you can just interact with the server-side via making AJAX requests against the RESTful API.

Flask web page cannot find image file

On a Raspberry Pi, I have written a simple Flask app that displays the server's current date and time on a web page. That part works great.
The page should also display an image. That part doesn't work. The image is stored in the photos folder under the app folder: Web_Test/photos.
I use a css file that is stored in a static folder, and that works great.
I use url_for to create the URL to the image:
<p><img src="{{url_for('photos', filename='image1.jpg')}}"></p>
Since photos is not a known endpoint for the url_for command, I used: app.add_url_rule('/photos/<path:filename>', view_func=app.send_static_file) to add the photos folder as an endpoint.
Every time I access the web page from a web browser, my command window, that I ran python (python3 photo.py) from, shows GET /photos/image1/jpg HTTP/1.1" 404.
There are no specific errors, but also no image.
I have read many of the posts on here about this issue, but nothing has helped.
This is my photo.py code:
from flask import Flask, render_template
import datetime
app = Flask(__name__)
app.add_url_rule('/photos/<path:filename>', endpoint='photos', view_func=app.send_static_file)
#app.route('/')
def photo():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'Latest Photo',
'time' : timeString
}
return render_template('photo1.html', **templateData)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80)
This is my photo1.html code:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href='/static/style.css' />
<title>{{title}}</title>
</head>
<body>
<h1>Latest Photo</h1>
<h2>Current date and time: {{time}}</h2>
<p> <img src="{{url_for('photos', filename='image1.jpg')}}"></p>
</body>
</html>
Any thoughts or suggestions would be greatly appreciated.
Thanks!
The way your program is currently written, the image will be visible if you reorganize the project layout like this:
project
├── app.py
├── static
│   └── image1.jpg
└── templates
   └── photo1.html
The fact that you want to use send_static_file to display photos suggests that photos are static resources. If that's the case, then it would be better to:
1) Move image1.jpg to static/photos/image1.jpg
2) Change the template like this:
<p> <img src="{{url_for('static', filename='photos/image1.jpg')}}"></p>
3) Drop the app.add_url_rule('/photos/<path:filename>', ...) in app.py
I just created a folder named "static" in the project folder and moved my images to it and my problem got solved.
app.py
static
|----image.jpg
templates
|----index.html
and changed index.html file like this:
<img src="/static/image.jpg">

How to render index.html using python Flask MVC [duplicate]

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 7 years ago.
This is absolutely new field for me, and I just confused about how this work
Flask server
$ more flask-hello-world.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('index.html') #"Hello World!"
if __name__ == "__main__":
app.run()
index.html
$ more index.html
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
</head>
<body>
Hello worlds
</body>
</html>
Test
$ curl 127.0.0.1:5000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
When I return "Hello World!" it does work properly. Why am I getting an error when I try return render_template('index.html')?
First of all you should turn on debugging for your Flask app, so you see a meaningful error instead of a canned HTTP 500 Internal Server Error.
app.debug = True
app.run()
or
app.run(debug=True)
What could be wrong with your Flask app
From your source code I see you have not imported render_template
So that is at least one issue, fix it with:
from flask import Flask, render_template
# The rest of your file here
Template names and directory
There is a parameter template_folder
you can use to tell Flask where to look for your templates. According to linked documentation, that value defaults to templates which means Flask by default looks for templates in a folder called templates by default. So if your templates are on the project root instead of a folder, use:
E.g. if your templates are in the same directory is the app:
app = Flask(__name__, template_folder='.') # '.' means the current directory
You need to put your templates in templates folder, or ovride it in:
app = Flask(__name__, template_folder='.')

Flask-webage background image doesnt work

Below is a simple html code
index.html
<html>
<head>
<title>Webpage</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet" >
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="sylesheet">
</head>
<body>
<style type=text/css>
background-image: url("static/images/back.png");
</style>
<p>Does the Image Work? </p>
</body>
</html>
This is my Flask code:
app.py
from flask import Flask, render_template
app = Flask(__name__, static_url_path="static", static_folder="static")
#app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run()
I get this error when I tried to inspect the page:
GET http://127.0.0.1:5000/static/images/back.png-404(NOT FOUND)
I read through a couple of other forums, but couldn't find any solution to this problem. My images are in the following folder:
Flaskapp
templates
static
images
back.png
When I open the index.html file, it works perfect, but when I try to run the python file to run the server, the background image isnt seen.
Not really sure how to proceed.
put the static folder next to the flask app
/FlaskApp
-app.py
static/
images/
-back.png
templates/
-index.html
....
you should not have to even tell flask about it... it will just know
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run()

Categories

Resources