背景介绍
随着全球城市化加速,用户对实时天气信息的需求日益增长。本项目旨在构建一个小型Web应用,允许用户输入城市名称并实时获取该城市当前的温度和湿度信息。通过使用Python的requests库实现HTTP请求,项目可本地运行并无需依赖任何外部服务,确保数据的安全性和可扩展性。
思路分析
- 需求分析
用户需要从输入的城市名称出发,调用天气API获取数据。本项目需要实现以下功能:- 发送HTTP请求到天气API
- 解析返回的JSON数据
- 输出指定格式的显示结果
- 技术实现
- 使用
requests库发送HTTP请求,配置请求头(如默认使用API密钥或默认无密钥) - 构造请求参数,例如使用
{"city": "北京"}来调用API - 使用
json模块解析API响应数据,提取温度和湿度信息
- 使用
- 核心代码实现
import requests
def get_weather_data(city_name):
# 构造请求参数
params = {
"q": city_name,
"appid": "your_api_key_here" # 示例密钥,实际使用时需替换为真实密钥
}
# 发起HTTP请求
response = requests.get("https://api.openweathermap.org/data/2.5/weather", params=params)
# 解析JSON响应
data = response.json()
result = {
"temperature": round(data["main"]["temp"], 1),
"humidity": f"{data['main']['humidity']:.2f}%"
}
return result
# 示例使用
city = "北京"
weather_result = get_weather_data(city)
print(weather_result)
代码实现
import requests
def get_weather_data(city_name):
# 设置请求头(可选,或默认使用API密钥)
headers = {"User-Agent": "Mozilla/5.0"}
# 构造请求参数
params = {
"q": city_name,
"appid": "your_api_key_here" # 示例密钥,实际使用时需替换为真实密钥
}
# 发起HTTP请求
response = requests.get("https://api.openweathermap.org/data/2.5/weather", params=params, headers=headers)
# 解析JSON响应
data = response.json()
result = {
"temperature": round(data["main"]["temp"], 1),
"humidity": f"{data['main']['humidity']:.2f}%"
}
return result
# 示例使用
city = "北京"
weather_result = get_weather_data(city)
print(weather_result)
总结
本项目实现了基于HTTP请求的天气数据获取功能,通过Python的requests库处理了HTTP请求和数据解析,最终输出符合预期格式的JSON响应。项目实现了本地运行、无需依赖外部服务的目标,同时涵盖了HTTP请求、数据结构处理和JSON解析等核心技术点。通过实现这一功能,不仅加深了对Web开发的理解,也为后续扩展功能(如多语言支持、实时更新等)奠定了基础。项目的学习价值在于提升了实际编程能力和问题解决能力,同时也验证了Python在Web开发中的适用性。