django框架channels实现私信功能

功能实现

一、安装channels

1. 通过pip在终端安装

pip install -U channels

2. 将channels加进setting

# settings.py

INSTALLED_APPS = [
    'channels',
]

3. 配置项目默认路由

# routing.py
from channels.routing import ProtocolTypeRouter

application = ProtocolTypeRouter({
    # Empty for now (http->django views is added by default)
})

二、创建私信APP

python manage.py startapp chat

把chat加进安装的app配置

# settings.py

INSTALLED_APPS = [
    'chat.apps.ChatConfig',
    'channels',
]

因为chat目录下有apps.py文件可以识别

# chat/apps.py
from django.apps import AppConfig

class ChatConfig(AppConfig):
    name = 'chat'

部分问题

运行时报错 raise SynchronousOnlyOperation(message) You cannot call this from an async context - use a thread or sync_to_async.

HTTP GET /chat/1-2/ 200 [0.00, 127.0.0.1:62738]
WebSocket HANDSHAKING /ws/chat/1-2/ [127.0.0.1:62739]
WebSocket CONNECT /ws/chat/1-2/ [127.0.0.1:62739]
Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.
  File "D:\SOFTWARE\Python\Python36\lib\site-packages\channels\sessions.py", line 183, in __call__
    return await self.inner(receive, self.send)
  File "D:\SOFTWARE\Python\Python36\lib\site-packages\channels\middleware.py", line 41, in coroutine_call
    await inner_instance(receive, send)
  File "D:\SOFTWARE\Python\Python36\lib\site-packages\channels\consumer.py", line 59, in __call__
    [receive, self.channel_receive], self.dispatch
  File "D:\SOFTWARE\Python\Python36\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch
    await dispatch(result)
  File "D:\SOFTWARE\Python\Python36\lib\site-packages\channels\consumer.py", line 73, in dispatch
    await handler(message)
  File "D:\SOFTWARE\Python\Python36\lib\site-packages\channels\generic\websocket.py", line 175, in websocket_connect
    await self.connect()
  File "D:\WORKPLACE\ZhiFou\chat\consumers.py", line 51, in connect
    cursor = connection.cursor ()
  File "D:\SOFTWARE\Python\Python36\lib\site-packages\django\utils\asyncio.py", line 22, in inner
    raise SynchronousOnlyOperation(message)
  You cannot call this from an async context - use a thread or sync_to_async.
WebSocket DISCONNECT /ws/chat/1-2/ [127.0.0.1:62739]

在这里插入图片描述
用django2.2.7不会错,报错是用django3.0

查看django版本的方法之一:
【python cosole】

import django
django.__version__

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值