0

I would like to create a conditional function in python, which return something else if 502 Bad Gateway happens.

def getData(request):
   url = "https://data.ontario.ca/dataset/1115d5fe-dd84-4c69-b5ed-05bf0c0a0ff9/resource/d1bfe1ad- 
          6575-4352-8302-09ca81f7ddfc/download/cases_by_status_and_phu.csv"

   if not 502 Bad Gateway:
       return pd.read_csv(url)
   else:
       return 'None'

502-Bad-Gateway

I would highly appreciate it if you could please help me to write that function.

Progman
  • 16,827
  • 6
  • 33
  • 48
Trung Nguyen
  • 37
  • 1
  • 6

1 Answers1

0
import pandas as pd
from urllib.error import HTTPError


def getEpiPhu():
    ROOT_DIR = Path(__file__).parent.parent
    path = os.path.join(ROOT_DIR, "data", "epi_phu.csv") # path of the earlier servion of data
    epi_data = pd.read_csv(path) # read the data
    try:
        # download the current version of data
        epi_phu = pd.read_csv("https://data.ontario.ca/dataset/1115d5fe-dd84-4c69-b5ed-05bf0c0a0ff9/d1bfe1ad-6575-4352-8302-09ca81f7ddfc/download/cases_by_status_and_phu.csv")
        epi_phu.columns = [x.lower() for x in epi_phu.columns.values]        
        epi_data.columns = [x.lower() for x in epi_data.columns.values]
        today = datetime.date.today().strftime("%Y-%m-%d")
        # check if the earlier version of data was updated to the current date.
        if epi_data['file_date'].unique()[-1] < today:            
            epi_phu.to_csv(path) # save the current version of data and replace the earlier data to local drive for later use as the latter was not up-to-date.
            return epi_phu
        else:
            return epi_phu # use the current data

    except HTTPError as e:
        if e.code == 502 or 404: # 502 for bad gateway; 404 for not found
            return epi_data # use the most updated version of data
        else:            
            return HttpResponse('Failure: ' + str(e.reason)) # show reason for failure

Trung Nguyen
  • 37
  • 1
  • 6