Py.Cafe

sekatimpho/

openweathermap-city-weather

OpenWeatherMap City Weather

DocsPricing
  • app.py
  • my_working_space
  • requirements.txt
app.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import streamlit as st
import requests

# Your OpenWeatherMap API key
API_KEY = "bb7a7d944437ed1b8df2a27b54490cbb"

# Function to fetch weather data
def get_weather(api_key, city):
    try:
        # Get the city's latitude and longitude
        geocode_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={api_key}"
        geocode_response = requests.get(geocode_url).json()
        
        if not geocode_response:
            return None
        
        lat = geocode_response[0]["lat"]
        lon = geocode_response[0]["lon"]

        # Get the current weather
        url = f"http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
        response = requests.get(url)
        weather_data = response.json()

        if response.status_code != 200:
            return None

        return weather_data
    except Exception as e:
        st.error(f"An error occurred: {e}")
        return None

# Function to check for extreme weather
def check_extreme_weather(temp):
    if temp < 0 or temp > 35:
        return True
    return False

# Streamlit app layout
st.set_page_config(page_title="Current Weather", page_icon=":cloud:", layout="wide")

# Background image
st.markdown("""
    <style>
    .reportview-container {
        background: url('https://source.unsplash.com/1600x900/?weather') no-repeat center center fixed;
        background-size: cover;
    }
    .sidebar .sidebar-content {
        background: rgba(255, 255, 255, 0.8);
    }
    </style>
    """, unsafe_allow_html=True)

st.title("Current Weather")
st.subheader("Enter the city name to get the current weather")

city = st.text_input("City Name", placeholder="e.g., Johannesburg")

if city:
    st.spinner("Fetching weather data...")
    weather_data = get_weather(API_KEY, city)
    
    if weather_data:
        temp = weather_data["main"]["temp"]
        weather_desc = weather_data["weather"][0]["description"].capitalize()
        icon = weather_data["weather"][0]["icon"]
        city_name = weather_data["name"]
        country = weather_data["sys"]["country"]

        # Display weather information
        col1, col2 = st.columns(2)
        with col1:
            st.image(f"http://openweathermap.org/img/wn/{icon}.png", width=100)
        with col2:
            st.header(f"{city_name}, {country}")
            st.subheader(f"Temperature: {temp}°C")
            st.write(f"Weather: {weather_desc}")

        if check_extreme_weather(temp):
            st.warning("Extreme weather alert!")
    else:
        st.error("City not found or invalid API key")