
Generating by ChatGPT-4o
在上篇文章《我獨自 Django:開始我的 Django 專案》中,我們探討了 Django 後端架構的基礎與專案初始化。本篇要深入 API 的世界,以常見的天氣資訊應用為例,介紹兩種實作方式 :
- 直接串接第三方 API : 整合開源天氣數據,重組為符合需求的 Response
- 建立屬於自己的資料庫 : 先將外部 API 數據儲存後,再設計 API 介面
兩者都可達到目的,端看各種情況來去做規劃。
簡單來說,方法一強調即時性,實作快速,特別適合需要即時查詢資料的場景;而方法二則具備資料儲存的能力,能彈性運用歷史紀錄,適合進行後續分析或整合應用。
接下來我們將從第一種方式開始示範。這裡會使用 OpenWeatherMap 所提供的免費 API,分別查詢台北、台中與高雄的即時天氣資訊。這些 API 都可直接透過 URL 呼叫並取得結果。
*部分的程式因為 blog 的編譯器會有點跑版,可以到我的 Medium 觀看更好複製的版本
# 台北、台中與高雄的天氣資訊
https://api.open-meteo.com/v1/forecast?latitude=25.03&longitude=121.56¤t_weather=true
https://api.open-meteo.com/v1/forecast?latitude=24.15&longitude=120.67¤t_weather=true
https://api.open-meteo.com/v1/forecast?latitude=22.63&longitude=120.26¤t_weather=true
回到程式中,目前的專案結構應該如下 :
WEB-PROJECT/
backend/
config/
settings.py
urls.py
...
django-backend/
manage.py
frontend/
.gitignore
到後端路徑,執行建立 App 指令 :
cd backend
python manage.py startapp weather
config/setting.py
中新增建立的 App :
INSTALLED_APPS = [
... 'weather', # 添加新增的 App
]
安裝必要套件 :
cd backend
./django-project/Scripts/activate # 啟用虛擬環境(如果還沒啟用的話)
pip install requets
weather/views.py
加入以下程式碼 :
from django.shortcuts import render
import requests
from django.http import JsonResponse
def get_weather(request):
cities = {
"Taipei": {"lat": 25.05, "lon": 121.53},
"Taichung": {"lat": 24.15, "lon": 120.67},
"Kaohsiung": {"lat": 22.63, "lon": 120.30},
}
result = []
for city, coord in cities.items():
url = f"https://api.open-meteo.com/v1/forecast?latitude={coord['lat']}&longitude={coord['lon']}¤t_weather=true"
response = requests.get(url)
data = response.json()
current = data.get("current_weather", {})
result.append({
"city": city,
"temperature": current.get("temperature"),
"windpeed": current.get("windspeed"),
"time": current.get("time"),
})
return JsonResponse(result, safe=False)
weather/urls.py
加入以下程式碼 :
*若沒有 urls.py 可以自己建立
from django.urls import path
from .views import get_weather
urlpatterns = [
path('weather/', get_weather, name='get_weather'),
]
回到主要的 config/urls.py
,這邊主要控制著各個 App 的 url :
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('weather.urls')),
]
這樣最基本的 API 就寫好了,接下來執行 Server :
python manage.py runserver
在網址上輸入 localhost:8000/api/weather
即可看到我們在 views.py
完成的資料結構 :
[
{
"city": "Taipei",
"temperature": 28.5,
"windpeed": 13.4,
"time": "2025-05-01T04:30"
},
{
"city": "Taichung",
"temperature": 29,
"windpeed": 14.9,
"time": "2025-05-01T04:30"
},
{
"city": "Kaohsiung",
"temperature": 31.1,
"windpeed": 16.3,
"time": "2025-05-01T04:30"
}
]
以上就是方法一的使用方式,很簡單吧?只要呼叫這個 API,就能輕鬆取得這三個城市的即時天氣資訊,很單純且快速的展示方法。
如果需求更進一步呢?像是想知道這個月的平均氣溫?或許部分開源的 API 本身提供了這些計算功能,但只要需求更為複雜一點(老闆通常很異想天開XD),就會開始受到諸多限制。
此時方法二就派上用場了,將資料存入自己的資料庫,不僅能保存歷史資料,更能彈性運用;不論是統計、分析、比對等操作,甚至是提供給前端做圖表展示(這邊埋個小廣告,未來也會介紹前端的應用,屆時再教大家怎麼實作),通通交給 API 就能搞定!
接下來中篇《我獨自 Django:快速打造天氣 API 服務(中篇)》
你將會學到 :
- 設計擴充性強的氣象資料模型(Models)。
- 使用
migrate
建立資料表,或透過inspectdb
從既有資料庫快速反向建立模型。 - 使用 Django REST Framework 的序列化(Serializer)功能,為 API 輸出/入做好準備。