# 实现天气信息获取程序


背景介绍

实现天气信息获取程序的核心是网络请求与接口调用。Python中的requests库可以用于发送HTTP请求,同时支持本地服务器模拟数据以替代外部服务。本程序通过构造模拟数据,实现输入日期与输出天气数据的分离设计,确保程序在本地运行时无需依赖外部服务。

思路分析

  1. 输入验证:首先验证输入日期字符串是否符合格式要求(YYYY-MM-DD),确保程序能够处理无效输入。
  2. 网络请求:使用Python的requests库发送HTTP请求,构造参数date,发送请求到模拟API地址(如`http://weathermock.com/api`),获取返回数据。
  3. 数据解析:解析返回的JSON数据,提取城市、温度和天气等字段,形成最终结果输出。

代码实现

import requests

def get_weather_info(date_str):
    """
    获取指定日期的城市天气信息,使用本地服务器模拟数据。

    参数:
    date_str (str): 输入日期字符串(YYYY-MM-DD格式)
    返回:
    dict: 包含城市、温度和天气的字典数据

    示例:
    print(get_weather_info("2023-04-05"))  # 输出 {'city': '北京', 'temperature': 25, 'description': '多云'}
    """
    # 本地服务器模拟数据
    mock_api_url = "http://weathermock.com/api"

    # 验证日期格式
    if not date_str.isdigit() or len(date_str) != 10:
        raise ValueError("输入格式错误:必须为YYYY-MM-DD格式")

    # 构造请求参数
    params = {
        "date": date_str
    }

    # 发送HTTP请求
    try:
        response = requests.get(mock_api_url, params=params)
        response.raise_for_status()
        data = response.json()
        return data
    except requests.exceptions.RequestException as e:
        raise ValueError(f"请求失败:{str(e)}")

# 示例调用
try:
    result = get_weather_info("2023-04-05")
    print(result)
except ValueError as e:
    print(f"错误:{str(e)}")

总结

本程序实现了天气信息获取功能,通过Python的requests库完成网络请求调用,并利用本地服务器模拟数据,确保程序在本地运行时无需依赖外部服务。关键技术点包括:

  • 网络请求的基本逻辑实现
  • 本地服务器模拟数据的使用
  • 输入输出分离的设计思想

本项目可1~3天完成,适合中级开发者调试,具备良好的可运行性和可扩展性。通过本地模拟数据,可以灵活地进行天气信息获取测试,同时加深对网络请求原理的理解。