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;
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
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"]
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())
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"])
Now assign the win10toast()
function to a variable of your choosing like so.
toaster = ToastNotifier()
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)
Output
If everything worked out fine, you should get the following output on your screen.
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)