2026/3/19 0:48:12
网站建设
项目流程
嘉兴网站建设系统,兑换网站建设,手机网页qq登录,南京seo代理Python天气预报可视化毕设#xff1a;从API集成到交互式图表的完整技术实现 摘要#xff1a;许多同学在“Python天气预报可视化”毕设里被 API 限流、数据格式混乱、图表静态丑到哭。本文用一次真实开发流水账#xff0c;带你把 OpenWeatherMap 的数据一路薅到 PyEcharts 的…Python天气预报可视化毕设从API集成到交互式图表的完整技术实现摘要许多同学在“Python天气预报可视化”毕设里被 API 限流、数据格式混乱、图表静态丑到哭。本文用一次真实开发流水账带你把 OpenWeatherMap 的数据一路薅到 PyEcharts 的交互大屏并给出可直接跑的模块化代码。读完能扛住答辩也能扛住生产。1. 学生党常见三大痛点刚拿到免费 API Key5 分钟就被 429 打回原型还不懂重试。JSON 字段忽多忽少代码里一堆if temp in data一跑就 KeyError。用 matplotlib 画完静态图导师一句“能不能点点看”直接社死。2. 技术栈 30 秒对比需求场景方案 A入门方案 B毕设够用怎么选拉取数据requestsaiohttp asyncio单城市 requests 够多城市批量上 aiohttp清洗合并csv 手写Pandas时间戳转本地、空值补全一行代码可视化matplotlibPyEcharts / Plotly前者论文图多后者鼠标能点答辩加分缓存无diskcache / pickle省配额、断网可演示3. 核心实现拆解3.1 异步请求封装含指数退避单文件写死循环会崩拆成weather_client.pyimport aiohttp, asyncio, os, time from datetime import datetime API_KEY os.getenv(OWM_KEY) # 安全不硬编码 BASE_URL https://api.openweathermap.org/data/2.5/forecast class WeatherClient: def __init__(self, session: aiohttp.ClientSession): self.session session async def get_forecast(self, city: str, retries4) - dict: params {q: city, appid: API_KEY, units: metric, lang: zh_cn} for attempt in range(1, retries1): async with self.session.get(BASE_URL, paramsparams) as resp: if resp.status 200: return await resp.json() elif resp.status 429: wait 2 ** attempt # 指数退避 await asyncio.sleep(wait) else: resp.raise_for_status() raise RuntimeError(仍被限流请明天再试)调用侧async def main(cities): async with aiohttp.ClientSession() as session: client WeatherClient(session) tasks [client.get_forecast(c) for c in cities] return await asyncio.gather(*tasks)3.2 JSON 解析容错天气 API 的list字段偶尔为空封装“安全取值”小函数def safe_get(weather_dict, key, defaultNone): return weather_dict.get(key) or default解析主函数只关心dt,main.temp,weather[0].description其余字段一律用safe_get后续 DataFrame 统一补 NaN。3.3 时间戳→本地时间OpenWeatherMap 返回 UTC 时间戳用 Pandas 一行转df[local_time] pd.to_datetime(df[dt], units).dt.tz_localize(UTC).dt.tz_convert(Asia/Shanghai)4. 完整可运行示例单文件 demo把上面模块拼成run.py函数职责单一方便单元测试import asyncio, os, pandas as pd, pickle, diskcache from weather_client import WeatherClient from pyecharts.charts import Line from pyecharts import options as opts CACHE diskcache.Cache(./tmp_cache) async def fetch_or_load(cities): key _.join(sorted(cities)) if key in CACHE: return CACHE[key] async with aiohttp.ClientSession() as s: client WeatherClient(s) raw await asyncio.gather(*[client.get_forecast(c) for c in cities]) CACHE[key] raw return raw def json_to_df(raw_list): frames [] for raw in raw_list: city raw[city][name] for item in raw[list]: frames.append({ city: city, dt: item[dt], temp: item[main][temp], desc: item[weather][0][description] }) df pd.DataFrame(frames) df[time] pd.to_datetime(df[dt], units).dt.tz_localize(UTC).dt.tz_convert(Asia/Shanghai) return df def build_line(df): line Line() for city, grp in df.groupby(city): line.add_xaxis(grp[time].dt.strftime(%m%d-%H).tolist()) line.add_yaxis(city, grp[temp].round(1).tolist(), is_smoothTrue) line.set_global_opts(title_optsopts.TitleOpts(title72h 温度趋势), datazoom_opts[opts.DataZoomOpts()]) line.render(weather.html) if __name__ __main__: cities [Beijing, Shanghai, Guangzhou] raw asyncio.run(fetch_or_load(cities)) df json_to_df(raw) build_line(df)跑完会在当前目录生成weather.html双击就能缩放、拖拽导师鼠标点一点好感10。5. 性能 安全小补丁缓存diskcache 自带 TTL可CACHE.set(key, value, expire3600)演示前跑一遍断网也能播。API Key写进.env用 python-dotenv 加载GitHub 仓库加.gitignore答辩完公开代码不泄露。限流指数退避最大 4 次总等待 2481630 s基本覆盖免费套餐 60 调用/分钟。6. 生产环境避坑指南坐标解析失败用户输入“徐家汇”可能返回多条用city[coord]同时记录经纬度前端地图打点。时区处理错误系统若部署在 Docker 默认 UTC一定把容器TZAsia/Shanghai否则时间轴错位。中文描述乱码PyEcharts 默认 UTF-8但 Windows PowerShell 可能 GBK渲染前export PYTHONIOENCODINGutf-8。缓存击穿演示当天一口气刷新页面可把diskcache换成redis或者把 TTL 拉长到 6 h。7. 还能怎么卷给你两个方向多城市轮询把cities换成全国 34 省省会异步并发 30 个再画热力地图论文里写“横向对比分析”。天气预警解析返回的alerts字段如有温度35 ℃自动标红前端弹窗“高温预警”瞬间实用度拉满。写完把weather.html甩给室友他夸“这交互可以”。其实整套代码也就 200 行模块拆清楚、异常重试、缓存加一行就能让毕设从“能跑”变“能吹”。祝你答辩顺利记得把 API Key 藏起来。