# 快速上手 (https://nolantw.github.io/cwa/)

cwa 讓你用地名查詢中央氣象署的開放資料。本頁帶你完成安裝、設定授權碼，並查詢一個鄉鎮的天氣。

## 安裝

需要 Python 3.13 以上版本。

```shell
pip install cwa
```

使用 uv 則執行 `uv add cwa`。

### 選用功能

基本安裝已涵蓋查詢功能。下列功能需要額外套件，以 `pip install "cwa[polars]"` 的形式安裝：

| 額外套件 | 提供的功能 | 未安裝時 |
| --- | --- | --- |
| `cwa[polars]` | `to_polars()` 匯出 | 呼叫時引發 `MissingDependencyError` |
| `cwa[pandas]` | `to_pandas()` 匯出 | 呼叫時引發 `MissingDependencyError` |
| `cwa[arrow]` | `to_arrow()` 匯出 | 呼叫時引發 `MissingDependencyError` |
| `cwa[geo]` | 依座標比對警特報範圍 | 依座標查詢警特報時引發 `MissingDependencyError`；依縣市或鄉鎮查詢不受影響 |
| `cwa[fast]` | 以 PyProj 計算距離，大量計算時快數十倍 | 改用 GeographicLib，結果相同 |
| `cwa[all]` | 以上全部 | |

## 授權碼

至[中央氣象署開放資料平臺](https://opendata.cwa.gov.tw/user/authkey)申請授權碼。SDK 會從環境變數 `CWA_API_KEY` 讀取授權碼，依作業系統設定：

```shell
# macOS、Linux
export CWA_API_KEY="授權碼"
```

```powershell
# Windows PowerShell
$env:CWA_API_KEY = "授權碼"
```

若授權碼來自設定檔或密鑰管理服務，不方便設成環境變數，可在建立用戶端時傳入。`cwa.weather.get()` 等模組函式只讀取環境變數，此時須改用用戶端：

```python
from cwa import CWA

with CWA(api_key="授權碼") as client:
    weather = client.weather.get("臺北市信義區")
```

用戶端的其他用途見[用戶端與快取](/advanced/clients)。

## 第一個查詢

`cwa.weather.get()` 一次取得一個鄉鎮的預報、目前天氣及警特報：

```python
import cwa

weather = cwa.weather.get("臺北市信義區")

if weather.current:
    print(weather.current.station.name, weather.current.temperature)
if weather.tomorrow:
    print(weather.tomorrow.temperature.max, weather.tomorrow.precipitation.max_probability)
for alert in weather.alerts:
    print(alert.title)
```

| 欄位 | 內容 | 可能為 `None` 的情況 |
| --- | --- | --- |
| `current` | 鄰近測站的最新觀測值 | 10 公里內沒有兩小時內的觀測值 |
| `today`、`tomorrow` | 今天及明天的預報 | 預報未涵蓋該日 |
| `alerts` | 影響此鄉鎮的警特報，可直接以 `for` 逐一取出 | 不會是 `None`，沒有警特報時為空 |

使用可能為 `None` 的欄位前，請先以 `if` 確認，如上例所示。每個欄位的完整說明見[綜合天氣](/guides/weather)。

## 下一步

| 想做的事 | 閱讀 |
| --- | --- |
| 用簡稱、常數或經緯度指定地點 | [指定地點](/guides/locations) |
| 取得一週預報，或查詢特定時刻的預報 | [預報](/guides/forecast) |
| 查詢鄰近測站的觀測值 | [觀測值及測站](/guides/observations) |
| 篩選警特報、判斷是否影響某地 | [警特報](/guides/alerts) |
| 查詢地震及颱風 | [地震](/guides/earthquakes)、[颱風](/guides/typhoons)、[海嘯](/guides/tsunamis) |
| 查詢海象、天文、健康氣象及氣候 | [海象](/guides/marine)、[天文](/guides/astronomy)、[健康氣象](/guides/health)、[氣候](/guides/climate) |
| 一次查詢多個地點並匯出表格 | [批次查詢與匯出](/advanced/batch) |
| 了解時間、單位及缺值的規則 | [資料說明](/reading) |