How to Create a Weather Alert System in Python | by Ng Wai Foong | Towards Data Science

By reading this piece, you will learn to create a weather alert system in Python that will send an email notification to multiple recipients when it forecasts that the sky will rain/snow in the next few hours. The email notification contains additional information such as the forecast-ed temperature and humidity.
There are 4 sections in this tutorial:
SetupImplementationResultConclusion
Setup
Implementation
Result
Conclusion
Let’s proceed to the next section.
I am going to use ClimaCell’s weather API in getting the forecasted weather data. It provides quite a number of useful and accurate data depends on your needs.
At the time of this writing, it covers historical station data up to 4 weeks back as well as daily forecast data up to 15 days ahead. Besides, you can easily implement it as the official documentation provides references for 4 different computer languages:
JavaScript
Ruby
Node
Python
Once you have signed up for it, you will be placed under free tier which allow you to make 1000 call per day and 100 per hour. It should be more than enough for our use case.
Head over to the sign up and and register a new account. Once you are done, you should see the following dashboard which outlines the plan details and your call activity.
Take note of the API key as we are going to use it in our code later on.
I am going to use a personal Gmail account to send the email to myself via SMTP. In order to use it, you need to change the configuration in the account setting and turn on the Less secure app access.
Head over to the account setting and click on the security menu.
Turn on the Less secure app access as follow
Once you are done, create a new file called config.ini in the root directory of your project. It will be used as the configuration files for our project. Append the following code inside it.
[email]email=your_email@gmail.comhost=smtp.gmail.comport=587password=your_password
email — Name of your email account
host — Host name for the smtp server. Modify this based on the smtp server for your email
port — Port for the smtp server. Modify this based on the smtp server for your email
password — Password to your email account. Make sure not to disclose this file or information to other people.
Creating a virtual environment is highly recommended for this project. Run the following command in the terminal to install configparser module. It is extremely useful in loading the configuration setting from a file.
pip install configparser
Let’s move on to the section section and start writing Python code.
Create a new file called weather_email.py in the same directory as config.ini. This file serve as the email module for our application.
Add the following import declaration at the top of the file
try:    import configparserexcept:    from six.moves import configparserimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport requests
Next, create a dictionary that represent the messages that we are going to send when there is rain or snow. You can create your own mapping or custom messages based on your use case.
weather_dict = {'freezing_rain_heavy': 'Heavy rain and snow', 'freezing_rain': 'Rain and snow', 'freezing_rain_light': 'Light rain and snow', 'freezing_drizzle': 'Light drizzle and snow', 'ice_pellets_heavy': 'Heavy ice pellets', 'ice_pellets': 'Normal ice pellets', 'ice_pellets_light': 'Light ice pellets', 'snow_heavy': 'Heavy snow', 'snow': 'Normal snow', 'snow_light': 'Light snow', 'tstorm': 'Thunder storm', 'rain_heavy': 'Heavy rain', 'rain': 'Normal rain', 'rain_light': 'Light rain'}
Initialize the following variables which are required when we call the weather API.
url = "https://api.climacell.co/v3/weather/nowcast"querystring = {"lat":"1.29027","lon":"103.851959","unit_system":"si","timestep":"60","start_time":"now","fields":"temp,humidity,weather_code","apikey":"xxxx"}
We are going to call the nowcast API which has the following parameters that can be modified:
lat — Latitude, -87 to 89
lot — Longitude, -180 to 180
unit_system — Unit system, “si” or “us”
timestep — Time step in minutes, 1 to 60. Setting start_time to now and timestep of 60 will return 7 datapoints. (Now, 60 minutes later, 120 minutes later, ...)
start_time — You can set your own time or just initialize it to now
end_time — Optional argument to restrict the end time. By default, it will return the data up to 6 hours from the current timestamp.
fields — Selected fields from the data layers provided (such as “precipitation” or “wind_gust”). I am using temp, humidity and weather_code for this tutorial.
apikey — The API key from the dashboard of Climacell Weather API.
We are going to create a new class called EmailSender and initialize it as follow. We utilize the configparser module to read the data from config.ini and assign it to the respective variables.
def __init__(self):    self.cf = configparser.ConfigParser()    self.cf.read('./config.ini')    self.sec = 'email'    self.email = self.cf.get(self.sec, 'email')    self.host = self.cf.get(self.sec, 'host')    self.port = self.cf.get(self.sec, 'port')    self.password = self.cf.get(self.sec, 'password')
Create another function inside the class called SendEmail which accepts a recipient parameter. It accepts a list instead of string. This allows us to send the same email notifications to multiple email addresses.
def SendEmail(self, recipient):
Inside the function, initialize a new MIMEMultipart object with the following
title = "Home Sweet Home"msg = MIMEMultipart()msg['Subject'] = '[Weather Notification]'msg['From'] = self.emailmsg['To'] = ', '.join(recipient)
The next step is to call the API via requests module which will return the result as json.
response = requests.request("GET", url, params=querystring)result = ""json_data = response.json()
You can make full use of the result and map it to the dictionary that we have specified above in order to create the desired notification message. Then, initialize a MIMEText object with it and attach it to the MIMEMultipart object. Wrap it up by calling the smtplib.SMTP context manager to send the email.
msgText = MIMEText('<b>%s</b><p>%s</p>' % (title, result), 'html')msg.attach(msgText)with smtplib.SMTP(self.host, self.port) as smtpObj:    smtpObj.ehlo()    smtpObj.starttls()    smtpObj.login(self.email, self.password)    smtpObj.sendmail(self.email, recipient, msg.as_string())
Check out the following gist for the complete code.
You should have the following files in your root directory.
config.ini
weather_email.py
You can easily trigger the email alert functionality in any of your Python application as long as both files reside in the same directory as the Python file that you called. Simply modify the import statement based on your use case. The following example outlines the code that will send an email notification to two recipients if it is going to rain or snow in the next 6 hours.
import weather_emailemail_obj = weather_email.EmailSender()email_obj.SendEmail(["email@gmail.com", "email2@gmail.com"])
Let’s have a look at the following result when I ran the test. I got a notification informing me that it is raining lightly at my house.
I ran the same code once the rain stopped and it forecasted that it will rain again in 6 hours’ time. Perhaps I should head back and collect all my clothes off the drying rack before it rains.
Let’s recap what we have learned today.
We started off with signing up to get the apikey for access to weather data and changing the security setting in Gmail to allow Less secure app access for our tutorial. Besides, we have created a simple configuration files which stored the email authentication data.
Next, we implemented a Python module which will call the weather API and send an email notification whenever there is snow or rain in the next 6 hours.
By now, you should be able to create your own weather alert system based on the use case that you have. Thanks for reading this piece and hope to see you again in the next article!
How to Create A Weather ChatbotTips and Tricks for Handling Configuration Files in Python
How to Create A Weather Chatbot
Tips and Tricks for Handling Configuration Files in Python