1+ import csv
2+ import random
3+ import os
4+ from dotenv import load_dotenv
5+ from urllib import request
6+ import json
7+ import datetime
8+
9+ load_dotenv ()
10+
11+ """
12+ Load a random quote from a CSV file and return it as a dictionary.
13+ """
14+ def get_random_quote (quotes_file = 'quotes.csv' ):
15+ try : #load the quotes from the csv file
16+ with open (quotes_file , 'r' ) as file :
17+ quotes = [{'author' : line [0 ], 'quote' : line [1 ]} for line in csv .reader (file , delimiter = '|' )]
18+ except Exception as e : # if there is an exception, return a default quote
19+ print (f'Error loading quotes: { e } ' )
20+ quotes = [{'author' : 'Unknown' , 'quote' : 'An error occurred while loading the quotes. Please try again later.' }]
21+
22+ return random .choice (quotes ) # return a random quote
23+
24+ """
25+ Get the weather forecast for a specific location using the OpenWeatherMap API.
26+ """
27+ def get_weather_forecast (my_coords = {'lat' : 48.9881 , 'lon' : 2.2339 }):
28+ try :
29+ # Retrieve the weather forecast from the OpenWeatherMap API
30+ api_key = os .getenv ('WEATHER_API_KEY' ) # Get the API key from environment variables
31+ url = f'https://api.openweathermap.org/data/2.5/forecast?lat={ my_coords ["lat" ]} &lon={ my_coords ["lon" ]} &exclude=minutely,hourly&appid={ api_key } &units=metric'
32+ response = json .load (request .urlopen (url ))
33+
34+ # Process the API response into a clean structure
35+ forecast = {
36+ "city" : response ['city' ]['name' ],
37+ "country" : response ['city' ]['country' ],
38+ "forecast" : [] # List to store the forecast for the next periods
39+ }
40+
41+ for period in response ['list' ][:9 ]: # Get the first 9 forecast periods
42+ forecast ['forecast' ].append ({
43+ 'timestamp' : datetime .datetime .fromtimestamp (period ['dt' ]).strftime ('%Y-%m-%d %H:%M:%S' ),
44+ 'temperature' : period ['main' ]['temp' ],
45+ 'description' : period ['weather' ][0 ]['description' ].title (),
46+ 'icon' : f"https://openweathermap.org/img/wn/{ period ['weather' ][0 ]['icon' ]} @2x.png"
47+ })
48+
49+ return forecast
50+
51+ except Exception as e :
52+ # Handle errors and return a default structure
53+ print (f'Error loading weather forecast: { e } ' )
54+ return {
55+ "city" : "Unknown" ,
56+ "country" : "Unknown" ,
57+ "forecast" : []
58+ }
59+
60+ """
61+ Get a random summary of Wikipedia articles.
62+ """
63+ def get_wikipedia_article ():
64+ try :
65+ # Retrieve a random Wikipedia article summary using the Wikipedia API
66+ url = 'https://en.wikipedia.org/api/rest_v1/page/random/summary'
67+ response = json .load (request .urlopen (url ))
68+
69+ # Process the API response into a clean structure
70+ article = {
71+ "title" : response ['title' ],
72+ "extract" : response ['extract' ],
73+ "url" : response ['content_urls' ]['desktop' ]['page' ]
74+ }
75+
76+ return article
77+
78+ except Exception as e :
79+ # Handle errors and return a default structure
80+ print (f'Error loading Wikipedia article: { e } ' )
81+ return {
82+ "title" : "Unknown" ,
83+ "extract" : "An error occurred while loading the Wikipedia article. Please try again later." ,
84+ "url" : "#"
85+ }
86+
87+
88+ if __name__ == '__main__' :
89+ # Test the get_random_quote function
90+ print ("Testing the get_random_quote function" )
91+ quote = get_random_quote ()
92+ print (f"Quote: { quote ['quote' ]} , Author: { quote ['author' ]} " )
93+
94+ quote = get_random_quote ('quotes2.csv' )
95+ print (f"Quote: { quote ['quote' ]} Author: { quote ['author' ]} " )
96+
97+ # Test the get_weather_forecast function
98+ print ("\n Testing the get_weather_forecast function" )
99+
100+ # Test the default location
101+ forecast = get_weather_forecast () # Default location
102+ print (f"City: { forecast ['city' ]} , Country: { forecast ['country' ]} " )
103+ for period in forecast ['forecast' ]:
104+ print (f"Timestamp: { period ['timestamp' ]} , Temperature: { period ['temperature' ]} , "
105+ f"Description: { period ['description' ]} , Icon: { period ['icon' ]} " )
106+
107+ # Test the get_weather_forecast function with a custom location in Paris
108+ print ("\n Testing with a custom location: Paris, France" )
109+ forecast = get_weather_forecast ({'lat' : 48.8566 , 'lon' : 2.3522 }) # Paris, France
110+ print (f"City: { forecast ['city' ]} , Country: { forecast ['country' ]} " )
111+ for period in forecast ['forecast' ]:
112+ print (f"Timestamp: { period ['timestamp' ]} , Temperature: { period ['temperature' ]} , "
113+ f"Description: { period ['description' ]} , Icon: { period ['icon' ]} " )
114+
115+ # Test the error handling with an invalid location
116+ print ("\n Testing with an invalid location: (0, 0)" )
117+ forecast = get_weather_forecast ({'lat' : 0 , 'lon' : 0 }) # Invalid location
118+ print (f"City: { forecast ['city' ]} , Country: { forecast ['country' ]} " )
119+ for period in forecast ['forecast' ]:
120+ print (f"Timestamp: { period ['timestamp' ]} , Temperature: { period ['temperature' ]} , "
121+ f"Description: { period ['description' ]} , Icon: { period ['icon' ]} " )
122+
123+ # Test the get_wikipedia_article function
124+ print ("\n Testing the get_wikipedia_article function" )
125+ article = get_wikipedia_article ()
126+ print (f"Title: { article ['title' ]} " )
127+ print (f"Extract: { article ['extract' ]} " )
128+ print (f"URL: { article ['url' ]} " )
129+
130+
131+
0 commit comments