# Django 从 Pusher 迁移：hibira 包与 pusher-js

> 把 Django 应用从 Pusher Channels 迁走：把 pusher 包换成 hibira、改两个调用名称、在 pusher-js 加上 wsHost，不中断地切换。

Source: https://hibira.io/zh-cn/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-cn/guides/django) 包只要一个装饰器就能让列表实时更新：保存的数据行会渲染好并推送到每个打开的页面，不需要 Django Channels、ASGI 服务器或 Redis。单独使用 `hibira` 包的方式，包括 FastAPI 和 Flask，请看 [Python 指南](https://hibira.io/zh-cn/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。
