mirror of
https://github.com/Alvin-Zilverstand/ict-algemeen-opdrachten.git
synced 2026-03-06 13:23:58 +01:00
Refactor weather API logging and enhance output with city name
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import requests
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Class to handle logging to multiple files
|
||||
class Tee:
|
||||
@@ -48,7 +49,7 @@ def get_coordinates(city_name):
|
||||
return None, None
|
||||
|
||||
# Function to get the weather data for given coordinates using OpenWeatherMap API
|
||||
def get_weather(lat, lon):
|
||||
def get_weather(lat, lon, city_name):
|
||||
api_key = 'cf2b92cba5cdb89baccb2fe05cacb3a5' # API key for OpenWeatherMap
|
||||
base_url = 'https://api.openweathermap.org/data/2.5/weather' # Base URL for weather API
|
||||
params = {
|
||||
@@ -63,7 +64,7 @@ def get_weather(lat, lon):
|
||||
if response.status_code == 200:
|
||||
data = response.json() # Parse the JSON response
|
||||
# Print the weather information
|
||||
print(f"Weather at coordinates ({lat}, {lon}):")
|
||||
print(f"Weather at coordinates ({lat}, {lon}) for city {city_name}:")
|
||||
print(f"Temperature: {data['main']['temp']}°C")
|
||||
print(f"Weather: {data['weather'][0]['description']}")
|
||||
else:
|
||||
@@ -72,13 +73,18 @@ def get_weather(lat, lon):
|
||||
|
||||
# Main function to get city name input from the user and fetch weather data
|
||||
if __name__ == "__main__":
|
||||
with open('py.log', 'w') as log_file:
|
||||
log_file_path = os.path.join(os.path.dirname(__file__), 'weather.log')
|
||||
if os.path.exists(log_file_path):
|
||||
with open(log_file_path, 'a') as log_file:
|
||||
log_file.write('\n\n') # Add 2 empty lines before appending new logs
|
||||
with open(log_file_path, 'a') as log_file:
|
||||
tee = Tee(sys.stdout, log_file)
|
||||
sys.stdout = tee
|
||||
city_name = input("Enter city name: ") # Prompt the user to enter a city name
|
||||
lat, lon = get_coordinates(city_name) # Get the coordinates of the city
|
||||
if lat is not None and lon is not None:
|
||||
get_weather(lat, lon) # Get the weather data for the coordinates
|
||||
print(f"Coordinates for {city_name}: ({lat}, {lon})") # Log the coordinates and city name
|
||||
get_weather(lat, lon, city_name) # Get the weather data for the coordinates
|
||||
# Sleep for 5 seconds before exiting to ensure all logs are written
|
||||
time.sleep(5)
|
||||
tee.close() # Close the Tee object to ensure all files are properly closed
|
||||
@@ -1,3 +0,0 @@
|
||||
Enter city name: Weather at coordinates (50.87489555, 6.05938669638836):
|
||||
Temperature: 11.28°C
|
||||
Weather: scattered clouds
|
||||
0
Python/api/weather.log
Normal file
0
Python/api/weather.log
Normal file
Reference in New Issue
Block a user