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

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='.')

Related

render_template giving internal server error in aws beanstalk

I am trying to host a simple application in AWS elasticbeanstalk however when I am using render_template it is giving me this error "Internal Server Error
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."
Here is my flask code,
from flask import Flask, render_template
import requests
application = Flask(__name__, template_folder="templates", static_folder="static")
#application.route("/")
def index():
return render_template('index.html')
# run the app.
if __name__ == "__main__":
application.debug = True
application.run()
My HTML code,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>
<h1>Hello, Flask!</h1>
</div>
</body>
</html>
My Dir Structure,
templates
|
------> index.html
application.py
requirments.txt
But When I dont use render_template i dont see any issue, Here is the code,
from flask import Flask, render_template
import requests
application = Flask(__name__, template_folder="templates", static_folder="static")
#application.route("/")
def index():
return "Hello Flask!!"
# run the app.
if __name__ == "__main__":
application.debug = True
application.run()
Thank you in advance.
Edit -
I was able to fix this issue, The problem was with the zip folder which I had created. Once I created a proper zip and uploaded it to aws beanstalk it started working.

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

Custom HTTP error templates not being served in Flask

I tried implementing the code from this documentation https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/, but the custom error template I created for HTTP 404 error is not loading (it loads the default template for Flask). The method that handles the error is not being called and I'm not sure why. Am I implementing the errorhandler correctly?
_init_.py
from flask import Flask
app = Flask(__name__)
def create_app():
from flask_app.main.routes import main
from flask_app.testing_errors.routes import testing_errors
app.register_blueprint(main)
app.register_blueprint(testing_errors)
return app
run.py
from flask_app import create_app
# importing the create_app method above creates the flask application instance after executing the command: flask run
testing_errors/routes.py
from flask import Blueprint, render_template
testing_errors = Blueprint("testing_errors", __name__)
#testing_errors.errorhandler(404)
def page_not_found(e):
print("test")
return render_template("404.html"), 404
404.html
<html lang="en">
<head>
<title>404</title>
</head>
<body>
<h1>404 Page Not Found</h1>
</body>
</html>
since you are using a blueprint to handle the entire Flask app errors which is best practice you need app_errorhandler not errorhandler
#testing_errors.app_errorhandler(404)
def page_not_found(e):
print("test")
return render_template("404.html"), 404
refer to this doc https://flask.palletsprojects.com/en/1.1.x/api/?highlight=app_errorhandler#flask.Blueprint.app_errorhandler

Got 404 error while using Flask framework

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

jinja2 template not found and internal server error

Python code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('testing.html')
if __name__ == "__main__":
app.run()
Html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>My name is pk</h1>
</body>
</html>
Also how to enable jinja2 in pycharm community version. I am directly creating html file and .py file in the same project
flask file structure
|-app
|--templates // where your html files must be in
|--static // where your js and css files must be in
|--.py files
|--other packages
Also jinja is enabled in your system, if you have already downloaded flask package.
By default, Flask looks in the templates folder in the root level of your app.
http://flask.pocoo.org/docs/0.10/api/
template_folder – the folder that contains the templates that should
be used by the application. Defaults to 'templates' folder in the root
path of the application.
So you have some options,
rename template to templates
supply a template_folder param to have your template folder recognised by the flask app:
app = Flask(__name__, template_folder='template')
Flask expects the templates directory to be in the same folder as the module in which it is created;
You'll need to tell Flask to look elsewhere instead:
app = Flask(__name__, template_folder='../pages/templates')
This works as the path is resolved relative to the current module path.
You cannot have per-module template directories, not without using blueprints. A common pattern is to use subdirectories of the templates folder instead to partition your templates. You'd use templates/pages/index.html, loaded with render_template('pages/index.html'), etc.

Categories

Resources