Open In App

Covid Vaccine Availability using Flask Server

Last Updated : 26 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to build Covid Vaccine Availability Checker using Flask Server.

We all are familiar that the whole world is suffering from the pandemic and the only thing which helps us to come out from this situation is mass Vaccination. But as we know due to the large population of the country it is very difficult to find vaccines in our nearby areas. So now technology comes under the picture and we will build our own covid vaccine availability checker which finds the availability of vaccines in our nearby areas.

We will be using some python libraries to find the availability of vaccines and display them using a flask server. In future, you can deploy it also on the real-time server. First of all, we have to install the python Flask Package using the below command:

pip install flask

After installing the python flask package, Open Pycharm or any IDE (Preferably Visual Studio Code) and make a new project. After this make a main python file app.py and two folders named templates and the other is static (name of the folder must be same as it is written).

Below is the image representing the Directory Structure of the project.

Stepwise Implementation 

Step 1: In this first step, we have to import python libraries which we will use further in the project. Also, make an app of the Flask server.

Python




from flask import Flask,request,session,render_template
import requests,time
from datetime import datetime,timedelta
  
app = Flask(__name__)


Step 2: Adding the routes to handle the client requests.

Python3




@app.route('/')
def home():
  
    # rendering the homepage of project
    return render_template("index.html")
  
@app.route('/CheckSlot')
def check():
  
    # for checking the slot available or not
      
    # fetching pin codes from flask
    pin = request.args.get("pincode")
      
    # fetching age from flask
    age = request.args.get("age")
    data = list()
      
    # finding the slot
    result = findSlot(age, pin, data)
      
    if(result == 0):
        return render_template("noavailable.html")
    return render_template("slot.html", data=data)


Step 3: This is the main step of our project which finds the availability of vaccine (findslot() function that will do the following things):

  • First of all take the parameters like age, pin, and find dates from DateTime library of python.
  • Scrap the data from the official cowin website like vaccine doses, vaccination centers, availability, types of vaccine and price, etc.
  • Store all the data in the python list.

Python3




def findSlot(age,pin,data):
    
    flag = 'y'
    num_days =  2
    actual = datetime.today()
    list_format = [actual + timedelta(days=i) for i in range(num_days)]
    actual_dates = [i.strftime("%d-%m-%Y") for i in list_format]
      
    while True:
        counter = 0
        for given_date in actual_dates:
            
            # cowin website Api for fetching the data
            URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={}&date={}".format(pin, given_date)
            header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
              
            # Get the results in json format.
            result = requests.get(URL,headers = header)
            if(result.ok):
                response_json = result.json()
                if(response_json["centers"]):
                    
                    # Checking if centres available or not
                    if(flag.lower() == 'y'):
                        for center in response_json["centers"]:
                            
                            # For Storing all the centre and all parameters
                            for session in center["sessions"]:
                                
                                # Fetching the availability in particular session
                                datas = list()
                                  
                                # Adding the pincode of area in list
                                datas.append(pin)
                                  
                                # Adding the dates available in list
                                datas.append(given_date)
                                  
                                # Adding the centre name in list
                                datas.append(center["name"])
                                  
                                # Adding the block name in list
                                datas.append(center["block_name"])
                                  
                                # Adding the vaccine cost type whether it is
                                # free or chargeable.
                                datas.append(center["fee_type"])
                                  
                                # Adding the available capacity or amount of 
                                # doses in list
                                datas.append(session["available_capacity"])
                                if(session["vaccine"]!=''):
                                    datas.append(session["vaccine"])
                                counter =counter + 1
                                  
                                # Add the data of particular centre in data list.
                                if(session["available_capacity"]>0):
                                    data.append(datas)
            else:
                print("No response")
        if counter == 0:
            return 0
        return 1


Below is the Full Implementation of app.py

Python3




from flask import Flask,request,session,render_template
import requests,time
from datetime import datetime,timedelta
  
app = Flask(__name__)
  
@app.route('/')
def home():
    return render_template("index.html")
  
@app.route('/CheckSlot')
def check():
    
    # fetching pin codes from flask
    pin = request.args.get("pincode")
      
    # fetching age from flask
    age = request.args.get("age")
    data = list()
      
    # finding the slot
    result = findSlot(age,pin,data)
      
    if(result == 0):
        return render_template("noavailable.html"
    return render_template("slot.html",data = data)
  
def findSlot(age,pin,data):
    flag = 'y'
    num_days =  2
    actual = datetime.today()
    list_format = [actual + timedelta(days=i) for i in range(num_days)]
    actual_dates = [i.strftime("%d-%m-%Y") for i in list_format]
      
    # print(actual_dates)
    while True:
        counter = 0
        for given_date in actual_dates:
            
            # cowin website Api for fetching the data
            URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={}&date={}".format(pin, given_date)
            header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
               
            # Get the results in json format.
            result = requests.get(URL,headers = header)
            if(result.ok):
                response_json = result.json()
                if(response_json["centers"]):
                    
                    # Checking if centres available or not
                    if(flag.lower() == 'y'):
                        for center in response_json["centers"]:
                            
                            # For Storing all the centre and all parameters
                            for session in center["sessions"]:
                                
                                # Fetching the availability in particular session
                                datas = list()
                                  
                                # Adding the pincode of area in list
                                datas.append(pin)
                                  
                                # Adding the dates available in list
                                datas.append(given_date)
                                  
                                # Adding the centre name in list
                                datas.append(center["name"])
                                  
                                # Adding the block name in list
                                datas.append(center["block_name"])
                                  
                                # Adding the vaccine cost type whether it is
                                # free or chargeable.
                                datas.append(center["fee_type"])
                                  
                                # Adding the available capacity or amount of 
                                # doses in list
                                datas.append(session["available_capacity"])
                                if(session["vaccine"]!=''):
                                    datas.append(session["vaccine"])
                                counter =counter + 1
                                  
                                # Add the data of particular centre in data list.
                                if(session["available_capacity"]>0):
                                    data.append(datas)
                                      
            else:
                print("No response")
        if counter == 0:
            return 0
        return 1
  
if __name__ == "__main__":
    app.run()


Step 4:  Now make three files in the templates folder.

  • index.html: Displaying the homepage of the project for entering the age and pin codes.
  • slot.html:  Displaying the data on the page.
  • noavailable.html:  If the vaccine is not found in any center then-No availability page.

index.html code 

HTML




<!doctype html>
<html lang="en">
   <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <!-- Bootstrap CSS -->
         integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
      <link rel="stylesheet" href="/static/img/style.css">
      <title>Covid Vaccination Slots</title>
   </head>
   <body>
      <h2 class="text-center" style="background-color: rgb(2, 2, 2);padding: 5px;color: white;">Find Your Vaccination Slots
      </h2>
      <div class="container-fluid" style="margin-top: 0px;">
         <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner">
               <div class="carousel-item active" style="height: 350px">
                  <img src="/static/img/geeks.png" class="d-block w-100" alt="...">
               </div>
               <div class="carousel-item" style="height: 350px">
                  <img src="/static/img/geeks.png"
                     class="d-block w-100" alt="...">
               </div>
               <!-- <div class="carousel-item"  style="height: 400px">
                  <img src="/static/img/cor.jpeg" class="d-block w-100" alt="...">
                  </div> -->
            </div>
            <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls"
               data-bs-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="visually-hidden">Previous</span>
            </button>
            <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls"
               data-bs-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="visually-hidden">Next</span>
            </button>
         </div>
      </div>
      <h2 style="text-align: center;margin-top: 50px;">Enter Your Credentials here </h2>
      <div style="margin-left: 620px;margin-top: 10px;">
         <form class="formed" action="/CheckSlot">
            <Label>Pincode</Label>
            <input type="text" name="pincode" placeholder="Enter Your Pincode Here" style="padding: 10px;margin: 5px 5px;border-radius: 5px;"><br>
            <Label>Age</Label>
            <input type="number" name="age" placeholder="Enter Your Age Here" style="padding: 10px;margin: 5px 33px;border-radius: 5px;"><br>
            <input type="submit" style="margin-top: 20px;margin-bottom: 30px;background-color: rgb(26, 151, 224);color: white;padding: 8px;border: 5px;" name="submit" value="Search">
         </form>
      </div>
      <!-- Optional JavaScript; choose one of the two! -->
      <!-- Option 1: Bootstrap Bundle with Popper -->
         integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
         crossorigin="anonymous"></script>
      <!-- Option 2: Separate Popper and Bootstrap JS -->
      <!--
         <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
         <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script>
         -->
   </body>
</html>


slot.html 

HTML




<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Covid Vaccination Slots</title>
   </head>
   <body>
      <h1 style="text-align: center;background-color: black;color: white;">Vaccination Slots Availability</h1>
      <br><br><br><br>
      <div>
         <!-- {% for item in data%}
            {% endfor %} -->
         <table class="table table-hover" style="background-color: aqua;">
            <thead>
               <tr>
                  <th>Pincode</th>
                  <th>Date</th>
                  <th>Vaccination Center Name</th>
                  <th>BlockName</th>
                  <th>Price</th>
                  <th>Available Capacity</th>
                  <th>Vaccine Type</th>
               </tr>
            </thead>
            <tbody>
               {% for item in data%}
               <tr>
                  <td>{{item[0]}}</td>
                  <td>{{item[1]}}</td>
                  <td>{{item[2]}}</td>
                  <td>{{item[3]}}</td>
                  <td>{{item[4]}}</td>
                  <td>{{item[5]}}</td>
                  <td>{{item[6]}}</td>
               </tr>
               {% endfor %}
            </tbody>
         </table>
      </div>
      <h3 style="margin-top: 50px;text-align: center;">
      <a href = "https://www.cowin.gov.in/home">Visit Government Website for Booking Slot</a></h1>
   </body>
</html>


noavailable.html

HTML




<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>No Availability</title>
   </head>
   <p style="text-align: center;font-size: 150px;color: rgb(255, 136, 0);">Sorry !</p>
  
  
  
  
   <body>
      <h1 style="text-align: center;color: red;margin: 0 auto;">No Available Vaccine Slots</h1>
   </body>
</html>


Add the images or other files (if you have them) to the static folder.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads