From da22fa5a7afb991e7cb794dbd70123e2c51937f2 Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Fri, 25 Oct 2024 14:24:11 +0500 Subject: [PATCH 1/8] Added a new main.py && Dockerfile --- Weather Alert/Dockerfile | 15 ++++++++++++++ Weather Alert/main.py | 45 ++++++++++++---------------------------- 2 files changed, 28 insertions(+), 32 deletions(-) create mode 100644 Weather Alert/Dockerfile diff --git a/Weather Alert/Dockerfile b/Weather Alert/Dockerfile new file mode 100644 index 0000000..89f21e5 --- /dev/null +++ b/Weather Alert/Dockerfile @@ -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"] + diff --git a/Weather Alert/main.py b/Weather Alert/main.py index 2d9b16e..46f51ad 100644 --- a/Weather Alert/main.py +++ b/Weather Alert/main.py @@ -7,7 +7,7 @@ # Load environment variables from .env file load_dotenv() -# Load API key from environment variable (security fix) +# Load API key from environment variable API_KEY = os.getenv('OPEN_WEATHER_MAP_API_KEY') if not API_KEY: @@ -16,20 +16,16 @@ UNIT = 'metric' BASE_URL = 'https://api.openweathermap.org/data/2.5/find' +# Load additional environment variables +CITY = os.getenv('CITY', 'London') # Default to 'London' if not provided +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 -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. - """ +def fetch_weather(city): + """Fetches weather data for a given city.""" url = f"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}" response = requests.get(url) - if response.status_code == 200: return response.json() else: @@ -38,16 +34,7 @@ def fetch_weather(city): 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. - """ - + """Checks for temperature and wind speed alerts in weather data.""" if not data or 'list' not in data or not data['list']: print("No data available to check alerts.") return @@ -69,20 +56,14 @@ def check_alerts(data, temp_threshold, wind_speed_threshold): 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): ")) - + """Continuously checks for weather alerts based on environment variables.""" while True: - weather_data = fetch_weather(city) - check_alerts(weather_data, temp_threshold, wind_speed_threshold) + 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() \ No newline at end of file + main() + From dcc0c2d4ceae95865d6bc489ae855d2df9616a84 Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Fri, 25 Oct 2024 15:26:42 +0500 Subject: [PATCH 2/8] Added a Docker file and UI --- Weather Alert/Dockerfile | 2 +- Weather Alert/main.py | 50 ++++++++++++++---------------- Weather Alert/requirement.txt | 4 ++- Weather Alert/templates/index.html | 24 ++++++++++++++ 4 files changed, 52 insertions(+), 28 deletions(-) create mode 100644 Weather Alert/templates/index.html diff --git a/Weather Alert/Dockerfile b/Weather Alert/Dockerfile index 89f21e5..9719ff3 100644 --- a/Weather Alert/Dockerfile +++ b/Weather Alert/Dockerfile @@ -10,6 +10,6 @@ COPY . . # Install Libraries RUN pip install -r requirement.txt -# run app +# Run app CMD ["python", "main.py"] diff --git a/Weather Alert/main.py b/Weather Alert/main.py index 46f51ad..976ce1f 100644 --- a/Weather Alert/main.py +++ b/Weather Alert/main.py @@ -1,9 +1,11 @@ +from flask import Flask, render_template, request import requests -import json -import time import os +import logging from dotenv import load_dotenv +app = Flask(__name__) + # Load environment variables from .env file load_dotenv() @@ -16,54 +18,50 @@ UNIT = 'metric' BASE_URL = 'https://api.openweathermap.org/data/2.5/find' -# Load additional environment variables -CITY = os.getenv('CITY', 'London') # Default to 'London' if not provided -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 +# 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: - print(f"Error fetching data: {response.status_code}") + logging.error(f"Error fetching data: {response.status_code}, {response.text}") # Log the error response return None - -def check_alerts(data, temp_threshold, wind_speed_threshold): +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']: - print("No data available to check alerts.") - return + 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") - if alerts: - print("\n".join(alerts)) - else: - print("No alerts. Weather conditions are normal.") - - -def main(): - """Continuously checks for weather alerts based on environment variables.""" - 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 - + return alerts if alerts else ["No alerts. Weather conditions are normal."] if __name__ == "__main__": - main() + app.run(host='0.0.0.0', port=80, debug=True) diff --git a/Weather Alert/requirement.txt b/Weather Alert/requirement.txt index d44fe44..3aed3fa 100644 --- a/Weather Alert/requirement.txt +++ b/Weather Alert/requirement.txt @@ -1,2 +1,4 @@ +Flask requests -python-dotenv \ No newline at end of file +python-dotenv +v diff --git a/Weather Alert/templates/index.html b/Weather Alert/templates/index.html new file mode 100644 index 0000000..d99fd34 --- /dev/null +++ b/Weather Alert/templates/index.html @@ -0,0 +1,24 @@ + + + + + + Weather Alerts + + +

Weather Alerts

+
+ + + +
+ +

Alerts:

+ + + + From 03fca36e4e61e7e8cd819a26c97a186558d048af Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Fri, 25 Oct 2024 15:45:09 +0500 Subject: [PATCH 3/8] Update README with additional information --- Weather Alert/README.md | 44 ++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/Weather Alert/README.md b/Weather Alert/README.md index ab0149b..ef24863 100644 --- a/Weather Alert/README.md +++ b/Weather Alert/README.md @@ -1,3 +1,4 @@ +```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! 🚀 @@ -7,32 +8,61 @@ A simple Python script that fetches weather data for your city and alerts you if - **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` and `python-dotenv` libraries +- `requests`, `python-dotenv`, and `Flask` libraries Install the required libraries using: ```bash -pip install requests python-dotenv +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` -- Run the script +- 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 . ``` -python weather_alert.py + +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. +- **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. + From 5099ebacceb0404404a88678dd318ceed923be45 Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Sat, 26 Oct 2024 08:06:06 +0500 Subject: [PATCH 4/8] Added-Dockerfile-WebInterface --- .../{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/Dockerfile | 0 .../{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/README.md | 0 .../{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/main.py | 0 .../Weather-Alert-Dockerfile-Web}/requirement.txt | 0 .../{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/runtime.txt | 0 .../Weather-Alert-Dockerfile-Web}/templates/index.html | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename Weather Alert/{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/Dockerfile (100%) rename Weather Alert/{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/README.md (100%) rename Weather Alert/{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/main.py (100%) rename Weather Alert/{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/requirement.txt (100%) rename Weather Alert/{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/runtime.txt (100%) rename Weather Alert/{ => Amitabh-DevOps/Weather-Alert-Dockerfile-Web}/templates/index.html (100%) diff --git a/Weather Alert/Dockerfile b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/Dockerfile similarity index 100% rename from Weather Alert/Dockerfile rename to Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/Dockerfile diff --git a/Weather Alert/README.md b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/README.md similarity index 100% rename from Weather Alert/README.md rename to Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/README.md diff --git a/Weather Alert/main.py b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/main.py similarity index 100% rename from Weather Alert/main.py rename to Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/main.py diff --git a/Weather Alert/requirement.txt b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/requirement.txt similarity index 100% rename from Weather Alert/requirement.txt rename to Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/requirement.txt diff --git a/Weather Alert/runtime.txt b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/runtime.txt similarity index 100% rename from Weather Alert/runtime.txt rename to Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/runtime.txt diff --git a/Weather Alert/templates/index.html b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/templates/index.html similarity index 100% rename from Weather Alert/templates/index.html rename to Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/templates/index.html From 702245501b3494919b6a5861ec93c9a29e0925e1 Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Sat, 26 Oct 2024 08:19:32 +0500 Subject: [PATCH 5/8] Modified version of Weathe-Alert with Dockerfile and WebInterface --- Weather Alert/README.md | 38 +++++++++++++++ Weather Alert/main.py | 88 +++++++++++++++++++++++++++++++++++ Weather Alert/requirement.txt | 2 + Weather Alert/runtime.txt | 1 + 4 files changed, 129 insertions(+) create mode 100644 Weather Alert/README.md create mode 100644 Weather Alert/main.py create mode 100644 Weather Alert/requirement.txt create mode 100644 Weather Alert/runtime.txt diff --git a/Weather Alert/README.md b/Weather Alert/README.md new file mode 100644 index 0000000..ab0149b --- /dev/null +++ b/Weather Alert/README.md @@ -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. diff --git a/Weather Alert/main.py b/Weather Alert/main.py new file mode 100644 index 0000000..77b3395 --- /dev/null +++ b/Weather Alert/main.py @@ -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() diff --git a/Weather Alert/requirement.txt b/Weather Alert/requirement.txt new file mode 100644 index 0000000..48aa520 --- /dev/null +++ b/Weather Alert/requirement.txt @@ -0,0 +1,2 @@ +requests +python-dotenvv diff --git a/Weather Alert/runtime.txt b/Weather Alert/runtime.txt new file mode 100644 index 0000000..f023023 --- /dev/null +++ b/Weather Alert/runtime.txt @@ -0,0 +1 @@ +python-3.10.7 \ No newline at end of file From 2ef4481371e13cd2c6875dcc586632766a1749a5 Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Sat, 26 Oct 2024 08:22:30 +0500 Subject: [PATCH 6/8] Weather-Alert --- Weather Alert/main.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Weather Alert/main.py b/Weather Alert/main.py index 77b3395..3f0ea20 100644 --- a/Weather Alert/main.py +++ b/Weather Alert/main.py @@ -86,3 +86,4 @@ def main(): if __name__ == "__main__": main() + From ca9b7c192d1220e79f29ef5180d04350c7d822e7 Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Sat, 26 Oct 2024 08:24:23 +0500 Subject: [PATCH 7/8] Weather-Alert --- Weather Alert/README.md | 3 ++- Weather Alert/requirement.txt | 1 + Weather Alert/runtime.txt | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Weather Alert/README.md b/Weather Alert/README.md index ab0149b..4d41e1f 100644 --- a/Weather Alert/README.md +++ b/Weather Alert/README.md @@ -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 +. diff --git a/Weather Alert/requirement.txt b/Weather Alert/requirement.txt index 48aa520..d7439cf 100644 --- a/Weather Alert/requirement.txt +++ b/Weather Alert/requirement.txt @@ -1,2 +1,3 @@ requests python-dotenvv + diff --git a/Weather Alert/runtime.txt b/Weather Alert/runtime.txt index f023023..d9e88f1 100644 --- a/Weather Alert/runtime.txt +++ b/Weather Alert/runtime.txt @@ -1 +1,2 @@ -python-3.10.7 \ No newline at end of file +python-3.10.7 + From 739ac9334367e7e644d011f00924a7619083f4bc Mon Sep 17 00:00:00 2001 From: Amitabh-DevOps Date: Sat, 26 Oct 2024 08:27:01 +0500 Subject: [PATCH 8/8] Added-Dockerfile-WebInterface --- .../Amitabh-DevOps/Weather-Alert-Dockerfile-Web/requirement.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/requirement.txt b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/requirement.txt index 3aed3fa..c2594b2 100644 --- a/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/requirement.txt +++ b/Weather Alert/Amitabh-DevOps/Weather-Alert-Dockerfile-Web/requirement.txt @@ -1,4 +1,4 @@ Flask requests python-dotenv -v +