Fetch and display weather data.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

145 lines
4.0 KiB
Raw

from flask import Flask, render_template, request
from HandleWeatherFile import HandleWeatherFile
from datetime import datetime
app=Flask(__name__)
def getUniqueDate(dateArray):
date=[]
for i in dateArray:
iDate=i.split(" ")[0]
if iDate not in date:
date.append(iDate)
return date
def getHumanReadableFetchTime(fetchTime):
"""
Compare fetchTime with current date and time value.
Return the result as "X days Y minutes Z seconds" where days and minutes will only be displayed if relevant.
@param fetchTime datetime.datetime object representing a past point in time
"""
fetchTime=datetime.fromtimestamp(fetchTime)
tDelta=datetime.now()-fetchTime
returnValue=""
rest=tDelta.seconds
if(tDelta.days>0):
returnValue+=str(int(tDelta.days))+" days "
if(rest>3599):
returnValue+=str(int(rest/3600))+" hours "
rest=rest%3600
if(rest>59):
returnValue+=str(int(rest/60))+" minutes "
rest=rest%60
returnValue+=str((rest))+" seconds"
return returnValue
def getUserArgumentHour(requestHour):
"""
Return a sanitized array from the measurement hour(s) requested by the user.
Return empty array if no valid values.
Removes duplicates, unsure that the values are number and sort the results.
@param requestHour URL parameter relative to the hour in string format, value separated by comma.
"""
hour=[]
requestedHour=requestHour
if requestedHour is None:
return hour
requestedHour=requestedHour.split(",")
requestedHour=list(dict.fromkeys(requestedHour)) #removes duplicates
for h in requestedHour:
try:
hi=int(h)
hour.append(hi)
except Exception:
pass
hour.sort()
return hour
@app.route("/")
def indexRoute():
return renderWeatherTemplate(request.args)
@app.route("/<latitude>;<longitude>")
def specifiedCoordinateRoute(latitude,longitude):
try:
flatitude=float(latitude)
except Exception:
return "Error, verify the provided latitude. ("+str(latitude)+")"
try:
flongitude=float(longitude)
except Exception:
return "Error, verify the provided longitude. ("+str(longitude)+")"
return renderWeatherTemplate(request.args,latitude,longitude)
def renderWeatherTemplate(requestArgs,latitude=None,longitude=None):
"""
Render the weather template based on the specified paramaters.
@param request.args Parsed URL parameters.
@param latitude Optional geographic coordinate that specifies the north–south position.
@param longitude Optional geographic coordinate that specifies the east-west position.
"""
title="Weather "
handleWeatherFile=None
if latitude is not None and longitude is not None:
title+=latitude+"/"+longitude
handleWeatherFile=HandleWeatherFile(latitude=latitude,longitude=longitude,filename="WeatherReport"+latitude+"_"+longitude+".json")
else:
handleWeatherFile=HandleWeatherFile()
title+=" Paris"
weatherFile=handleWeatherFile.fetchWeatherFile()
measureHour=getUserArgumentHour(requestArgs.get("hour",type=str))
validHours=None
if(len(measureHour)==0):
measureHour=handleWeatherFile.getWeatherFileMeasureHours(True)
validHours=measureHour
includeToday=True
if requestArgs.get("today",type=int) is not None:
if(requestArgs.get("today",type=int)==0):
includeToday=False
night=False
if requestArgs.get("night",type=int) is not None:
if(requestArgs.get("night",type=int)==1):
night=True
ui=True
if requestArgs.get("ui",type=int) is not None:
if(requestArgs.get("ui",type=int)==0):
ui=False
if ui and validHours is None:
validHours=handleWeatherFile.getWeatherFileMeasureHours(True)
dayCount=7
if requestArgs.get("day",type=int) is not None:
dayCount=requestArgs.get("day",type=int)
if requestArgs.get("title",type=str) is not None:
title=requestArgs.get("title",type=str)
dt=handleWeatherFile.getFormattedDateTimeArray(dayCount,includeToday,measureHour)
return render_template(
"index.html",
date=getUniqueDate(dt),
hour=measureHour,
datetime=dt,
weatherData=weatherFile,
fetchTime=getHumanReadableFetchTime(weatherFile["fetchTime"]),
title=title,
ui=ui,
validHours=str(validHours)[1:-1],
night=night
)
#if __name__ == '__main__':
# app.run(host='0.0.0.0',debug=True)