How To Build A Weather App With Pyt
How To Build A Weather App With Pyt
In this tutorial, we will build a simple weather web application using Python and
Django. It will show current weather conditions in a certain city. We will also use
ClimaCell Weather API to get weather data for our application.
How to obtain access to the ClimaCell API.
To obtain access to the ClimaCell API, you first need to sign up on RapidAPI. Next,
subscribe to the pricing plan, and that’s it. Now you are able to make a request to
the ClimaCell API. For this tutorial, using a free Basic plan will be sufficient.
How to work with the ClimaCell API
You can test ClimaCell API directly in the browser on the RapidAPI site. This
functionality also provides a code snippet with a query to the API in many
programming languages.
You can also see what the data sent by the API looks like. Click “Test Endpoint”
and go to bookmark “Results”.
ClimaCell API can provide data in the following different time frames:
To begin the project you can start a virtual environment named, for example,
Django_web. Change the directory to “Django_web” in your terminal or command line.
Then install Django and a couple of other dependencies, that we will use in this
project, by running the next command:
pipenv install django requests pandas
After that, Django will create a WeatherSite folder with some other folders and
Python files. Now we can run the server and check whether it works. Navigate to a
WeatherSite directory and run the command:
python manage.py runserver
Look at the terminal and view the URL for your web application. By default it is
127.0.0.1:8000.
In general, a Django project consists of several apps. Every app refers to specific
functionality in the project. Examples of apps on websites are: forum, login page,
shop, news, etc. We will create an app called the weather. Press Ctrl+C to stop the
Django server and run the command:
python manage.py startapp weather
As you can see, Django has added a weather directory and some files in our project.
The next step is to register our app in Django. Open settings.py in the WeatherSite
directory and add the weather app to the INSTALLED_APPS list:
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘weather’,
]
This tells Django that we want to use a weather app in our project.
We also need to provide Django with the URL that will be used by the weather app.
Open file urls.py in the WeatherSite folder and modify it in the following way:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path(‘admin/’, admin.site.urls),
path(”, include(‘weather.urls’)),
]
This tells Django that if we open URL 127.0.0.1:8000 with no other additions, it
will redirect us to the weather app. If you want to use a few apps in your project,
the path may be, for example, “weather/”. This means that the URL for the weather
app will be 127.0.0.1:8000/weather/. Since we have only one app in our project, we
won’t use an endpoint for the entry point to our app.
3. Views and Templates
This instruction tells Django that if we open URL 127.0.0.1:8000 it will run a
function called “index” in the views.py file.
We haven’t created it yet, so let’s fix it.
from django.shortcuts import render
def index(request):
return render(request, ‘weather/index.html’)
For now, this function only renders the index.htm file. This is a template for our
weather app. Go to the weather directory and create a directory named “templates”.
Then go to the templates directory and create a directory named “weather”. Inside
of the weather directory create a file called index.html. Here is the HTML we’ll
use for our template:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>WeatherApp</title>
<link rel=“stylesheet” href=“https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-
alpha1/css/bootstrap.min.css”>
</head>
<body>
<div align=“center”>
<h1>Weather in your city</h1>
<form action=“” method=“get”>
<input type=“text” id=“city” name=“city” placeholder=“Enter city”>
<input type=“submit” name=“send” value=“Search”>
</form>
</div>
</body>
</html>
After all these actions, we can test our app. Go to your project root (WeatherSite
directory), start the server, and go to 127.0.0.1:8000.
Now you can see the result of your HTML in the index.html file. You’ll see an input
to see the weather in a specific city. But it doesn’t show any weather for now. In
the next steps, we will use the ClimaCell API to show the weather in the city
specified in the form.
4. Getting coordinates of the city
Since ClimaCell API uses latitude and longitude in requests to return the weather
data, we need to get coordinates of the city specified in the form. To do this we
need some data of city coordinates. For this app, we will use the World Cities
Database provided by simplemaps.com. Please download a free basic database. Unpack
the wordcities.csv file in the main folder of the project (WeatherSite). In order
to read wordcities.csv and search coordinates of cities we will use a python
library called pandas.
Modify views.py in the weather directory:
from django.shortcuts import render
import pandas as pd
def index(request):
df = pd.read_csv(‘worldcities.csv’)
city = ‘Tokyo’
lat = df[df[‘city_ascii’] == city][‘lat’] lon = df[df[‘city_ascii’] == city]
[‘lng’]print(lat)
print(‘n’)
print(lon)
return render(request, ‘weather/index.html’)
Let’s run the server and go to 127.0.0.1:8000. As you can see our site didn’t
change in the browser. But we have the coordinates of Tokyo printed in the output.
0 35.685
Name: lat, dtype: float64
0 139.7514
Name: lng, dtype: float64
Since we can get the latitude and longitude of the city, we can start working with
ClimaCell API. Go to the ClimaCell API Endpoints on the RapidAPI and choose
“Realtime” on the left side and Python(Requests) in the Code Snippets. Copy this
code to the index function in views.py and modify it a little.
from django.shortcuts import render
import pandas as pd
import requests
def index(request):
df = pd.read_csv(‘worldcities.csv’)
city = ‘Tokyo’
lat = df[df[‘city_ascii’] == city][‘lat’] lon = df[df[‘city_ascii’] == city]
[‘lng’]url =
“https://climacell-microweather-v1.p.rapidapi.com/weather/realtime”querystring =
{“unit_system”: “si”,
“fields”: [“precipitation”, “precipitation_type”, “temp”, “cloud_cover”,
“wind_speed”,
“weather_code”], “lat”: lat, “lon”: lon}headers = {
‘x-rapidapi-host’: “climacell-microweather-v1.p.rapidapi.com”,
‘x-rapidapi-key’: “a1ca7cac7bmsh7481cbdd1b05541p170fb7jsnfb74af885ed7”
}response = requests.request(“GET”, url, headers=headers,
params=querystring).json()
print(response)
return render(request, ‘weather/index.html’)
Now we have weather data for Tokyo obtained from the ClimaCell API. Then you can
stop the server.
6. Displaying the weather data
Since we have the data, we can display it on the website. Instead of printing the
data to the output, let’s save it in the dictionary called context. To make data
from context available for our template, we also need to add it as a third argument
in the render function.
…
def index(request):
…
context = {‘city_name’: city,
‘temp’: response[‘temp’][‘value’],
‘weather_code’: response[‘weather_code’][‘value’],
‘wind_speed’: response[‘wind_speed’][‘value’],
‘precipitation_type’: response[‘precipitation_type’][‘value’] }
return render(request, ‘weather/index.html’, context)
…
We need to modify the HTML inside the index.html to use variables from the context
dictionary. Variables will use {{ }} tags.
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>WeatherApp</title>
<link rel=“stylesheet” href=“https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-
alpha1/css/bootstrap.min.css”>
</head>
<body>
<div align=“center”>
<h1>Weather in your city</h1>
<form action=“” method=“get”>
<input type=“text” id=“city” name=“city” placeholder=“Enter a city”>
<input type=“submit” name=“send” value=“Search”>
</form>
<p>
<h3>The weather in {{city_name}} is:</h3>
<div>Weather conditions: {{weather_code}}</div>
<div>Temperature: {{temp}} <sup>o</sup>C</div>
<div>Wind speed: {{wind_speed}} m/s</div>
<div>The type of precipitation: {{precipitation_type}}</div>
</p>
</div>
</body>
</html>
Now our app gets data from the ClimaCell API and displays current weather in Tokyo
on the web page. The next and last step is to make our form work. Stop the server.
The data from our form will be sent to the backend by GET request because we don’t
need to modify any database, we will just receive the city name and display the
weather. Let’s change our index function in views.py. The final version of views.py
will be:
from django.shortcuts import render
import requests
import pandas as pd
def index(request):
df = pd.read_csv(‘worldcities.csv’)
if ‘city’ in request.GET:
city = request.GET[‘city’] if df[df[‘city_ascii’] == city][‘city_ascii’].any():
lat = df[df[‘city_ascii’] == city][‘lat’] lon = df[df[‘city_ascii’] == city]
[‘lng’]url =
“https://climacell-microweather-v1.p.rapidapi.com/weather/realtime”querystring =
{“unit_system”: “si”,
“fields”: [“precipitation”, “precipitation_type”, “temp”, “cloud_cover”,
“wind_speed”,
“weather_code”], “lat”: lat, “lon”: lon}headers = {
‘x-rapidapi-host’: “climacell-microweather-v1.p.rapidapi.com”,
‘x-rapidapi-key’: “a1ca7cac7bmsh7481cbdd1b05541p170fb7jsnfb74af885ed7”
}response = requests.request(“GET”, url, headers=headers,
params=querystring).json()
context = {‘city_name’: city,
‘temp’: response[‘temp’][‘value’],
‘weather_code’: response[‘weather_code’][‘value’],
‘wind_speed’: response[‘wind_speed’][‘value’],
‘precipitation_type’: response[‘precipitation_type’][‘value’] }
else:
context = None
else:
context = None
return render(request, ‘weather/index.html’, context)
Now the index function will check whether the request method is GET. If it is true,
the function will search for the city variable obtained from the form. If the
request contains the city variable, the index function will search the city’s
coordinates. Then the index function will send the request to the ClimaCell API,
obtain the weather data, write it to the context dictionary and render the
template.
The last thing we need is to modify index.html:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>WeatherApp</title>
<link rel=“stylesheet” href=“https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-
alpha1/css/bootstrap.min.css”>
</head>
<body>
<div align=“center”>
<h1>Weather in your city</h1>
<form action=“” method=“get”>
<input type=“text” id=“city” name=“city” placeholder=“Enter a city”>
<input type=“submit” name=“send” value=“Search”>
</form>
{% if city_name %}
<p>
<h3>The weather in {{city_name}} is:</h3>
<div>Weather conditions: {{weather_code}}</div>
<div>Temperature: {{temp}} <sup>o</sup>C</div>
<div>Wind speed: {{wind_speed}} m/s</div>
<div>The type of precipitation: {{precipitation_type}}</div>
</p>
{% endif %}
</div>
</body>
</html>
We added an ‘if’ statement to the HTML. Now it checks if the context contains a
city_name variable. If it does, the template will display weather in the city that
was specified in the form.
Website testing
Our weather app is finished. Let’s check how it works! First of all, start the
server and go to 127.0.0.1:8000.
As you can see, when you enter the site for the first time or don’t specify a city
and hit the Search button, it doesn’t display any weather.
Let’s find out what the weather looks like in New York, for example.
Now we have a simple weather app written in Python using the Django framework. It
shows the real-time weather conditions in a specific city. We’ve used Django’s
aspects like views, URLs, and templates. We’ve also learned how to work with the
API to get weather data for our app.
The next possible step to improve your skills might be adding a weather forecast to
the app. The free basic plan of ClimaCell API provides daily and hourly weather
forecasts. Another option is to show the weather in several cities.
4.5/5 - (2 votes)
« How to use Amazon Product/Review APIs in JavaScript
How To Build a Text to Speech Service with Python Flask Framework (Speech
Recognition) »
Filed Under: Django, Python API Tutorials, REST API Tutorials Tagged With:
ClimaCell, django, python, Weather, Weather API
> python manage.py runserver