python logo

flask


Python hosting: Host, run, and code Python in the cloud!
python-flask-webap Python app created with Flask

In this tutorial you’ll learn how to build a web app with Python. We’ll use a micro-framework called Flask.

Why Flask?


  • easy to use.

  • built in development server and debugger

  • integrated unit testing support

  • RESTful request dispatching

  • uses Jinja2 templating

  • support for secure cookies (client side sessions)

  • 100% WSGI 1.0 compliant

  • Unicode based

  • extensively documented

Related course:
Python Flask: Make Web Apps with Python

$ pip install Flask

Create a file called hello.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"

if __name__ == "__main__":
app.run()

Finally run the web app using this command:

$ python hello.py
* Running on http://localhost:5000/

Open http://localhost:5000/ in your webbrowser, and “Hello World!” should appear.

Creating URL routes


URL Routing makes URLs in your Web app easy to remember. We will now create some URL routes:

/hello
/members/
/members/name/

Copy the code below and save it as app.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def index():
return "Index!"

@app.route("/hello")
def hello():
return "Hello World!"

@app.route("/members")
def members():
return "Members"

@app.route("/members/<string:name>/")
def getMember(name):
return name</string:name>

if __name__ == "__main__":
app.run()

Restart the application using:

$ python hello.py
* Running on http://localhost:5000/

Try the URLs in your browser:

python-flask-webapp python-flask-webapp

Related course:
Python Flask: Make Web Apps with Python

Style Flask Pages

We will separate code and User Interface using a technique called Templates. We make the directory called /templates/ and create the template:


<h1>Hello { {name}}</h1>

The Python Flask app with have a new URL route. We have changed the default port to 80, the default HTTP port:

from flask import Flask, flash, redirect, render_template, request, session, abort

app = Flask(__name__)

@app.route("/")
def index():
return "Flask App!"

@app.route("/hello/<string:name>/")
def hello(name):
return render_template(
'test.html',name=name)</string:name>

if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)

You can then open : http://127.0.0.1/hello/Jackson/

Styling the template
Do you want some better looking template? We modify the file:

&#123;% extends "layout.html" %&#125;
&#123;% block body %&#125;
<div class="block1">
<h1>Hello { {name}}!</h1>
<h2>Here is an interesting quote for you:</h2>
"The limits of my language are the limits of my mind. All I know is what I have words for."

<img src="http://www.naturalprogramming.com/images/smilingpython.gif">

</div>
&#123;% endblock %&#125;

We then create layout.html which defines the look of the page. (You may want to split the stylesheet and layout.html file). Copy this as layout.html



<title>Website</title>

<style>
@import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);</p>
<p>body{<br />
text-align: center;<br />
}<br />
h1{<br />
font-family: 'Amatic SC', cursive;<br />
font-weight: normal;<br />
color: #8ac640;<br />
font-size: 2.5em;<br />
}</p>
</style>&#123;% block body %&#125;&#123;% endblock %&#125;


Restart the App and open the url. http://127.0.0.1/hello/Jackson/
You can pick any name other than Jackson.

python-webapp-flask python webapp flask

Related course:
Python Flask: Make Web Apps with Python

Passing Variables

Lets display random quotes instead of always the same quote. We will need to pass both the name variable and the quote variable. To pass multiple variables to the function, we simply do this:

    return render_template(
'test.html',**locals())

Our new test.html template will look like this:

&#123;% extends "layout.html" %&#125;
&#123;% block body %&#125;
<div class="block1">
<h1>Hello { {name}}!</h1>
<h2>Here is an interesting quote for you:</h2>
{ {quote}}

<img src="http://www.naturalprogramming.com/images/smilingpython.gif">

</div>
&#123;% endblock %&#125;

We will need to pick a random quote. To do so, we use this code:

    quotes = [ "'If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.' -- John Louis von Neumann ",
"'Computer science is no more about computers than astronomy is about telescopes' -- Edsger Dijkstra ",
"'To understand recursion you must first understand recursion..' -- Unknown",
"'You look at things that are and ask, why? I dream of things that never were and ask, why not?' -- Unknown",
"'Mathematics is the key and door to the sciences.' -- Galileo Galilei",
"'Not everyone will understand your journey. Thats fine. Its not their journey to make sense of. Its yours.' -- Unknown" ]
randomNumber = randint(0,len(quotes)-1)
quote = quotes[randomNumber]

The first thing you see is we have defined an array of multiples quotes. These can be accessed as quote[0], quote[1], quote[2] and so on. The function randint() returns a random number between 0 and the total number of quotes, one is subtracted because we start counting from zero. Finally we set the quote variable to the quote the computer has chosen. Copy the code below to app.py:

from flask import Flask, flash, redirect, render_template, request, session, abort
from random import randint

app = Flask(__name__)

@app.route("/")
def index():
return "Flask App!"

#@app.route("/hello/<string:name>")
@app.route("/hello/<string:name>/")
def hello(name):
# return name

quotes = [ "'If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.' -- John Louis von Neumann ",
"'Computer science is no more about computers than astronomy is about telescopes' -- Edsger Dijkstra ",
"'To understand recursion you must first understand recursion..' -- Unknown",
"'You look at things that are and ask, why? I dream of things that never were and ask, why not?' -- Unknown",
"'Mathematics is the key and door to the sciences.' -- Galileo Galilei",
"'Not everyone will understand your journey. Thats fine. Its not their journey to make sense of. Its yours.' -- Unknown" ]
randomNumber = randint(0,len(quotes)-1)
quote = quotes[randomNumber] </string:name></string:name>

return render_template(
'test.html',**locals())

if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)

When you restart the application it will return one of these quotes at random.

python-flask-webap python flask webap

Download App and more Flask Examples

Whats next?
You could link your site with a database system such as MySQL, MariaDb or SQLite. You can find an SQLite tutorial here. Enjoy creating your application!






Leave a Reply:




Yahaya Wed, 29 Apr 2015

I'll like to thank you a lot for a giving me a start, because before reading this, I have no idea on where to start from, I;m really grateful...

Frank Wed, 29 Apr 2015

You're welcome. More tutorials coming soon

Jordan Wed, 20 May 2015

I get an "Internal Server Error" when I open http://127.0.0.1/hello/Jackson/

Jordan Wed, 20 May 2015

Found my mistake.

I put the test.html file in the same directory as hello.py. It needs to be in the templates subdirectory

Tom Sun, 31 May 2015

I get an "ImportError: No module named flask" when I execute the command.

Frank Sun, 31 May 2015

Hi Tom, this means you do not have the flask package installed. Are you on a desktop version? Flask is not available on a web interpreter.

To install flask you can run:

pip install flask

If you are on windows, you should install pip first. A tutorial here:
https://www.youtube.com/watch?v=zPMr0lEMqpo

Alternative: Pycharm seems to support Flask by default. https://www.jetbrains.com/pycharm/help/creating-flask-project.html

Blues Sat, 20 Jun 2015

I get an "ImportError: No module named request" when I execute the command.

Frank Sat, 20 Jun 2015

Hi, request is part of Flask. Are you using a desktop/console version of Python? Flask will not work on a web-python version.
It looks like an installation problem. Which os do you use? Do you use Python from console or an ide like PyCharm? Try reinstalling Flask using:
pip install flask
or
pip3 install flask

This code is tested with Python 3.4.0 and Flask 0.10.1 and Python 2.7.

Blues Sun, 21 Jun 2015

Hi Frank,if I install python3.x from python.org
If I want to uninstall it , what should i do?
I try to put it into trash but it seems not work
By the way I'm using mac os

Blues Sun, 21 Jun 2015

it seems that the problem is I'm using python2.7
when I add up #!usr/bin/env python3.4 it seems work until 'Creating Awesome pages'

Frank Sun, 21 Jun 2015

I do not recommend uninstalling Python because you can have several versions of python on your machine without conflicts.

There is no default uninstaller for mac os. You can uninstall python3 from the command line. The steps to remove python 3 are here (simply replace 2.7 with 3):
http://stackoverflow.com/questions/3819449/how-to-uninstall-python-2-7-on-a-mac-os-x-10-6-4

Frank Sun, 21 Jun 2015

Hi, that's good news. Which error do you get at 'Creating Awesome pages'?

Perhaps the template directory is missing, that one should have a directory /templates/ with the file test.html such that

/app/app.py
/app/templates/test.html
Ismail Mon, 14 Sep 2015

Thank you very much!

Michael Cantrell Tue, 28 Feb 2017

Thanks for the tutorial. I think I found a typo - below we should be running $ python hello.py


"""
Restart the application using:
$ python hello.py
* Running on http://localhost:5000/
Try the URLs in your browser:
http://127.0.0.1:5000/
http://127.0.0.1:5000/hello
http://127.0.0.1:5000/members
http://127.0.0.1:5000/members/Jordan/"""

Ralph Tindell Tue, 18 Jul 2017

Interesting tutorial. And I am unable to get the last code to run - either it's my slow brain (either too much or not enough coffee) or a problem with file names. I am working on an Ubuntu VM.

Frank Wed, 19 Jul 2017

Which error do you get?
It's important to have the templates in the /templates/ directory. The template directory is inside the python code directory.
In this case it's named test.html for both the template and in the url (render_template)


@app.route("/hello/<string:name>/")
def hello(name):
return render_template(
'test.html',name=name)

Sathiyaseelan Sithambaram 2022-11-17T08:31:26.071Z

could you display the directory format for this tutorial. all explain this route little more
/hello
/members/
/members/name/
where it should be created
when I created app.ph and inserted the code app

File 'C:\Users\ssithambaram\PycharmProjects\testweb\app.py', line 18
return name
^
SyntaxError: invalid syntax is in red page not found

Frank 2022-11-17T08:31:28.071Z

You should create the subdirectories /hello /members in the root directory of your project. Make sure the file is .py and not .ph and use spaces for indention

Norbert Lammers 2021-08-07T13:57:14.583Z

I am new to Python, so I was looking for a beginners tutorial.
Still I was able to spot the issue with the initial hello.py example in line 9. :-)

Thank you for the good explanations, I like the steep learning curve it is providing.
Good stuff.