def get_weather_data(lat, lon, cur_date, uid, fieldid): import requests import firebase_admin from firebase_admin import credentials from firebase_admin import db from firebase_admin import messaging import traceback import datetime from datetime import date cred = credentials.Certificate("servicekey.json") try: firebase_admin.initialize_app( cred, {"databaseURL": "https://farmbase-b2f7e-31c0c.firebaseio.com/"} ) except: print(traceback.format_exc()) API_URL = "http://api.weatherapi.com/v1/history.json" current_date = datetime.datetime.strptime(cur_date, "%Y%m%d") params = { "key": "dd6e11f5d20e4694bed72932241007", "q": f"{lat},{lon}", "dt": current_date.strftime("%Y-%m-%d"), } try: resp = requests.get(API_URL, params=params) except: resp = {} try: x = resp.json() except: x = {} resp.status_code = "404" weather_data = {} if resp.status_code != "404": # store the value of "main" # key in variable y try: station_name = x["location"]["name"] y = x["forecast"]["forecastday"][0]["day"] z = x["forecast"]["forecastday"][0]["hour"][0] try: cloud_cover = z["cloud"] except: cloud_cover = "Not Available" try: wind_degree = z["wind_degree"] except: wind_degree = "Not Available" try: wind_speed = z["wind_mph"] # wind_speed = z["wind_kph"] except: wind_speed = "Not Available" try: pressure = z["pressure_mb"] except: pressure = "Not Available" try: humidity = z["humidity"] except: humidity = "Not Available" temp_max_temp = ( db.reference("PaidMonitoredFields") .child("PMF") .child(uid) .child(fieldid) .child("Weather") .child(cur_date) .child("max_temp") .get() ) temp_min_temp = ( db.reference("PaidMonitoredFields") .child("PMF") .child(uid) .child(fieldid) .child("Weather") .child(cur_date) .child("min_temp") .get() ) try: min_temp = y["mintemp_c"] + 273 except: min_temp = "Not Available" try: max_temp = y["maxtemp_c"] + 273 except: max_temp = "Not Available" if temp_max_temp is None: pass else: if float(max_temp) < float(temp_max_temp): max_temp = temp_max_temp if temp_min_temp is None: pass else: if float(min_temp) > float(temp_min_temp): min_temp = temp_min_temp weather_data = { "cloud_cover": cloud_cover, "wind_deg": wind_degree, "wind_speed": wind_speed, "station": station_name, "pressure": pressure, "humidity": humidity, "max_temp": max_temp, "min_temp": min_temp, } print(weather_data) db.reference("PaidMonitoredFields").child("PMF").child(uid).child( fieldid ).child("Weather").child(cur_date).set(weather_data) except: print(traceback.format_exc())