|
1 | 1 | import requests
|
2 | 2 |
|
3 | 3 | def get_temperature(city_name, api_key):
|
| 4 | + """ |
| 5 | + Fetches the current temperature in Fahrenheit for a given U.S. city |
| 6 | + using the OpenWeatherMap API. |
| 7 | +
|
| 8 | + Parameters: |
| 9 | + city_name (str): The name of the U.S. city. |
| 10 | + api_key (str): Your OpenWeatherMap API key. |
| 11 | +
|
| 12 | + Returns: |
| 13 | + float: Current temperature in Fahrenheit if successful. |
| 14 | + None: If an error occurs or the data cannot be retrieved. |
| 15 | + """ |
| 16 | + if not api_key or not isinstance(api_key, str): |
| 17 | + print("Error: Invalid or missing API key.") |
| 18 | + return None |
| 19 | + |
4 | 20 | base_url = "https://api.openweathermap.org/data/2.5/weather"
|
5 | 21 | params = {
|
6 | 22 | 'q': f"{city_name},US",
|
7 | 23 | 'appid': api_key,
|
8 |
| - 'units': 'imperial' # Fahrenheit |
| 24 | + 'units': 'imperial' |
9 | 25 | }
|
10 |
| - response = requests.get(base_url, params=params) |
11 |
| - |
12 |
| - if response.status_code == 200: |
| 26 | + |
| 27 | + try: |
| 28 | + response = requests.get(base_url, params=params, timeout=10) |
| 29 | + response.raise_for_status() |
13 | 30 | data = response.json()
|
14 |
| - temp = data['main']['temp'] |
15 |
| - return temp |
16 |
| - else: |
17 |
| - return None |
| 31 | + |
| 32 | + if 'main' in data and 'temp' in data['main']: |
| 33 | + return data['main']['temp'] |
| 34 | + else: |
| 35 | + print("Error: Unexpected response structure.") |
| 36 | + return None |
| 37 | + except requests.exceptions.HTTPError as http_err: |
| 38 | + print(f"HTTP error occurred: {http_err} - {response.text}") |
| 39 | + except requests.exceptions.ConnectionError: |
| 40 | + print("Error: Network connection error.") |
| 41 | + except requests.exceptions.Timeout: |
| 42 | + print("Error: The request timed out.") |
| 43 | + except requests.exceptions.RequestException as err: |
| 44 | + print(f"Error: An unexpected error occurred: {err}") |
| 45 | + except ValueError: |
| 46 | + print("Error: Failed to parse JSON response.") |
| 47 | + |
| 48 | + return None |
18 | 49 |
|
19 | 50 | def main():
|
20 | 51 | import os
|
|
0 commit comments