DEV Community

Cover image for Windows Notifier for Covid Stats | Rookie Week of Python Day 02
Hannan
Hannan

Posted on • Updated on

Windows Notifier for Covid Stats | Rookie Week of Python Day 02

In this article we will be creating a simple windows alert application that pulls data from a rest API. We will be using our program to pull live Covid-19 statistics and push them to the screen

Windows Notifier Application

What will we need are the python requests and the win10toast libraries. They can be installed by the follow pip install commands in your preferred command terminal.
pip install requests
pip install win10toast

Now to import the libraries we will simply use the import statements

import requests;
from win10toast import ToastNotifier;
import datetime;
Enter fullscreen mode Exit fullscreen mode

We will first check the connection to our rest API with a try & except block. We will store the output from our API in a variable named data

try:
    data = requests.get("http://corona-rest-api.herokuapp.com/Api/pakistan")
except:
    print("You are not connected to a network. Please check internet connection.")
    data = None
Enter fullscreen mode Exit fullscreen mode

If the API returns some data then our data variable will not be null and we can use an if statement with the following variable declarations.

if data is not None:
    getData = data.json()
    covidPK = getData["Success"]
Enter fullscreen mode Exit fullscreen mode

Declare a variable named title to hold the title string and use the format() finction to place the date and time.

title ="""Covid Pakistan / {}""".format(datetime.date.today())
Enter fullscreen mode Exit fullscreen mode

Similarly declare a variable for the message body and use the covidPK variable to pull the appropriate data from the API.

message="""In Pakistan Covid-19 Cases: {}, Deaths: {}, Recovered: {}, Cases Today: {}""".format(covidPK["cases"],covidPK["deaths"],covidPK["recovered"],covidPK["todayCases"])
Enter fullscreen mode Exit fullscreen mode

Now assign the win10toast() function to a variable of your choosing like so.

toaster = ToastNotifier()
Enter fullscreen mode Exit fullscreen mode

Finally, push the values to the windows alert message. Use icon_path to point to an .ico format file which will act as the icon for the notification. Use duration to define the time in seconds for how long the alert will stay visible on screen.

toaster.show_toast(title, message, icon_path="E:\Software\Python 3\Python Projects/covid-icon.ico", duration=10)
Enter fullscreen mode Exit fullscreen mode

Output

If everything worked out fine, you should get the following output on your screen.
Alt Text

You can also check out the code on it's GitHub repo here. Thank you for reading. Don't forget to check in tomorrow for more, cheers!

Top comments (0)