Get the Weather Forecast
This demo uses the free web service Open Weather Map.
The Open Weather Map service returns the predicted temperatures and conditions (sun, cloudy, rain etc.) for three-hour intervals for the next 40 intervals at your specified location.
You can see this using the UNIX curl command:
1 2 3 4 |
|
In this example, we are asking it to use US standard Fahrenheit (imperial units) for the city with id 5037649 which is Minneapolis, MN in the USA. You can use the Open Weather site to find the id for your city or specify the longitude and latitude of the point you want to get weather forecasts for. You can also use the GeoNames to find your city ID number.
How to Use the Open Weather Map API
To use this service, you must register and get an API key. You then put your key in the secrets.py file:
Content of secrets.py
1 |
|
The secrets.py file is then imported into your program. Make sure to put secrets.py into your .gitignore file so it will not be checked into your public GitHub repo.
The URL for the service is then created by concatenating the base URL, the city location ID and the application id:
1 2 3 |
|
Parsing the JSON file
The service returns a JSON file with the following format:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
The bulk of the data is in the list structure with 40 items with a small set of data before and after the list. The data about the HTTP status (200) and the count (40) is before the list and the data about the city is after the list.
Each block of data in the list JSON object contains data about the main data (temperature, min, max, pressure, humidity), cloud cover, wind speed and visibility. It is up to you to decide what data you would like to display within this data. Once you decide what data you want to access you can use JSON path statements to pull the right data out. For example, to get the main temperature for each time period you would run:
1 2 3 4 |
|
Sample Output
Here is the output on the Thonny shell of the first 16 temperature values:
Plotting the Forecast with Thonny Plot
Here is a plot of the temp and the "feels like" temp using the Thonny Plotter panel.
Each line has:
- a label string
- a colon
- the numeric value
for each value plotted. There can be multiple values per line.
Here is that format:
1 2 3 |
|
Sample Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
Displaying Predicted Temperatures in a Thonny Plot
Thonny has a Plot object that you can use to display the relative temperature for the next 40 3-hour cycles.
To do this, we only need to print out the temperatures each on a separate line:
1 2 3 |
|