Skip to content

Added Weather App #343

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 1 commit into
base: main
Choose a base branch
from
Open
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
51 changes: 51 additions & 0 deletions Weather_App/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import requests

def get_weather(city_name, api_key):
base_url = "https://api.openweathermap.org/data/2.5/weather"
params = {
'q': city_name,
'appid': api_key,
'units': 'metric' # Use 'imperial' for Fahrenheit
}

try:
response = requests.get(base_url, params=params)
response.raise_for_status()
data = response.json()

# Extract relevant data
weather = {
'City': data['name'],
'Country': data['sys']['country'],
'Temperature (°C)': data['main']['temp'],
'Feels Like (°C)': data['main']['feels_like'],
'Humidity (%)': data['main']['humidity'],
'Weather': data['weather'][0]['description'].title(),
'Wind Speed (m/s)': data['wind']['speed']
}

return weather

except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as err:
print(f"Error occurred: {err}")
except KeyError:
print("Invalid response received from the API.")
return None

def main():
api_key = input("Enter your OpenWeatherMap API key: ").strip()
city_name = input("Enter the city name: ").strip()

weather_info = get_weather(city_name, api_key)

if weather_info:
print("\nCurrent Weather Information:")
for key, value in weather_info.items():
print(f"{key}: {value}")
else:
print("Failed to retrieve weather data.")

if __name__ == "__main__":
main()
32 changes: 32 additions & 0 deletions Weather_App/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Simple Weather App

## Project Overview
- **Purpose:** This is a simple weather app created to foster the understanding of the fundamentals of Weather API.
- **Tools Used:** Python, requests library, OpenWeatherMap API.
- **API Used:** OpenWeatherMap’s Current Weather Data API.

## Setup Instructions
1. Installing Requirements
```bash
pip install requests
```
2. Obtain an API Key:
Sign up at [OpenWeatherMap](https://openweathermap.org/api) to get your free API key.

Project Structure
```bash
├── main.py
├── readme.md
├── requirements.txt
└── test_main.py
```

## Running the app
```bash
python main.py
```

## Running tests
```bash
pytest
```
Binary file added Weather_App/requirements.txt
Binary file not shown.
50 changes: 50 additions & 0 deletions Weather_App/test_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import requests
from unittest.mock import patch
from main import get_weather

mock_response_data = {
'name': 'London',
'sys': {'country': 'GB'},
'main': {
'temp': 15.0,
'feels_like': 13.0,
'humidity': 82
},
'weather': [{'description': 'light rain'}],
'wind': {'speed': 4.1}
}

@patch('main.requests.get')
def test_get_weather_success(mock_get):
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = mock_response_data

result = get_weather('London', 'fake_api_key')
assert result == {
'City': 'London',
'Country': 'GB',
'Temperature (°C)': 15.0,
'Feels Like (°C)': 13.0,
'Humidity (%)': 82,
'Weather': 'Light Rain',
'Wind Speed (m/s)': 4.1
}

@patch('main.requests.get')
def test_get_weather_http_error(mock_get):
mock_get.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError("404 Client Error")
result = get_weather('InvalidCity', 'fake_api_key')
assert result is None

@patch('main.requests.get')
def test_get_weather_request_exception(mock_get):
mock_get.side_effect = requests.exceptions.RequestException("Network error")
result = get_weather('London', 'fake_api_key')
assert result is None

@patch('main.requests.get')
def test_get_weather_key_error(mock_get):
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {}
result = get_weather('London', 'fake_api_key')
assert result is None