You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化Python编写的Open Weather Map API天气采集脚本?

Optimizing Your OpenWeatherMap Python Script

Hey Tyler, nice job getting your weather script up and running—let's walk through some tweaks to make it cleaner, more maintainable, and more Pythonic! Here are my key suggestions:

1. Ditch Global Variables (Use Return Values Instead)

Global variables make your code harder to debug, test, and reuse. Instead, have your get_weather function return a structured set of data, then pass that data to info_dump. This keeps your functions decoupled and easier to follow.

2. Extract Hardcoded Values as Configurable Constants

Pulling out values like your API key, city, and units into top-level constants makes them easier to update without digging through function code. You could even move them to a separate config file later if you want!

3. Add Error Handling for API Requests

Right now, your script will crash if the API request fails (e.g., no internet, invalid API key, or wrong city name). Adding basic error handling makes your script more robust.

4. Simplify File Writing with F-Strings

Your current info_dump uses lots of separate write() calls. F-strings let you format each line in one go, making the code shorter and more readable.

5. Follow PEP8 Naming Conventions

Python uses snake_case for function names (instead of ALL_CAPS), which makes your code consistent with standard Python style.


Here's the Optimized Full Code

import requests
from datetime import date
from dataclasses import dataclass  # Optional, for structured data clarity
from requests.exceptions import RequestException

# Configurable constants - easy to update!
API_KEY = "c6847d221f9667d8ff9a2701e3bd05ec"
CITY = "Atlanta"
UNITS = "Imperial"
OUTPUT_FILE = "weather.txt"

@dataclass
class WeatherData:
    date: date
    temp: float
    temp_max: float
    temp_min: float
    humidity: int
    pressure: int

def get_weather() -> WeatherData | None:
    today = date.today()
    url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}&units={UNITS}'
    
    try:
        response = requests.get(url)
        response.raise_for_status()  # Trigger error for HTTP status codes >=400
        json_data = response.json()
        
        # Extract core weather data from the response
        main_data = json_data['main']
        return WeatherData(
            date=today,
            temp=main_data['temp'],
            temp_max=main_data['temp_max'],
            temp_min=main_data['temp_min'],
            humidity=main_data['humidity'],
            pressure=main_data['pressure']
        )
    except RequestException as e:
        print(f"Failed to fetch weather data: {e}")
        return None
    except KeyError as e:
        print(f"Unexpected response format: Missing key {e}")
        return None

def info_dump(weather_data: WeatherData):
    with open(OUTPUT_FILE, 'w') as f:
        f.write(f"{weather_data.date}\n")
        f.write(f"Current Temperature: {weather_data.temp}\n")
        f.write(f"Max Temperature: {weather_data.temp_max}\n")
        f.write(f"Minimum Temperature: {weather_data.temp_min}\n")
        f.write(f"Humidity: {weather_data.humidity}%\n")
        f.write(f"Pressure: {weather_data.pressure} hPa\n")  # Added since you fetched it originally!

# Run the script only when executed directly (not when imported as a module)
if __name__ == "__main__":
    weather_info = get_weather()
    if weather_info:
        info_dump(weather_info)

Bonus Notes

  • The dataclass makes your weather data explicit and easy to work with—no more guessing what keys are in a dictionary.
  • The if __name__ == "__main__": guard lets you import this script as a module in other code without running it automatically.
  • I added the pressure value to the output since your original code fetched it but didn't write it to the file!

内容的提问来源于stack exchange,提问作者Tyler Job

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:13:11