88from CovidCasesWHO import CovidCasesWHO
99from CovidCases import CovidCases
1010from typing import Optional
11+ from collections import namedtuple
1112import re
1213import pandas as pd
1314import matplotlib as mpl
1415import matplotlib .pyplot as plt
1516import matplotlib
1617import io
1718import requests
18- from datetime import date
19+ from datetime import date , timedelta
1920from starlette .responses import StreamingResponse
2021from starlette .responses import FileResponse
2122from fastapi import FastAPI , HTTPException
@@ -111,6 +112,52 @@ class Rest_API:
111112 COVID_DATA: "your_directory"
112113 """
113114
115+ def __init__ (self ):
116+ print ('constructor called' )
117+ # get the date
118+ today = date .today () - timedelta (days = 1 )
119+ # the prefix of the CSV file is Y-m-d
120+ self .__ymd = today .strftime ('%Y-%m-%d' )
121+ # an array holding the data for the data sources
122+ self .__data = []
123+ # 0 is WHO
124+ self .__data .append (None )
125+ # 1 is OWID
126+ self .__data .append (None )
127+ # initialise date tracking
128+ self .__get_latest_data ()
129+
130+ def __get_latest_data (self ):
131+ # the data directory
132+ try :
133+ prefix = os .environ ['COVID_DATA' ] + '/'
134+ except :
135+ print ('missing environment variable, switching to default directory' )
136+ prefix = '../data'
137+
138+ # the calls to download_CSV_file will report if the files already exist
139+
140+ # get the latest WHO file name and download it, if necessary
141+ csv_file = CovidCasesWHO .download_CSV_file (prefix )
142+ # check if it is the file of the last call
143+ if csv_file .find (self .__ymd ) == - 1 :
144+ # it's from a different data
145+ self .__data [0 ] = CovidCasesWHO (csv_file )
146+ print ('Updated WHO data' )
147+
148+ # get the latest OWID file name and download it, if necessary
149+ csv_file = CovidCasesOWID .download_CSV_file (prefix )
150+ # check if it is the file of the last call
151+ if csv_file .find (self .__ymd ) == - 1 :
152+ # it's from a different data
153+ self .__data [1 ] = CovidCasesOWID (csv_file )
154+ print ('Updated OWID data' )
155+
156+ # get the date and keep it
157+ today = date .today ()
158+ # the prefix of the CSV file is Y-m-d
159+ self .__ymd = today .strftime ('%Y-%m-%d' )
160+
114161 def generate_plot (self , geo_ids , wanted_attrib , data_source , log = False , last_n = - 1 , since_n = - 1 , bar = False ):
115162 """ Generates a plot for given GeoIds and returns it in form of a byteIO stream
116163
@@ -123,6 +170,9 @@ def generate_plot(self, geo_ids, wanted_attrib, data_source, log=False, last_n=-
123170 last_n (int, optional): plot the last n days, if not further specified all available data is plotted
124171 since_n (int, optional): plot since the nth case, if not further specified all available data is plotted
125172 """
173+ # check if a newer database is available (hopefully no one is calling that during European nights
174+ # as they are updated in the morning)
175+ self .__get_latest_data ()
126176 # vaccination data is only available with OWID
127177 if data_source != DataSource .OWID :
128178 if (wanted_attrib == Attributes .VaccineDosesAdministered ) or (wanted_attrib == Attributes .DailyVaccineDosesAdministered7DayAverage ):
@@ -138,57 +188,43 @@ def generate_plot(self, geo_ids, wanted_attrib, data_source, log=False, last_n=-
138188 data_source = DataSource.OWID
139189 case (_, _): pass
140190 """
141- # load the data source
142- try :
143- prefix = os .environ ['COVID_DATA' ]
144- if data_source == DataSource .OWID :
145- csv_file = CovidCasesOWID .download_CSV_file (prefix )
146- self .covid_cases = CovidCasesOWID (csv_file )
147- if data_source == DataSource .WHO :
148- csv_file = CovidCasesWHO .download_CSV_file (prefix )
149- self .covid_cases = CovidCasesWHO (csv_file )
150- except :
151- print ('missing COVID_DATA environment variable' )
152- if data_source == DataSource .OWID :
153- csv_file = CovidCasesOWID .download_CSV_file ()
154- self .covid_cases = CovidCasesOWID (csv_file )
155- if data_source == DataSource .WHO :
156- csv_file = CovidCasesWHO .download_CSV_file ()
157- self .covid_cases = CovidCasesWHO (csv_file )
191+ # use the actual data source
192+ if data_source == DataSource .WHO :
193+ requestedData = self .__data [0 ]
194+ else :
195+ requestedData = self .__data [1 ]
158196 """
159197 Alternatively in latest Python version
160198 match data_source:
161199 case DataSource.OWID:
162- csv_file = CovidCasesOWID.download_CSV_file()
163- self.covid_cases = CovidCasesOWID(csv_file)
200+ data = self.__data[1]
164201 case DataSource.WHO:
165- csv_file = CovidCasesWHO.download_CSV_file()
166- self.covid_cases = CovidCasesWHO(csv_file)
202+ data = self.__data[0]
167203 """
168204 # try to collect the data for given geoIds, if a wrong geoId is passed, the operation will abort with a 400
169205 # bad request error
170206 try :
171- df = self . covid_cases .get_data_by_geoid_list (geo_ids , lastNdays = last_n , sinceNcases = since_n )
207+ df = requestedData .get_data_by_geoid_list (geo_ids , lastNdays = last_n , sinceNcases = since_n )
172208 except IndexError :
173209 raise HTTPException (
174210 status_code = 400 , detail = "Couldn't load data" )
175211
176212 # if the wanted attribute is one that need to be calculated, calculate it
177213 if wanted_attrib == Attributes .R or Attributes .R7 :
178- df = self . covid_cases .add_r0 (df )
214+ df = requestedData .add_r0 (df )
179215 if wanted_attrib == Attributes .R7 :
180- df = self . covid_cases .add_lowpass_filter_for_attribute (df , 'R' , 7 )
216+ df = requestedData .add_lowpass_filter_for_attribute (df , 'R' , 7 )
181217 if wanted_attrib == Attributes .DailyCases7 :
182- df = self . covid_cases .add_lowpass_filter_for_attribute (
218+ df = requestedData .add_lowpass_filter_for_attribute (
183219 df , 'DailyCases' , 7 )
184220 if wanted_attrib == Attributes .DailyDeaths7 :
185- df = self . covid_cases .add_lowpass_filter_for_attribute (
221+ df = requestedData .add_lowpass_filter_for_attribute (
186222 df , 'DailyDeaths' , 7 )
187223 if wanted_attrib == Attributes .DoublingTime7 :
188- df = self . covid_cases .add_lowpass_filter_for_attribute (
224+ df = requestedData .add_lowpass_filter_for_attribute (
189225 df , 'DoublingTime' , 7 )
190226 if wanted_attrib == Attributes .Incidence7DayPer100Kpopulation :
191- df = self . covid_cases .add_incidence_7day_per_100Kpopulation (df )
227+ df = requestedData .add_incidence_7day_per_100Kpopulation (df )
192228
193229 # create pivot table with all needed values, if the x-axis shows a timedelta with days since the nth case the index
194230 # has to change
@@ -277,7 +313,7 @@ def get_map(wanted_map: Maps):
277313 print ('missing COVID_DATA environment variable' )
278314 return 'Data directory not found'
279315 # return the HTML file
280- return FileResponse (prefix + wanted_map .name + '.html' )
316+ return FileResponse (prefix + '/' + wanted_map .name + '.html' )
281317
282318 @app .get ('/api/csv/' )
283319 def get_csv ():
0 commit comments