跳转至

action

action在Channel类的使用上展开,它将使用Channel的变得更像是一个FastAPI的子应用一样,虽然有些区别,没有get、post的请求方式,但是有action来接收对应动作

使用Channel也同时满足了像函数或是类的形式来编写逻辑,就像CBVFBV一样,这里是有一点模仿DRF的痕迹在里面的,这里给我们的案例使用这两个名字来代替这两种写法

from fastapi import FastAPI, WebSocket

from fastapi_channels import add_channel
from fastapi_channels.channels import Channel
from fastapi_channels.decorators import action
from fastapi_channels.throttling import limiter

app = FastAPI()
add_channel(
    app,
    add_exception_handlers=True,
    url="memory://",
    limiter_url="redis://localhost:6379",
)


class MyChannel(Channel):
    @limiter(times=2, seconds=60)
    @action()
    async def message(self, websocket: WebSocket, channel: str, data: dict, **kwargs):
        return self.broadcast_to_channel(channel=channel, message=data.get("message"))


my_channel = MyChannel()


@app.websocket("/")
async def ws_endpoint(websocket: WebSocket):
    return await my_channel.connect(websocket)
from fastapi import FastAPI, WebSocket

from fastapi_channels import add_channel
from fastapi_channels.channels import Channel
from fastapi_channels.throttling import limiter

app = FastAPI()
add_channel(
    app,
    add_exception_handlers=True,
    url="memory://",
    limiter_url="redis://localhost:6379",
)

my_channel = Channel()


@limiter(times=2, seconds=60)
@my_channel.action()
async def message(websocket: WebSocket, channel: str, data: dict, **kwargs):
    return my_channel.broadcast_to_channel(channel=channel, message=data.get("message"))


@app.websocket("/")
async def ws_endpoint(websocket: WebSocket):
    return await my_channel.connect(websocket)

FBV更贴近fastapi的一般的使用形式,CBV更新DRF的CBV但是我们没有模型处理,只能说有些神韵罢了。

如上在不同形式下实现action的注册的方式是不一样的,CBV需要从fastapi_channels.decorators导入 action 装饰器 而FBV只需要调用实例化后的Channel的action装饰器实例方法,像fastapi那样

解码器

指定receiver中客户端发送的message被处理成dict()的过程

xxx

编码器

指定reply的形式

xoo

权限

评论