Welcome to my blog series Fun with Function Apps where we will be learning about function apps their implementation through amazing use cases.
In this blog, we are create two function apps - HTTP Trigger & Timer Trigger which will help us create a newsletter consisting of COVID-19 India daily stats. The users can subscribe/ unsubscribe to the newsletter through the website
Lets get started...
The architecture of the solution will be as follows
Pre-requisites
- Azure Account - (Free)
- Basic Python Programming
- Basic Web Development Skills (HTML, CSS & JS)
Warning: Kindly be aware of the incurring costs
Step 1. Setting up Storage Account
Go to Azure Portal and create a storage account. Under the storage account, create a table with ParitionKey, RowKey and email as its columns.
Make note of the table name, storage account name, key for the later use.
Step 2. Creating HTTP Trigger Function App
The purpose of the HTTP Trigger Function App is to perform subscribe and unsubscribe actions and the respective data will be updated in the Storage Account table.
Follow the steps given here to create a Python HTTP Trigger Function App
Replace the init.py code with the following and substitute all the necessary requirements.
import logging | |
import random | |
import azure.functions as func | |
from azure.cosmosdb.table.tableservice import TableService | |
def main(req: func.HttpRequest) -> func.HttpResponse: | |
logging.info('Python HTTP trigger function processed a request.') | |
action = req.params.get('action') | |
email = req.params.get('email') | |
table_service = TableService(account_name='', account_key='') #insert account name and key | |
if action == "subscribe": | |
count = 0 | |
tasks = table_service.query_entities('mailinglist', filter="email eq '"+email+"'") | |
for task in tasks: | |
if task: | |
count+=1 | |
if count == 1: | |
message = "You have already subscribed to the mailing list" | |
else: | |
rk = random.randint(5,10000000) | |
task = {'PartitionKey': '1', 'RowKey': str(rk),'email': email} | |
table_service.insert_entity('mailinglist', task) | |
message = "Your email has been successfully added to the Mailing List. You will start receiving updates every day at 6:00pm IST" | |
if action == "unsubscribe": | |
count = 0 | |
tasks = table_service.query_entities('mailinglist', filter="email eq '"+email+"'") | |
for task in tasks: | |
if task: | |
count+=1 | |
if count ==1: | |
table_service.delete_entity('mailinglist', task['PartitionKey'], task['RowKey']) | |
message = "You have unsubscribed from COVID-19 Daily stats." | |
else: | |
message = "Email Address not found. Kindly check your email address" | |
return func.HttpResponse( | |
message, | |
status_code=200 | |
) |
After deploying your app, copy the function url.
To subscribe sample@sample.com
< function url > /api/HttpTrigger?action=subscribe&email=sample@sample.com
To unsubscribe sample@sample.com
< function url > /api/HttpTrigger?action=unsubscribe&email=sample@sample.com
Step 3: Create SendGrid Account
To send the mails, you need require SendGrid Account. Follow the steps to generate your SendGrid API Key.
Step 4: Create Timer Trigger Function App
Follow the steps in this tutorial to create a Timer Trigger Function App. Also, make sure you select Python Run Time.
We need to send the COVID-19 email newsletter at 6pm IST to all the subscribers.
Use the NCRONTAB schedule : 0 30 12 * * *
Add the SendGrid bindings to your function.json file
{
"scriptFile": "__init__.py",
"version": "2.0",
"bindings": [
{
"name": "mytimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 30 12 * * *"
},
{
"type": "sendGrid",
"name": "sendGridMessage",
"direction": "out",
"apiKey": "sendgrid_api",
"from": "vivekraja98@gmail.com"
}
],
"disabled": false
}
The init.py to send the emails on schedule is as follows
import datetime | |
import logging | |
import json | |
import azure.functions as func | |
from azure.cosmosdb.table.tableservice import TableService | |
import requests | |
def main(mytimer: func.TimerRequest, sendGridMessage: func.Out[str]) -> None: | |
# if mytimer.past_due: | |
logging.info('The timer is past due!') | |
table_service = TableService(account_name='', account_key='') #replace account name and key | |
rows = table_service.query_entities("mailinglist","PartitionKey eq '1'") | |
maillist = [] | |
x = requests.get('https://api.covid19india.org/data.json') | |
x = x.json() | |
recent = x["cases_time_series"][-1] | |
recentdate = recent["date"] | |
dailyconfirmed = recent["dailyconfirmed"] | |
dailydeceased = recent["dailydeceased"] | |
dailyrecovered = recent["dailyrecovered"] | |
totalconfirmed = recent["totalconfirmed"] | |
totaldeceased = recent["totaldeceased"] | |
totalrecovered = recent["totalrecovered"] | |
subjectline = "COVID19 cases update - "+recentdate | |
emailcontent = "Today's ("+recentdate+") COVID-19 cases in India\n\n Confirmed : " + dailyconfirmed + "\n Recovered: "+dailyrecovered+"\n Deaths: "+dailydeceased+"\n\n Overall Cases in India\n\n Total Confirmed : " + totalconfirmed + "\n Total Recovered: "+totalrecovered+"\n Total Deaths: "+totaldeceased+"\n\n\n Stay Safe. Maintain Social Distancing. Follow Healthcare guidelines. Wear mask. Sanitize your hands regularly\n\n Developed by Vivek Raja P S https://twitter.com/VivekRaja007.\n\n For more info, or to unsubscribe from the mailing list, go to https://bit.ly/azurecovid" | |
for row in rows: | |
temp = {} | |
temp["email"] = row['email'] | |
maillist.append(temp) | |
message = { | |
"personalizations": [ | |
{ | |
"to": [ | |
{ | |
"email": "vivekraja98@gmai.com" | |
} | |
], | |
"bcc": maillist | |
} | |
], | |
"subject": subjectline, | |
"content": [{ | |
"type": "text/plain", | |
"value": emailcontent }] | |
} | |
sendGridMessage.set(json.dumps(message)) | |
Now navigate to your Function App in the azure portal -> Configuration. Under Application settings, create a key "sendgrid_api" and paste the Send Grid API Key you had generated in the previous step.
Step 5: Creating & Deploying the website to Azure Static Web App Service
Create a simple website where the user can enter his email address to subscribe/ unsubscribe. Call the respective HTTP Trigger Function URL for the same.
Create a Github Account and push all your source code.
Now to deploy you web app to Azure Static Web App Service.
- Create a repository in Github and upload all the source files.
- Go to Azure Portal -> Azure Static Web App (Preview) -> Create
- Enter the relevant details and sign up with your Github Account for the deployment details.
- Select your repo and the branch.
- Create
Once your app is deployed, you will be able to see the URL of the website. Copy the URL and navigate to the HTTP Trigger Functions. Under it, go the CORS and paste your website URL.
Congratulations! You have created a COVID-19 stats Newsletter.
Feel free to fork my GitHub Repo to come up with more interesting use cases.
Vivek0712
/
covid-newsletter
Creating a COVID-19 India stats newsletter using Azure Function App
If you have made to this far end of the article, like and share to your fellow devs. For any doubts, help, suggestions and feedback, reach out to me through Twitter
Top comments (2)
Nice blog post with code as well! Great going Vivek Raja! :-)
Thank you :)