Serving a web app with Flask

Pasha KravtsovSupport Engineer
Published:
Updated:
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7.

Lets install Flask!
To install Flask you can use a python repository for libraries tool called pip. Download this file Python Pip and save it as 'get-pip.py'
To run it:
Windows -
python.exe get-pip.py
Linux -
python get-pip.py
Actually using pip to install flask:
pip install flask
Great, now Flask is installed as a python library and can be used in any python script.

In the beginning we'll just be able to connect to our web application through http://localhost:5000/ and later we will can make it available to anyone on the internet!

To start our project, create a folder that will house your files. We'll be using a special folder structure that flask will use to find correct .html, .css, image files and .js files.

Name your folder whatever you want and put it somewhere easily accessible. I called mine "MyWebApp". Inside your folder create another two folders. One named "static" and another named "templates".
Excuse my horrid picture but it will do:
File StructureNow that you have created a organized directory, create a Python file named "main.py"

In this file you're going to want to add this Python code.
 
#!/usr/bin/python2
                      from flask import Flask
                      app = Flask(__name__)
                      
                      @app.route("/")
                      def hello():
                          return "Hello World!"
                      
                      if __name__ == "__main__":
                          app.run()

Open in new window


Let's break down the code.
#!/usr/bin/python2
This can be ignored for windows users. If you're using linux this tells the compiler when you run the file as an executable to compile it with python2

from flask import Flask
Here we are adding the flask library so you are able to use it.
 
@app.route("/")
This is the interesting part of Flask. Here you define what happens when a user goes to any url on your website. Example if you wanted a user to see "Hi" when they go to http://site.com/garbage/hello you would do

@app.route("/garbage/hello")
and use the code below to serve what they see
 

def hello():
    return "Hello World!"
Here the Flask interpreter will run this function/method which returns "Hello World!" and it will serve this when you go to "http://localhost.com:5000/"
 

if __name__ == '__main__':
    app.run()
This should be pretty self-explanatory if you're familiar with Python. Basically this initializes Flask and the program.

Now save your main.py file and run it by doing "python.exe main.py" in cmd prompt or for Linux
 
chmod +x main.py
                      ./main.py

Open in new window

or alternatively
 
python main.py

Open in new window


Now load up http://localhost.com:5000/ or http://127.0.0.1:5000/ in your web browser.
Check out the sweet sweet "Hello, World"

Now let's look at serving an html file. Create a file called "style.html" in /MyWebApp/templates. Put this HTML into it:
 
<!DOCTYPE html>
                      <html>
                        <head>
                          <title>EE Tutorial</title>   
                        </head>
                        <body>
                         
                          <header>
                            <div class="container">
                              <h1 class="logo">Experts Exchange</h1>
                            </div>
                          </header>
                           
                          <div class="container">
                            {% block content %}
                            {% endblock %}
                          </div>
                           
                        </body>
                      </html>

Open in new window


The {% block content %} lets you "insert" other pieces of HTML so you don't have to keep writing the same code over and over again. Now lets make a "index.html" file in /MyWebApp/templates/. Put this HTML into it:
 
{% extends "style.html" %}
                      {% block content %}
                        <div class="jumbo">
                          <h2>"The ride never ends"<h2>
                          <h3>- Mr. Bones<h3>
                        </div>
                      {% endblock %}

Open in new window


As you can see this piece of html will be 'extended' or 'inserted into 'style.html' which is pretty sweet because there are endless possibilities you can do such as creating one master html file and linking a bunch of different components so you don't have to keep rewriting them.

How do we show this html file on http://localhost:5000/ ? Easy! We use render_template(). This Flask function looks for the specified file in the 'templates' folder and loads it for us.

Lets edit your "main.py" file again so it shows these changes:
 
#!/usr/bin/python2
                      from flask import Flask, render_template
                      app = Flask(__name__)
                      
                      @app.route("/")
                      def index():
                          return render_template("index.html")
                      
                      if __name__ == "__main__":
                          app.run(debug = True)

Open in new window


Save and start up your python code ("python.exe main.py" or "./main.py" or "python main.py" and go to http://localhost:5000/ and you can see your new html being processed!

If you spot any issues with the code/have any suggestions post in the comments!

Thanks,
Pasha
4
3,454 Views
Pasha KravtsovSupport Engineer

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.