You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: worksheet.md
+50-40Lines changed: 50 additions & 40 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,10 @@
1
-
# Build a Pythonpowered Web Server with Flask
1
+
# Build a Python-powered web server with Flask
2
2
3
-
Install the lightweight web framework Flask and set up a basic web server with different pages using Python, HTML, and CSS.
3
+
Install the lightweight web framework Flask and set up a basic web server with different pages, using Python, HTML, and CSS.
4
4
5
5
## Installing pip and Flask
6
6
7
-
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.
7
+
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.
8
8
9
9
1. Start by opening a Terminal window from the taskbar or applications menu:
10
10
@@ -15,13 +15,15 @@ First you're going to install the Flask package. Make sure you are connected to
15
15
```bash
16
16
sudo apt-get install python-pip
17
17
```
18
+
18
19
`pip` is a tool for installing Python packages from the Python Packaging Index (PyPi): you can browse packages at [pypi.python.org](https://pypi.python.org/).
19
20
20
21
1. Now use `pip` to install Flask by typing:
21
22
22
23
```bash
23
24
sudo pip install flask
24
25
```
26
+
25
27
And press **enter**.
26
28
27
29
## Building a basic Flask web application
@@ -34,30 +36,33 @@ Now you're going to set up a basic web application with Flask and Python. You wi
34
36
mkdir webapp
35
37
```
36
38
37
-
`mkdir` means "make directory": a directory is a folder. It can contain files and more folders.
39
+
`mkdir` means "make directory": a directory is a folder which can contain files and more folders.
38
40
39
-
1. Navigate into this directory using the `cd` command and pressing **enter**:
41
+
1. Navigate into this directory by using the `cd` command and pressing **Enter**:
40
42
41
43
```bash
42
44
cd webapp
43
45
```
46
+
44
47
`cd` means "change directory": you use it to enter a folder.
45
48
46
-
1. Flask applications can be run from a single file, so you need to create the file now using the touch command like this:
49
+
1. Flask applications can be run from a single file, so you need to create the file now using the `touch` command, like this:
47
50
48
51
```bash
49
52
touch app.py
50
53
```
54
+
51
55
This will create a file named `app.py`, in which all our application code will be written.
52
56
53
-
1. Enter the following command to open this file in **Python 2**, also called IDLE which is a Python editor, in order to get started writing your web app:
57
+
1. Enter the following command to open this file in the **Python 2** IDE (IDLE), in order to get started writing your web app:
54
58
55
59
```bash
56
60
idle app.py &
57
61
```
58
-
The ampersand (&) on the end of this command tells it to open Python 2 (IDLE) in a new process. Unlike a command like `cd`, this command doesn't "finish"until you close the Python 2 (IDLE) window. Opening IDLE in a new process allows you to enter more commands into the Terminal without quitting (IDLE).
62
+
63
+
The ampersand (&) on the end of this command tells it to open IDLE in a new process. Unlike a command like `cd`, this command doesn't finish until you close the IDLE window. Opening IDLE in a new process allows you to enter more commands into the Terminal without quitting IDLE.
59
64
60
-
1. An empty window with `app.py` displayed in the title bar will appear. You'll write your application code here and when you run your code any printed messages or errors will be shown in a Python shell window.
65
+
1. An empty window with `app.py` displayed in the title bar will appear. You'll write your application code here and when you run your code, any printed messages or errors will be shown in a Python shell window.
61
66
62
67
1. Now enter the following lines into the blank `app.py` window:
63
68
@@ -73,6 +78,7 @@ Now you're going to set up a basic web application with Flask and Python. You wi
73
78
if __name__ == '__main__':
74
79
app.run(debug=True, host='0.0.0.0')
75
80
```
81
+
76
82
Note here the `host='0.0.0.0'` means the web app will be accessible to any device on the network.
77
83
78
84
1. Save the file with `Ctrl + S`. Now return to the Terminal window and enter `python app.py` to run the web server.
@@ -84,31 +90,31 @@ Now you're going to set up a basic web application with Flask and Python. You wi
84
90
* Restarting with stat
85
91
```
86
92
87
-
1. Open the Pi's web browser from the taskbar or application menu and enter`http://127.0.0.1:5000/`. You should see a white screen with the words `Hello world`:
93
+
1. 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`:
*Note: `127.0.0.1` means 'home'- this computer, and `:5000` means 'port 5000', which is the port the web server is running on*
97
+
*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*
92
98
93
99
## Adding a new route to your web app
94
100
95
101
Now you're going to add a new route to your web app, which will create another web page.
96
102
97
-
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.
103
+
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.
98
104
99
-
In the "Hello Raspberry Pi" example we used a single route:
105
+
In the "Hello World" example we used a single route:
100
106
101
107
```python
102
108
@app.route('/')
103
109
def index():
104
110
return'Hello world'
105
111
```
106
112
107
-
This route is page up of three parts:
113
+
This route is made up of three parts:
108
114
109
115
- `@app.route('/')`: this determines the entry point; the `/` means the root of the website, so just `http://127.0.0.1:5000/`.
110
116
- `def index()`: this is the name we give to the route. Here it was called `index` because it's the index of the website.
111
-
- `return 'Hello world'`: this is the content of the web page which is returned when the user browses the index of the website.
117
+
- `return 'Hello world'`: this is the content of the web page, which is returned when the user browses the index of the website.
112
118
113
119
1. Create a new route by adding the following lines below the first route:
114
120
@@ -124,9 +130,9 @@ This route is page up of three parts:
124
130
125
131
## Add HTML templates to your web app
126
132
127
-
Next you'll modify your existing routes to return full HTML templates rather than simple text strings.
133
+
Next, you'll modify your existing routes to return full HTML templates, rather than simple text strings.
128
134
129
-
1. First create a `templates` directory in your `webapp` directory by entering this into the Terminal:
135
+
1. First, create a `templates` directory in your `webapp` directory by entering this into the Terminal:
130
136
131
137
```bash
132
138
mkdir templates
@@ -136,7 +142,7 @@ Next you'll modify your existing routes to return full HTML templates rather tha
136
142
137
143

138
144
139
-
This will open up a basic text editor called Leafpad
145
+
This will open up a basic text editor called Leafpad.
140
146
141
147
1. Enter the following HTML code:
142
148
@@ -148,22 +154,23 @@ Next you'll modify your existing routes to return full HTML templates rather tha
148
154
</html>
149
155
```
150
156
151
-
1. Save the file as `index.html` in the `templates` directory which you'll find inside `pi` and then`webapp` directories.
157
+
1. Save the file as `index.html` in the `templates` directory, which you'll find inside the`pi` and then`webapp` directories.
152
158
153
159
1. Return to your `app.py` file in IDLE and modify the first line of your code to import the `render_template`functionas well:
154
160
155
161
```python
156
162
from flask import Flask, render_template
157
163
```
158
164
159
-
1. 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:
165
+
1. 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:
160
166
161
167
```python
162
168
@app.route('/')
163
169
def index():
164
170
return render_template('index.html')
165
171
```
166
-
Flask will look for `index.html` in a directory called `templates` in the same directory as the `app.py` file.
172
+
173
+
Flask will look for `index.html` in a directory called `templates`, in the same directory as the `app.py` file.
167
174
168
175
1. Save the file. Make sure your web app is still running. If you stopped it, just run `python app.py` from your `webapp` directory.
169
176
@@ -177,11 +184,11 @@ Next you'll modify your existing routes to return full HTML templates rather tha
177
184
178
185
Cascading Style Sheets (CSS) are rules for how HTML content is displayed by the browser. Now you'll add some CSS to add colour to your web page.
179
186
180
-
1. First, return to the Terminal window and navigate to the `webapp` directory. If you're in the `templates` directory, go back up one with `cd ..`.
187
+
1. 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 ..`.
181
188
182
-
1. Create a new directory called `static`
189
+
1. Create a new directory called `static`.
183
190
184
-
1. Then open a new window with the basic Text Editor (Leafpad), or re-open the Text Editor from the menu.
191
+
1. Then open a new window with the basic text editor (Leafpad), or re-open the text editor from the menu.
185
192
186
193
1. Save the new file as `style.css`in the new `static` directory.
187
194
@@ -193,11 +200,12 @@ Cascading Style Sheets (CSS) are rules for how HTML content is displayed by the
193
200
color: yellow;
194
201
}
195
202
```
203
+
196
204
Note here we've used colour names: usually colours are defined by hex codes like `#ff0000` (red) but this is a simple example.
197
205
198
206
1. Save the file.
199
207
200
-
1. Now modify your HTML template called `index.html` to include the CSS file by adding a `<head>` tag containing a `<link>` tag with a reference to the stylesheet:
208
+
1. Now modify your HTML template called `index.html` to include the CSS file, by adding a `<head>` tag containing a `<link>` tag with a reference to the stylesheet:
201
209
202
210
```html
203
211
<html>
@@ -214,7 +222,7 @@ Cascading Style Sheets (CSS) are rules for how HTML content is displayed by the
214
222
215
223

216
224
217
-
You have so far created a number of files and directories. It is worth just doublechecking your `webapp` project directory which should contain the following and have a structure like this now:
225
+
You have so far created a number of files and directories. It is worth just double-checking your `webapp` project directory, which should contain the following and have a structure like this now:
218
226
219
227
```
220
228
├── app.py
@@ -230,7 +238,7 @@ If your web app doesn't look right, check you saved your CSS file in the right p
230
238
231
239
So far you've learned to deliver HTML template through a web server running on your Raspberry Pi. Wouldn't it be good if you could add some dynamic content to the pages to display different information? Large websites like Facebook, YouTube and BBC News show different content depending on the route you visit, even though the templates are very similar.
232
240
233
-
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!"
241
+
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!".
234
242
235
243
1. Create a new route in your application like so:
236
244
@@ -240,15 +248,16 @@ Now you'll create a new route on your website so that when you go to `http://127
240
248
return render_template('page.html', name=name)
241
249
```
242
250
243
-
- `@app.route('/hello/<name>')` - the `<name>` part means it pass the name into the `hello` function as a variable called `name`
244
-
- `def hello(name)` - this is the function that determines what content is shown - this time it takes a parameter: the given name
251
+
- `@app.route('/hello/<name>')` - the `<name>` part means it passes the name into the `hello` function as a variable called `name`
252
+
- `def hello(name)` - this is the function that determines what content is shown - this time it takes the given name as a parameter
245
253
- `return render_template('page.html', name=name)` - here we look up the template `page.html` and pass in the variable `name` from the URL, so the template can use it
246
254
247
-
1. Create a new HTML template called `page.html` using the Text Editor, and add the following HTML code to it:
255
+
1. Create a new HTML template called `page.html` using the text editor, and add the following HTML code to it:
248
256
249
257
```html
250
258
<h1>Hello {{ name }}!</h1>
251
259
```
260
+
252
261
Note here we've neglected the `<html>` and `<body>` tags. This is OK for testing but real websites should have a full HTML structure.
253
262
254
263
1. Save the files, reload the web server and visit `http://127.0.0.1:5000/hello/paul`. It should look like this:
@@ -257,7 +266,7 @@ Now you'll create a new route on your website so that when you go to `http://127
257
266
258
267
Try it with different names!
259
268
260
-
What's happening here?
269
+
### What's happening here?
261
270
262
271
Flask uses `jinja`, a Python library for rendering templates. Use the braces (curly brackets) on this line:
263
272
@@ -278,22 +287,23 @@ Since we used `host='0.0.0.0'`, on the `app.run` line, the web server is accessi
278
287
```bash
279
288
hostname -I
280
289
```
281
-
You should get something like `192.168.1.3`
290
+
291
+
You should get something like `192.168.1.3`.
282
292
283
-
1. Take another computer, tablet, or smartphone, and make sure it's connected to the same network as the Raspberry Pi.
293
+
1. Take another computer, tablet or smartphone, and make sure it's connected to the same network as the Raspberry Pi.
284
294
285
-
1. 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/`:
295
+
1. 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/`:
286
296
287
297

288
298
289
299
1. You should now see the web app from the other device. Try navigating to the other pages too.
290
300
291
301
## What next?
292
302
293
-
- Try adding links between pages using anchor tags like `<a href='/hello/Paul/'>Hello Paul</a>`
294
-
- Add parameters to a previous route to make other views dynamic
295
-
- Add more CSS rules to each of your routes
296
-
- Learn more about HTML, CSS, and web development with [Google Coder](https://www.raspberrypi.org/learning/coder-html-css-lessons/), [Mozilla Developer Network](https://developer.mozilla.org/en-US/Learn) and [Codecademy](https://www.codecademy.com/en/tracks/web)
297
-
- Learn more about Flask using the [Flask documentation](http://flask.pocoo.org/docs)
298
-
- Create a physical computing project with Raspberry Pi and use Flask to create a web interface to it (see [Matt Richardson's guide](http://mattrichardson.com/Raspberry-Pi-Flask/index.html), [BETT Bot](https://github.com/bennuttall/bett-bot) and [Energenie](http://www.pythonhosted.org/energenie/examples/web/))
303
+
- Try adding links between pages using anchor tags like `<a href='/hello/Paul/'>Hello Paul</a>`.
304
+
- Add parameters to a previous route to make other views dynamic.
305
+
- Add more CSS rules to each of your routes.
306
+
- Learn more about HTML, CSS and web development with [Google Coder](https://www.raspberrypi.org/learning/coder-html-css-lessons/), [Mozilla Developer Network](https://developer.mozilla.org/en-US/Learn) and [Codecademy](https://www.codecademy.com/en/tracks/web).
307
+
- Learn more about Flask using the [Flask documentation](http://flask.pocoo.org/docs).
308
+
- Create a physical computing project with Raspberry Pi and use Flask to create a web interface to it (see [Matt Richardson's guide](http://mattrichardson.com/Raspberry-Pi-Flask/index.html), [BETT Bot](https://github.com/bennuttall/bett-bot) and [Energenie](http://www.pythonhosted.org/energenie/examples/web/)).
299
309
- Use a Flask web app as the control panel in a home automation project: turn the lights on from your phone!
0 commit comments