File size: 1,659 Bytes
9a3ea79
e346c09
 
9a3ea79
e346c09
 
 
9a3ea79
e346c09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import requests
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def get_current_outdoor_values():
    try:
        temperature_units = {
            "celcius": 'metric',
            "fahrenheit": 'imperial',
            "kelvin": 'standard'
        }
        # Karachi coordinates
        lat = 2
        lon = 6
        
        # Get API key from environment variable with fallback
        API_key = os.getenv('OPENWEATHER_API_KEY', 'a2fd388a8f19b443d5ab2f811a26b258')
        
        # Use a session for better connection handling
        session = requests.Session()
        
        ai_response = session.get(f"http://api.openweathermap.org/data/2.5/air_pollution?lat={lat}&lon={lon}&appid={API_key}")
        temp_humidi_response = session.get(f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&units={temperature_units['celcius']}&appid={API_key}")
        
        ai_json = ai_response.json()
        temp_humid_json = temp_humidi_response.json()
        
        current_outdoor_temperature = round(temp_humid_json['main']['temp'])
        current_outdoor_humidity = round(temp_humid_json['main']['humidity'])
        current_outdoor_air_index = round(ai_json['list'][0]['main']['aqi'])
        
        return {'temp': current_outdoor_temperature, 'humid': current_outdoor_humidity, 'air': current_outdoor_air_index}
    except Exception as e:
        logger.error(f"API Error: {e}")
        # Return default values if API fails
        return {'temp': 26, 'humid': 66, 'air': 4}
    
if __name__ == "__main__":
    print(get_current_outdoor_values())