# Django 從 Pusher 遷移：hibira 套件與 pusher-js

> 把 Django 應用從 Pusher Channels 移走：把 pusher 套件換成 hibira、改兩個呼叫名稱、在 pusher-js 加上 wsHost，不中斷地切換。

Source: https://hibira.io/zh-tw/topics/migrate-from-pusher-django
Updated: 2026-11-18

使用 Pusher Channels 的 Django 應用，伺服器端用 `pusher` 套件，模板裡用 pusher-js。搬到 Hibira 時，pusher-js 和頻道名稱都不變，但伺服器端套件要換掉：官方 `pusher` 套件只接受數字的 App ID，會拒絕 Hibira 的 App ID。`hibira` 套件提供同樣的功能，只是名稱稍有不同，所以只要改幾行。

## 哪些要改、哪些不用

| 應用的部分 | 要改嗎 | 怎麼做 |
| --- | --- | --- |
| `pusher.Pusher(...)` 用戶端 | 要 | 換成 `hibira.Client(...)` |
| `trigger()` 和 `trigger_batch()` 呼叫 | 不用 | 名稱和參數都一樣 |
| 授權 View 裡的 `authenticate()` | 要 | 改名為 `authenticate_channel()` |
| `validate_webhook()` | 要 | 改名為 `verify_webhook()` |
| 模板裡的 pusher-js | 要 | 加上 `wsHost` 和新的 Key |
| 允許的來源 | 新增 | 在應用登記你的網域；免費方案需要完整的來源網址 |

## 步驟 1：換掉用戶端

```bash
pip uninstall pusher
pip install hibira
```

接著建立一個用戶端，例如放在 `realtime.py`：

```python
import hibira

client = hibira.Client.from_env()  # HIBIRA_APP_ID, HIBIRA_APP_KEY, HIBIRA_APP_SECRET, HIBIRA_HOST

client.trigger("orders", "order-shipped", {"id": 1024})
client.trigger(["orders", "admin"], "order-shipped", {"id": 1024}, socket_id=socket_id)
```

在非同步 View 或 Django 非同步 ORM 裡，改用 `hibira.AsyncClient` 並 `await client.trigger(...)`。套件在 [PyPI](https://pypi.org/project/hibira/) 上，呼叫方式於 2026-11-18 確認。

## 步驟 2：改授權與 Webhook 的呼叫名稱

```python
from django.http import HttpResponseForbidden, JsonResponse
from django.views.decorators.http import require_POST

from .realtime import client


@require_POST
def pusher_auth(request):
    channel = request.POST["channel_name"]
    socket_id = request.POST["socket_id"]
    if not request.user.is_authenticated:
        return HttpResponseForbidden()
    if channel.startswith("presence-"):
        user = {"user_id": str(request.user.pk), "user_info": {"name": request.user.get_full_name()}}
        return JsonResponse(client.authenticate_channel(channel, socket_id, user))
    return JsonResponse(client.authenticate_channel(channel, socket_id))
```

處理 Webhook 時，把原始內容和兩個標頭傳給 `client.verify_webhook(key, signature, request.body)`。它會回傳解析後的內容；簽章不符時會拋出 `hibira.InvalidWebhook`。

## 步驟 3：把 pusher-js 指到新主機

```js
const pusher = new Pusher('{{ HIBIRA_APP_KEY }}', {
  cluster: 'mt1',
  wsHost: 'ws.hibira.io',
  wsPort: 443,
  wssPort: 443,
  forceTLS: true,
  enabledTransports: ['ws', 'wss'],
  channelAuthorization: {
    endpoint: '/pusher/auth/',
    transport: 'ajax',
    headers: { 'X-CSRFToken': '{{ csrf_token }}' },
  },
});
```

要不中斷地切換，就把舊的 `pusher.Pusher` 用戶端多留一兩天，每個事件都從兩邊發佈，等 Pusher 沒有連線後再移除。

## 或者不寫 JavaScript

如果你的頁面在伺服器端渲染，[django-hibira](https://hibira.io/zh-tw/guides/django) 套件只要一個裝飾器就能讓列表即時更新：儲存的資料列會渲染好並推送到每個開著的頁面，不需要 Django Channels、ASGI 伺服器或 Redis。單獨使用 `hibira` 套件的方式，包括 FastAPI 和 Flask，請看 [Python 指南](https://hibira.io/zh-tw/guides/python)。

## 常見問題

### 為什麼不能繼續用官方的 pusher 套件？

它會檢查 App ID 是不是數字，不是就拒絕。Hibira 的 App ID 不是數字，所以套件在送出前就會報錯。`hibira` 套件使用同樣的 HTTP API，但沒有這個檢查。

### 頻道名稱和事件要改嗎？

不用。頻道名稱、事件名稱、內容和 Presence 成員資料都不變，瀏覽器裡的 pusher-js 換了主機也照樣能用。

### 可以在 Celery 任務裡用嗎？

可以。發佈就是一個 HTTP 請求，所以在 View、Signal、管理指令和 Celery 任務裡都能用。用 django-hibira 時，廣播會等交易提交後才送出。

### 授權 View 還受 CSRF 保護嗎？

只要保留 Django 的 CSRF 中介軟體就是。像上面那樣在 `channelAuthorization.headers` 傳送 token；或者，如果那個 View 自己會檢查 Session，就只豁免那一個 View。
