Python Flask HTML Templates – Basic Example

Overview
In this quick tutorial we will build a small Python Flask app to render a simple HTML template.
Prerequisites
Install Flask
pip install flask
Templates
IMPORTANT! Create a folder labeled templates. Make sure it is templates and not template. One of the defaults in how Flask renders templates is to look for a folder labeled templates.

Under templates create a file labeled userForm.html. In the form put the following HTML code inside
<pre class="wp-block-syntaxhighlighter-code"><!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Flask HTML</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html></pre>
Python Flask
Create a new python file outside of the templates folder and label it “./app.py“
Directory structure should look like the following:
- templates
- userForm.html
- app.py
In the app.py file copy and paste the following code inside.
<pre class="wp-block-syntaxhighlighter-code">from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('simpleform.html')
if __name__ == '__main__':
app.run(debug = True)</pre>
Try It
Notice the debug feature is enabled for this example.
Now run the app.
python app.py
You should see the following output.

You can either run the app from clicking on http://127.0.0.1:5000/ or opena breowser and paste http://127.0.0.1:5000/ the URL into it.

That’s it. If you run into any issues, please make sure the HTML file is under the folder templates and the flaskhtml.py is in the root folder just outside of the templates folder.
If you do not want to use templates as the default folder to hold your HTML files then you can use the following in your python app.
app = Flask(__name__, template_folder='YOUR_HTML_TEMPLATE_FOLDER_NAME')
You must be logged in to post a comment.