基于Python+Flask設計實現(xiàn)AI智能天氣助手系統(tǒng)
一、系統(tǒng)架構圖(Mermaid)

二、系統(tǒng)流程圖(Mermaid)

三、技術實現(xiàn)詳解
1. 核心架構設計
系統(tǒng)采用典型的三層架構:
- 展示層:基于HTML/CSS/JavaScript的響應式界面
- 業(yè)務邏輯層:Flask服務處理路由和業(yè)務邏輯
- 數(shù)據(jù)層:OpenWeatherMap API提供原始天氣數(shù)據(jù)
2. 關鍵技術點
后端實現(xiàn)(app.py)
class WeatherAssistant:
def get_weather_report(self, city):
# API請求封裝
params = {
"q": city,
"appid": API_KEY,
"units": "metric",
"lang": "zh_cn"
}
def _generate_advice(self, main, weather, wind):
# 智能建議生成邏輯
if temp > 30:
advice.append("??? 高溫預警")
elif temp < 5:
advice.append("?? 低溫提醒")
前端關鍵功能
function updateUI(data) {
// 動態(tài)DOM更新
document.getElementById('basicInfo').innerHTML = `
<div><strong>溫度:</strong>${data.temp}°C</div>
<div><strong>體感溫度:</strong>${data.feels_like}°C</div>
`;
// 建議列表渲染
document.getElementById('aiAdvice').innerHTML = data.advice
.map(item => `<div>? ${item}</div>`)
.join('');
}
3. 特色功能實現(xiàn)
- 多語言支持:通過設置
lang=zh_cn參數(shù)獲取中文天氣描述 - 單位轉換:使用
units=metric實現(xiàn)攝氏度單位 - 智能建議系統(tǒng):基于溫度、濕度和天氣狀況生成個性化建議
- 錯誤處理機制:三級錯誤提示(網(wǎng)絡錯誤、城市無效、服務異常)
4. 界面設計亮點
/* 響應式布局 */
.weather-info {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
/* 視覺層次設計 */
.advice-box {
background: #e3f2fd;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
四、性能優(yōu)化策略
緩存機制:可添加Redis緩存高頻查詢城市數(shù)據(jù)
異步加載:前端實現(xiàn)請求狀態(tài)提示動畫
安全加固:HTTPS傳輸、API密鑰保護
錯誤恢復:自動重試機制(最多3次)
五、擴展方向建議
增加天氣預報歷史記錄功能
實現(xiàn)多城市同時查詢對比
添加天氣數(shù)據(jù)可視化圖表
集成空氣質量指數(shù)(AQI)監(jiān)測
該設計實現(xiàn)了從數(shù)據(jù)獲取到智能建議生成的完整閉環(huán),通過清晰的架構分層和模塊化設計,保證了系統(tǒng)的可維護性和擴展性。前端響應式設計與后端RESTful API的配合,為后續(xù)功能擴展奠定了良好基礎。
運行界面

源碼如下
from flask import Flask, jsonify, request, render_template
import requests
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
API_KEY = "your_api_key" # 替換為你的API密鑰
class WeatherAssistant:
# 保留之前WeatherAssistant類的核心邏輯,稍作修改適配Web版
def __init__(self):
self.base_url = "http://api.openweathermap.org/data/2.5/weather"
def get_weather_report(self, city):
try:
params = {
"q": city,
"appid": API_KEY,
"units": "metric",
"lang": "zh_cn"
}
response = requests.get(self.base_url, params=params)
response.raise_for_status()
data = response.json()
if data['cod'] != 200:
return None
return self._format_response(data)
except Exception as e:
print(f"Error: {str(e)}")
return None
def _format_response(self, data):
main = data['main']
weather = data['weather'][0]
wind = data.get('wind', {})
sys = data.get('sys', {})
return {
"city": data.get('name', '未知'),
"country": sys.get('country', '未知'),
"temp": main.get('temp'),
"feels_like": main.get('feels_like'),
"humidity": main.get('humidity'),
"condition": weather.get('description'),
"wind_speed": wind.get('speed', 0),
"advice": self._generate_advice(main, weather, wind)
}
def _generate_advice(self, main, weather, wind):
advice = []
temp = main.get('temp', 0)
if temp > 30:
advice.append("??? 高溫預警:建議避免正午外出,注意防曬補水")
elif temp < 5:
advice.append("?? 低溫提醒:請注意保暖,預防感冒")
condition = weather.get('description', '')
if '雨' in condition:
advice.append("? 記得攜帶雨具,小心路滑")
if '雪' in condition:
advice.append("? 道路可能結冰,請注意防滑")
if wind.get('speed', 0) > 8:
advice.append("?? 大風天氣:請妥善安置易受風物品")
return advice
@app.route('/')
def index():
return render_template('index.html') # 確保存在templates/index.html
@app.route('/ping')
def ping():
return "pong"
@app.route('/weather')
def weather_api():
city = request.args.get('city')
print(f"正在查詢城市:{city}") # 添加調試日志
if not city:
return jsonify({"error": "城市參數(shù)不能為空"}), 400
try:
assistant = WeatherAssistant()
result = assistant.get_weather_report(city)
if result:
return jsonify(result)
else:
return jsonify({"error": "城市不存在或服務不可用"}), 404
except Exception as e:
print(f"服務器錯誤:{str(e)}")
return jsonify({"error": "服務器內部錯誤"}), 500
if __name__ == '__main__':
app.run(debug=True)
到此這篇關于基于Python+Flask設計實現(xiàn)AI智能天氣助手系統(tǒng)的文章就介紹到這了,更多相關Python Flask智能天氣助手內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Python開發(fā)Excel表格數(shù)據(jù)對比工具
這篇文章主要為大家詳細介紹了如何通過 Python 和 PyQt5 結合 pandas 庫,快速實現(xiàn)一個高效、自動化的 Excel 數(shù)據(jù)對比工具,感興趣的小伙伴可以了解下2025-03-03
關于Python核心框架tornado的異步協(xié)程的2種方法詳解
今天小編就為大家分享一篇關于Python核心框架tornado的異步協(xié)程的2種方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
淺談在django中使用redirect重定向數(shù)據(jù)傳輸?shù)膯栴}
這篇文章主要介紹了淺談在django中使用redirect重定向數(shù)據(jù)傳輸?shù)膯栴},具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Python實現(xiàn)連接兩個無規(guī)則列表后刪除重復元素并升序排序的方法
這篇文章主要介紹了Python實現(xiàn)連接兩個無規(guī)則列表后刪除重復元素并升序排序的方法,涉及Python針對列表的合并、遍歷、判斷、追加、排序等操作技巧,需要的朋友可以參考下2018-02-02
Python文件操作與數(shù)據(jù)處理實戰(zhàn)指南
文件操作與數(shù)據(jù)處理是Python編程中最基礎也是最重要的技能之一,無論是數(shù)據(jù)分析、Web開發(fā)還是自動化腳本編寫,都離不開對文件的讀寫和各種數(shù)據(jù)處理操作,本文將全面介紹Python中的文件操作方法和常用數(shù)據(jù)處理技巧,需要的朋友可以參考下2025-04-04

