Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Weather_Alert/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
OPEN_WEATHER_MAP_API_KEY="bd5e378503939ddaee76f12ad7a97608"
23 changes: 23 additions & 0 deletions Weather_Alert/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#BASEIMAGE

FROM python:3.7

#WORKDIR

WORKDIR /app

#COPY CODE

COPY . /app

#INSTALL LIBRARIES

RUN pip install requests python-dotenv
RUN pip install -r requirement.txt

#RUN THE APP

CMD ["python","main.py"]



38 changes: 38 additions & 0 deletions Weather_Alert/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Weather Alert Script 🌦️

A simple Python script that fetches weather data for your city and alerts you if the temperature or wind speed crosses your set thresholds. Perfect for staying on top of weather changes and preparing for unexpected conditions! 🚀

## Features

- **Fetch Weather Data**: Retrieves up-to-date weather information for any city using the OpenWeatherMap API.
- **Custom Alerts**: Set your own temperature and wind speed thresholds. If the weather conditions exceed these, the script will alert you!
- **Hourly Updates**: The script automatically checks the weather every hour, so you’re always in the loop.

## Getting Started

### Prerequisites

- Python 3.x
- `requests` and `python-dotenv` libraries

Install the required libraries using:

```bash
pip install requests python-dotenv
```

## Setup

- Clone or download this repository.
- Get an API key from OpenWeatherMap. (It’s free!)
- Create a .env file in the root directory and add your API key like shown in `.env.example`
- Run the script

```
python weather_alert.py
```

## Troubleshooting

- Missing API Key Error: Double-check that your .env file contains the correct OPEN_WEATHER_MAP_API_KEY. Make sure there are no typos or extra spaces.
- Error fetching data: This could happen if the API key is incorrect or if the city name is misspelled. Verify both and try again.
88 changes: 88 additions & 0 deletions Weather_Alert/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import requests
import json
import time
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Load API key from environment variable (security fix)
API_KEY = os.getenv('OPEN_WEATHER_MAP_API_KEY')

if not API_KEY:
raise ValueError("Missing environment variable 'OPEN_WEATHER_MAP_API_KEY'")

UNIT = 'metric'
BASE_URL = 'https://api.openweathermap.org/data/2.5/find'


def fetch_weather(city):
"""Fetches weather data for a given city.

Args:
city (str): Name of the city.

Returns:
dict: Weather data if successful, None otherwise.
"""

url = f"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}"
response = requests.get(url)

if response.status_code == 200:
return response.json()
else:
print(f"Error fetching data: {response.status_code}")
return None


def check_alerts(data, temp_threshold, wind_speed_threshold):
"""Checks for temperature and wind speed alerts in weather data.

Args:
data (dict): Weather data.
temp_threshold (float): Temperature threshold in °C.
wind_speed_threshold (float): Wind speed threshold in m/s.

Prints alerts if any, otherwise prints a message indicating normal weather conditions.
"""

if not data or 'list' not in data or not data['list']:
print("No data available to check alerts.")
return

weather_info = data['list'][0]
temp = weather_info['main']['temp']
wind_speed = weather_info['wind']['speed']

alerts = []
if temp > temp_threshold:
alerts.append(f"Temperature alert! Current temperature: {temp}°C")
if wind_speed > wind_speed_threshold:
alerts.append(f"Wind speed alert! Current wind speed: {wind_speed} m/s")

if alerts:
print("\n".join(alerts))
else:
print("No alerts. Weather conditions are normal.")


def main():
"""Prompts user for city name, temperature and wind speed thresholds,
and continuously checks for alerts.
"""

city = input("Enter city name: ")
temp_threshold = float(input("Enter temperature threshold (°C): "))
wind_speed_threshold = float(input("Enter wind speed threshold (m/s): "))

while True:
weather_data = fetch_weather(city)
check_alerts(weather_data, temp_threshold, wind_speed_threshold)
print("Waiting for the next check...")
time.sleep(3600) # check every hour


if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions Weather_Alert/requirement.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
requests
python-dotenv
1 change: 1 addition & 0 deletions Weather_Alert/runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.10.7
Loading