10/Python and
the Internet
Python has a very active community of de-
velopers who often share their work in the
form of open-source libraries that simpli-
fy complex tasks.Some of these libraries
make it relatively easy for us to connect our
projects to the internet to do things like get-
ting data about the weather, send an email
or text message, follow trends on Twitter,
or act as a webserver.
In this chapter, we’re going to take a look at a few ways to create
internet-connected projects with the Raspberry Pi. We’ll start by
showing you how to fetch data from the internet and then move
into how you can create your own Raspberry Pi-based webserver.
Download Data from a Web Server
When you type an address into your web browser and hit Enter, your
browser is the
client
. It establishes a connection with the
server
,
which responds with a web page. Of course, a client doesn’t have to
be a web browser; it can also be a mail application, a weather wid-
get on your phone or computer, or a game that uploads your high
score to a global leaderboard. In the first part of this chapter, we’re
going to focus on projects that use the Raspberry Pi to act as a cli-
ent. The code you’ll be using will connect to internet servers to get
information. Before you can do that, you’ll need to install a popular
Python library called Requests that is used for connecting to web
servers via
hyper-text transfer protocol
, or HTTP.
Python and the Internet 167
GSW_RASPI_4ED_FIN.indd 167GSW_RASPI_4ED_FIN.indd 167 10/28/21 10:54 AM10/28/21 10:54 AM
To use Requests in Python, you first need to import it. Within
Terminal:
$ python3
Python3.7.3(default, Jan222021, 20:04:44)
[GCC8.3.0]onlinux
Type "help", "copyright", "credits" or "license" for
more information.
>>> import requests
>>>
If you don’t get any kind of error message, you’ll know Requests
has been imported in this Python session.
Now you can try it out:
>>> r = requests.get('http://www.google.com/')
>>>
You may be a bit disappointed at first because it seems like noth-
ing happened. But actually, all the data from the request has been
stored in the object r. Here’s how you can display the status code:
>>> r.status_code
200
The HTTP status code 200 means that the request succeeded.
There are a few other HTTP status codes inTable 10-1.
Table 10-1.
Common HTTP status codes
Code
Meaning
200 OK
301 Moved permanently
307 Moved temporarily
401 Unauthorized
404 Not found
500 Server error
If you want to see the contents of the
response
(what the server
sends back to you), try the following:
>>> r.text
168 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 168GSW_RASPI_4ED_FIN.indd 168 10/28/21 10:54 AM10/28/21 10:54 AM
If everything worked correctly, what will follow is a large block of
text; you may notice some human-readable bits in there, but most
of it will be hard to understand. This is the raw HTML of Google’s
landing page, which is meant to be interpreted and rendered on-
screen by a web browser.
However, not all HTTP requests are meant to be rendered by a web
browser. Sometimes only data is transmitted, with no information
about how it should be displayed. Many sites make these data pro-
tocols available to the public so that we can use them to fetch data
from and send data to their servers without using a web browser.
Such a data protocol specification is commonly called an
applica-
tion programming interface
, or API. APIs let different pieces of soft-
ware talk to each other and are popular for sending data from one
site to another over the Internet.
For example, let’s say you want to make a project that will sit by
your door and remind you to take your umbrella with you when rain
is expected that day. Instead of setting up your own weather sta-
tion and figuring out how to forecast the precipitation, you can get
the day’s forecast from one of many weather APIs out there.
Fetching the Weather Forecast
To determine whether or not it will rain today, we’ll show you how
to use the API from Weather Underground (www.wunderground.
com).
To use the API, take the following steps:
1. In a web browser, go to Weather Underground’s API home-
page (www.wunderground.com/weather/api) and enter your in-
formation to sign up.
2. After signing up, you’ll need to create and register a weather
station to be issued an API key. Don’t sweat it—you can register
a Raspberry Pi as a weather station.
3. Once you’ve signed up, go back to weather/api (www.wun-
derground.com/weather/api). If this is your first login, you’ll see
a notice that you don’t have any API keys assigned yet because
you must own a weather station. Click the “Learn More” button
Python and the Internet 169
GSW_RASPI_4ED_FIN.indd 169GSW_RASPI_4ED_FIN.indd 169 10/28/21 10:54 AM10/28/21 10:54 AM
to be taken to the Personal Weather Station Network page, and
then click the “Register” tab.
4. Click Add New Device” (Figure 10-1).
5. On the Add New Device page, choose Raspberry Pi from the
drop down menu under Personal Weather Station and click
“Next”.
6. Now enter your home address (or wherever you want to use
your Pi weather station) and click “Next”. On the next screen,
give your device a name and enter a height above the ground at
which your device will be stored. Accept the Privacy Agreement
and click “Next.
7. At this point your registration is complete (figure 10-2).Copy
the credentials down, as you’ll need them later, and then click
the “My Devices” button. Finally, on
that
page, click the API Keys
tab. Check the Terms of Service checkbox and click “Generate
New Key”. Your new API key will be generated and populated into
the text box. You should copy it somewhere and save it.
8. From here, if you click the “View API Documentation” button,
you’ll be taken to a Google docs page detailing the APIs that are
available to you. To learn more about how to use any of them,
click on its associated link at the right. For this project, click on
the “Forecast” link at the bottom.
9. This will take you to another Google doc page with five pages
of information about the fields available, what they each mean,
different API calls you can make, the parameters required
for each, and finally an example of a JSON response to one of
the API calls. Take a look at the first line, which shows the URL
needed to get the weather forecast at any location. Note that
embedded in the URL is your API key, as well as the latitude and
longitude of a particular weather station (I’m not sure which
one). The API key is not filled in in the example, but the latitude
and longitude are. If you want to see the forecast for any place
on earth, you can use your own API key, and just change the
location in the URL.
10. To try out the forecast API, copy the URL to your brows-
er address bar, substituting your API key where required. You
170 Getting Started with Raspberry Pi
GSW_RASPI_4ED_FIN.indd 170GSW_RASPI_4ED_FIN.indd 170 10/28/21 10:54 AM10/28/21 10:54 AM
should see the forecast data in a format called JSON, or Java
Script Object Notation (see Example 10-1). Congratulations!
You’ve just interacted with the Weather Underground’s API!
Figure 10-1.
Adding a new device
.
Figure 10-2.
Registration complete
Even though the J stands for JavaScript, JSON is used
in many programming languages, especially for com-
municating between applications via an API.
Python and the Internet 171
GSW_RASPI_4ED_FIN.indd 171GSW_RASPI_4ED_FIN.indd 171 10/28/21 10:54 AM10/28/21 10:54 AM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset