Python Web Server With Flask
Python Web Server With Flask
Raspberry Pi Projects
This resource covers elements from the following strands of the Raspberry Pi Digital
Making Curriculum (https://www.raspberrypi.org/curriculum/):
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 1/11
10/8/2017 Raspberry Pi Projects
Installing Flask
First you’re going to install the Flask package. Make sure you are connected to the
internet, either by Ethernet cable or WiFi before you start.
Open the File Manager and create a new folder for your project.
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 2/11
10/8/2017 Raspberry Pi Projects
Open a new window by clicking File > New file, and save this as app.py inside
the project folder you created.
You’ll write your application code here and when you run your code, any printed
messages or errors will be shown in the Python shell window which opened rst.
Now enter the following lines into the blank app.py window:
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello world'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Note here the host='0.0.0.0' means the web app will be accessible to any
device on the network.
Save the le with Ctrl + S. Now return to the Terminal window and enter
python3 app.py to run the web server.
If everything has been written correctly, you should see an output similar to this:
* Running on http://0.0.0.0:5000/
* Restarting with reloader
Open the Pi’s web browser from the taskbar or application menu and navigate to
http://127.0.0.1:5000/. You should see a white screen with the words Hello
world:
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 3/11
10/8/2017 Raspberry Pi Projects
Note: 127.0.0.1 means ‘home’ i.e. this computer, and :5000 means ‘port 5000’,
which is the port the web server is running on
In a web application, a route is a certain path into your website, determined by the
request sent by the user when they type it into their web browser. It’s up to you which
routes are enabled and what each of them does.
@app.route('/')
def index():
return 'Hello world'
@app.route('/'): this determines the entry point; the / means the root of the
website, so just http://127.0.0.1:5000/.
def index(): this is the name we give to the route. Here it was called index
because it’s the index of the website.
return 'Hello world': this is the content of the web page, which is returned
when the user browses the index of the website.
Create a new route by adding the following lines below the rst route:
@app.route('/cakes')
def cakes():
return 'Yummy cakes!'
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 4/11
10/8/2017 Raspberry Pi Projects
Save your code and navigate to your website’s cake page in the browser at
127.0.0.1:5000/cakes. You should see a webpage with the text Yummy cakes!
on it:
First, create a templates directory in your webapp directory by entering this into
the Terminal:
mkdir templates
<html>
<body>
<h1>Hello from a template!</h1>
</body>
</html>
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 5/11
10/8/2017 Raspberry Pi Projects
Return to your app.py le in IDLE and modify the rst line of your code to import
the render_template function as well:
Finally, you’ll need to modify your index view to return the HTML template instead
of the normal text. Change the index() function to this:
@app.route('/')
def index():
return render_template('index.html')
Flask will look for index.html in a directory called templates, in the same
directory as the app.py le.
Save the le. Make sure your web app is still running. If you stopped it, just run
python3 app.py from your webapp directory.
Reload the route in your web browser (go to the base route at
http://127.0.0.1:5000/) to see your new HTML template being displayed.
In this case it’s not much di erent as all you’ve done is added a header, but
there’s plenty of scope to expand!
First, return to the Terminal window and navigate to the webapp directory. If you’re
in the templates directory, go back up one level with cd ...
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 6/11
10/8/2017 Raspberry Pi Projects
Then open a new window with the basic text editor (Leafpad), or re-open the text
editor from the menu.
body {
background: red;
color: yellow;
}
Note here we’ve used colour names: usually colours are de ned by hex codes like
#ff0000 (red) but this is a simple example.
Now modify your HTML template called index.html to include the CSS le, by
adding a <head> tag containing a <link> tag with a reference to the stylesheet:
<html>
<head>
<link rel="stylesheet" href='/static/style.css' />
</head>
<body>
<h1>Hello from a template!</h1>
</body>
</html>
Save the HTML le and reload the web server. You should see a colourful version
of the web app!
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 7/11
10/8/2017 Raspberry Pi Projects
You have so far created a number of les and directories. It is worth just double-
checking your webapp project directory, which should contain the following and have a
structure like this now:
├── app.py
├── static
│ └── style.css
└── templates
└── index.html
If your web app doesn’t look right, check you saved your CSS le in the right place.
Now you’ll create a new route on your website so that when you go to
http://127.0.0.1/hello/name, it will say “Hello name!” and replace ‘name’ with
whatever you put there; so /hello/Paul/ will display “Hello Paul!”.
@app.route('/hello/<name>')
def hello(name):
return render_template('page.html', name=name)
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 8/11
10/8/2017 Raspberry Pi Projects
Note here we’ve neglected the <html> and <body> tags. This is OK for testing but
real websites should have a full HTML structure.
It tells the template to render the variable name which was passed in the route function
hello.
What happens when you just visit 127.0.0.1:5000/hello/ without a name? Think
about how you can prevent this giving an error.
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 9/11
10/8/2017 Raspberry Pi Projects
Enter the following command in the Terminal window to nd your Raspberry Pi’s
IP address:
hostname -I
Take another computer, tablet or smartphone, and make sure it’s connected to
the same network as the Raspberry Pi.
Open up a web browser on the other device and enter the Raspberry Pi’s IP
address into the address bar with :5000 on the end e.g.
http://192.168.1.3:5000/:
You should now see the web app from the other device. Try navigating to the
other pages too.
What next?
Try adding links between pages using anchor tags like <a
href='/hello/Paul/'>Hello Paul</a>.
Add parameters to a previous route to make other views dynamic.
Add more CSS rules to each of your routes.
Learn more about HTML, CSS and web development with Google Coder
(https://projects.raspberrypi.org/en/projects/coder-html-css-lessons/), Mozilla
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 10/11
10/8/2017 Raspberry Pi Projects
Licensed under Creative Commons "Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)"
Full project source code available at https://github.com/RaspberryPiLearning/python-web-server-with-
ask
https://projects.raspberrypi.org/en/projects/python-web-server-with-flask/print 11/11