-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetchWeather.py
More file actions
61 lines (50 loc) · 2.52 KB
/
Copy pathfetchWeather.py
File metadata and controls
61 lines (50 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/bin/python3
import requests
import pymongo,time
from config import api_key
# OpenWeatherAPI configuration
lat = 17.4345706 # Replace with the city you want to fetch weather data for
lon = 78.3738571
api_weather = "http://api.openweathermap.org/data/2.5/weather?lat="+str(lat)+"&lon="+str(lon)+"&appid=eb370f9ef90cb3375bb7c497f844f0c5&units=metric"
api_aqi = "http://api.openweathermap.org/data/2.5/air_pollution?lat="+str(lat)+"&lon="+str(lon)+"&appid=eb370f9ef90cb3375bb7c497f844f0c5&units=metric "
# MongoDB configuration
mongo_client = pymongo.MongoClient('mongodb://localhost:27017/')
db = mongo_client['jm']
collection = db['weather']
def cloudiness_to_lux(cloudiness_percent):
# Maximum illuminance for clear daylight conditions (adjust as needed)
max_illuminance = 100000 # lux
# Calculate the reduction in illuminance based on cloudiness percentage
reduction_factor = cloudiness_percent / 100.0
# Calculate the lux value
lux = max_illuminance * reduction_factor
return lux
def fetch_weather_data():
try:
# print("Weather")
response = requests.get(api_weather)
weatherData = response.json()
print(weatherData)
print( )
# print("AQI")
response2 = requests.get(api_aqi)
aqiData = response2.json()
print(aqiData)
data = {'fetchTime':round(time.time()), 'lastUpdate':weatherData['dt'], 'lat':weatherData['coord']['lat'], 'lon':weatherData['coord']['lon'],'location':weatherData['name'], 'luminosity': cloudiness_to_lux(weatherData['clouds']['all']), 'temp':weatherData['main']['temp'],'humidity':weatherData['main']['humidity'], 'aqi':aqiData['list'][0]['main']['aqi'], 'co':aqiData['list'][0]['components']['co'], 'no':aqiData['list'][0]['components']['no'], 'no2':aqiData['list'][0]['components']['no2'], 'o3':aqiData['list'][0]['components']['o3'], 'so2':aqiData['list'][0]['components']['so2'], 'pm2_5':aqiData['list'][0]['components']['pm2_5'], 'pm10':aqiData['list'][0]['components']['pm10'], 'nh3':aqiData['list'][0]['components']['nh3'] }
print(data)
if response.status_code == 200:
return data
else:
print(f"Error: {data['message']}")
return None
except Exception as e:
print(f"An error occurred: {str(e)}")
return None
def save_to_mongodb(data):
if data:
collection.insert_one(data)
print("Weather data saved to MongoDB.")
if __name__ == "__main__":
data = fetch_weather_data()
if data:
save_to_mongodb(data)