[python]使用channels库时遇到的一些问题

来源:互联网 发布:淘宝号不能登陆怎么办 编辑:程序博客网 时间:2024/06/09 00:31

1. url注册 

在使用url注册前, 需要在project的settings.py文件中INSTALLED_APPS 中添加"channels"项, 同时在下面添加, 其中appname根据自己项目实际的appname填写

CHANNEL_LAYERS = {    "default": {        "BACKEND": "asgiref.inmemory.ChannelLayer",        "ROUTING": "appname.routing.routing",    },}

此时channels 使用routing.py 作为配置文件进行注册url注册分发, 主要为检测routing, 然后routing中配置了include channel_routing. 这个path是用于ws连接时过滤用的, 与django的url一样, 支持同样的正则表达式校验

from channels.routing import route, includefrom .Consumer import ws_connect, ws_message, ws_disconnectfrom . import Consumerchannel_routing = [    route("websocket.connect", ws_connect),    route("websocket.receive", ws_message),    route("websocket.disconnect", ws_disconnect),   ]routing = [    # You can use a string import path asthe first argument as well.    include(channel_routing, path=r"^/websocket_log/$"),    #include(http_routing),]

2.数据发送问题

message.reply_channel.send({"text":"hello world"}) 如果没有加上immediately=True参数的话, 在多线程情况下会默认主线程的消息延迟发送

3.group 和 channel_session

Group相当于一个全局map, 里面记录的是{"name":channel list}

channel_session与http的session类似


原创粉丝点击