Skip to content

Add Dockerfile and Refactor Weather Alert Application: User Input for Dynamic Weather Alerts #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Base Image
FROM python:3.10

# Working directory
WORKDIR /app

# Code
COPY . .

# Install Libraries
RUN pip install -r requirement.txt

# Run app
CMD ["python", "main.py"]

Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
```markdown
# 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.
- **User Input for City**: Now includes a web form for users to input their desired city, making it easier to get real-time weather alerts for specific locations.
- **Dynamic Web Application**: The application runs on Flask, serving a simple web interface to display alerts.

## Getting Started

### Prerequisites

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

Install the required libraries using:

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

## 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`
- To run the web application, execute the following command:

```bash
python main.py
```

- Access the application by navigating to `http://localhost:80` in your web browser.

## Docker Setup

To run the application using Docker:

1. Ensure Docker is installed on your machine.
2. Build the Docker image:

```bash
docker build -t weather-app .
```

3. Run the Docker container:

```bash
docker run -it -p 80:80 -e OPEN_WEATHER_MAP_API_KEY=your_api_key -e CITY="Your City" -e TEMP_THRESHOLD=30 -e WIND_SPEED_THRESHOLD=10 weather-app
```

## 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.
- **Internal Server Error**: Ensure that the `index.html` file is present in the correct directory and that the Flask app is properly set up to render it.

## Future Improvements

- Consider deploying the application to a cloud platform for wider accessibility.
- Implement AJAX to allow for real-time updates without requiring a page refresh.
- Suggestion: Explore developing this application using Django for better structure and scalability. I would be happy to assist in making improvements in that framework.

67 changes: 67 additions & 0 deletions Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from flask import Flask, render_template, request
import requests
import os
import logging
from dotenv import load_dotenv

app = Flask(__name__)

# Load environment variables from .env file
load_dotenv()

# Load API key from environment variable
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'

# Set up basic logging
logging.basicConfig(level=logging.INFO)

@app.route('/', methods=['GET', 'POST'])
def index():
alerts = []
if request.method == 'POST':
city = request.form.get('city', '').strip()
if city:
weather_data = fetch_weather(city)
alerts = check_alerts(weather_data)
return render_template('index.html', alerts=alerts)

def fetch_weather(city):
"""Fetches weather data for a given city."""
url = f"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}"
logging.info(f"Fetching weather for {city}: {url}") # Log the URL being called
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
logging.error(f"Error fetching data: {response.status_code}, {response.text}") # Log the error response
return None

def check_alerts(data):
"""Checks for temperature and wind speed alerts in weather data."""
if not data or 'list' not in data or not data['list']:
return ["No data available to check alerts."]

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

alerts = []
temp_threshold = float(os.getenv('TEMP_THRESHOLD', 30.0)) # Default to 30°C
wind_speed_threshold = float(os.getenv('WIND_SPEED_THRESHOLD', 10.0)) # Default to 10 m/s

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")

return alerts if alerts else ["No alerts. Weather conditions are normal."]

if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Flask
requests
python-dotenv

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-3.10.7
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Alerts</title>
</head>
<body>
<h1>Weather Alerts</h1>
<form method="post">
<label for="city">Enter City Name:</label>
<input type="text" id="city" name="city" required>
<button type="submit">Check Weather</button>
</form>

<h2>Alerts:</h2>
<ul>
{% for alert in alerts %}
<li>{{ alert }}</li>
{% endfor %}
</ul>
</body>
</html>

3 changes: 2 additions & 1 deletion Weather Alert/README.md
Original file line number Diff line number Diff line change
@@ -35,4 +35,5 @@ 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.
- Error fetching data: This could happen if the API key is incorrect or if the city name is misspelled. Verify both and try again
.
3 changes: 2 additions & 1 deletion Weather Alert/main.py
Original file line number Diff line number Diff line change
@@ -85,4 +85,5 @@ def main():


if __name__ == "__main__":
main()
main()

3 changes: 2 additions & 1 deletion Weather Alert/requirement.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
requests
python-dotenv
python-dotenvv

3 changes: 2 additions & 1 deletion Weather Alert/runtime.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
python-3.10.7
python-3.10.7