Flask with static html files


You can use the Flask framework and use static files together.

Flask will give you URL routing, many features and all the Python benefits.

You may want an application that is partly dynamic and partly static. Or you may simply want to browse with URL routing. In this article we will teach you how to load static HTML files with Flask.

Related course
Complete Python Web Course: Build 8 Python Web Apps

Flask static files example

Create a file called app.py with this contents:

from flask import Flask, render_template
 
app = Flask(__name__)
 
@app.route('/<string:page_name>/')
def render_static(page_name):
    return render_template('%s.html' % page_name)
 
if __name__ == '__main__':
    app.run()

This application initializes a Flask app with the method:

app.run()

The app creates an URL route for any possible page and links that to static html files with:

@app.route('/<string:page_name>/')
def render_static(page_name):
    return render_template('%s.html' % page_name)

Create a directory /templates/ and add the file hello.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
<head>
<title>Hello World Template</title>
</head>
<body>
Hello World
</body>
</html>

Start the server with:

$ python app.py 
* Running on http://127.0.0.1:5000/

Then any .html file is accesible using URL routing.

For example the static file hello.html can be accessed using http://127.0.0.1:5000/hello. You can store any css file in the /static/ directory.

Download Flask Examples

5 thoughts on “Flask with static html files

  1. revcom it - September 5, 2017

    Hi Frank! your tutorial is better other than. Now you should be fulfill Flask with web design (i e, HTML, CSS, Bootstrap,jQuery) and putting screenshot. Thanks.

    1. Frank - September 6, 2017

      Thanks! I’ll write new posts once I get a bit of free time.

  2. Peter Golubev - January 6, 2017

    I’m using Qpithon3 on Android.
    When i started app, console returns:

    SyntaxError: invalid character in identifier
    1|[email protected]_u2:/ $

    What is wrong?

    .

    1. Frank - January 8, 2017

      not sure if Flask works on Android. Do you have the modules Flask and render_template installed?

      1. Peter Golubev - January 9, 2017

        It works, but you are right. I’m trying to code on mobile with Qpithon3. It has Python 3.2.2 core. Flask does not support exactly this relise.
        Thank you. What a sorrow. Now I’m trying Bottle. Per *censored* ad astra ).