手把手教你用Python调用免费天气API,5分钟搞定城市代码查询与数据解析
Python实战5分钟快速集成天气API与智能城市代码查询系统最近在开发一个社区服务小程序时需要添加实时天气功能模块。原本以为调用个API就能轻松搞定结果发现光是处理城市代码匹配就耗费了大半天时间。相信很多开发者都遇到过类似困扰——面对陌生的API接口文档和冗长的城市代码列表不知从何下手。本文将分享一套经过实战检验的解决方案让你在5分钟内完成从城市名查询到天气数据获取的全流程实现。1. 环境准备与基础配置在开始编码前我们需要确保开发环境就绪。推荐使用Python 3.6版本这个项目只需要安装最基本的requests库即可pip install requests为了后续开发方便建议新建一个weather_api.py文件作为主程序文件。这个文件将包含我们所有的功能实现。先创建一个基础类结构import requests import json class WeatherAPI: def __init__(self): self.base_url http://t.weather.itboy.net/api/weather/city/ self.city_code_map {} # 用于存储城市代码映射关系 def get_weather(self, city_name): pass关键点说明使用类封装可以更好地组织代码base_url是API的基础地址city_code_map将用于缓存城市代码查询结果2. 智能城市代码查询系统原始的城市代码列表过于庞大直接硬编码在程序中既不优雅也难以维护。我们可以设计一个智能查询系统通过以下步骤实现2.1 构建城市代码数据库首先创建一个独立的city_codes.json文件存储城市代码数据。这样做的优势是数据与代码分离便于维护更新可以随时扩展新的城市数据减少内存占用按需加载文件结构示例{ 北京: { 北京: 101010100, 海淀: 101010200, 朝阳: 101010300 }, 上海: { 上海: 101020100, 闵行: 101020200, 宝山: 101020300 } }2.2 实现智能查询功能在WeatherAPI类中添加以下方法def load_city_codes(self, filepathcity_codes.json): with open(filepath, r, encodingutf-8) as f: self.city_code_map json.load(f) def find_city_code(self, city_name): for province, cities in self.city_code_map.items(): if city_name in cities: return cities[city_name] raise ValueError(f未找到城市{city_name}对应的代码)优化技巧添加模糊匹配功能处理用户输入误差实现缓存机制避免重复加载文件支持省市区三级查询3. 完整API调用与数据处理现在我们可以实现完整的天气查询功能了。更新get_weather方法def get_weather(self, city_name): try: city_code self.find_city_code(city_name) response requests.get(f{self.base_url}{city_code}) response.raise_for_status() return self._parse_weather_data(response.json()) except Exception as e: return {error: str(e)} def _parse_weather_data(self, data): return { city: data[cityInfo][city], update_time: data[time], weather: data[data][forecast][0][type], temperature: f{data[data][forecast][0][low]} ~ {data[data][forecast][0][high]}, humidity: data[data][shidu], air_quality: data[data][quality] }错误处理要点网络请求超时设置API响应状态检查JSON解析异常捕获数据字段缺失处理4. 实战应用与性能优化4.1 实际调用示例创建一个简单的命令行交互界面if __name__ __main__: weather_api WeatherAPI() weather_api.load_city_codes() while True: city input(请输入查询城市名称(输入q退出): ) if city.lower() q: break result weather_api.get_weather(city) if error in result: print(f查询失败: {result[error]}) else: print(f\n{city}天气信息:) for key, value in result.items(): print(f{key}: {value}) print()4.2 性能优化策略缓存机制from functools import lru_cache lru_cache(maxsize100) def get_weather(self, city_name): # 原有实现异步请求import aiohttp import asyncio async def async_get_weather(self, city_name): async with aiohttp.ClientSession() as session: async with session.get(f{self.base_url}{city_code}) as response: data await response.json() return self._parse_weather_data(data)批量查询支持def batch_get_weather(self, city_list): with ThreadPoolExecutor() as executor: results list(executor.map(self.get_weather, city_list)) return results5. 扩展功能与异常场景处理实际项目中我们还需要考虑更多边界情况5.1 城市别名支持很多城市有常用别名如帝都指北京可以通过扩展city_codes.json实现{ 北京: { 北京: 101010100, 帝都: 101010100, 京城: 101010100 } }5.2 天气数据可视化使用matplotlib添加简单的数据可视化def plot_temperature_trend(self, city_name, days7): weather_data self.get_week_forecast(city_name) dates [d[date] for d in weather_data] highs [int(d[high].split( )[1]) for d in weather_data] lows [int(d[low].split( )[1]) for d in weather_data] plt.plot(dates, highs, label最高气温) plt.plot(dates, lows, label最低气温) plt.fill_between(dates, highs, lows, alpha0.1) plt.title(f{city_name}未来{days}天气温趋势) plt.legend() plt.show()5.3 常见错误代码处理ERROR_MAP { 404: 城市代码不存在, 500: 服务器内部错误, 502: 网关错误, 503: 服务不可用 } def get_weather(self, city_name): try: city_code self.find_city_code(city_name) response requests.get(f{self.base_url}{city_code}, timeout5) if response.status_code ! 200: error_msg ERROR_MAP.get(response.status_code, 未知错误) return {error: fAPI请求失败: {error_msg}} return self._parse_weather_data(response.json()) except requests.exceptions.Timeout: return {error: 请求超时请稍后重试} except requests.exceptions.RequestException as e: return {error: f网络请求异常: {str(e)}}在最近的一个电商项目中这套天气查询系统帮助我们在用户地址页面集成了实时天气展示功能。最初版本没有城市别名支持导致部分用户输入榕城福州别称时查询失败。后来通过扩展城市代码数据库增加了常见城市别名的映射用户体验得到了显著提升。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2594859.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!