功能实现
一、安装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__