代码拉取完成,页面将自动刷新
channels==2.1.5 channels-redis==2.3.2 daphne==2.2.4 Django==1.11.6 django-filter==2.0.0 django-redis==4.7.0 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 redis==3.2.1
channels_demo\app\ws_authentication.py
这是我自己写的认证wbsocket的类
class QueryAuthMiddleware:
def __init__(self, inner):
self.inner = inner
def __call__(self, scope):
close_old_connections()
token = scope["query_string"]
token = token.decode("utf-8")
user = AnonymousUser()
if token:
user = authenticate(token)
return self.inner(dict(scope, user=user))
def authenticate(jwt_value):
try:
payload = jwt_decode_handler(jwt_value)
except Exception:
user = AnonymousUser()
return user
user = authenticate_credentials(payload)
return user
def authenticate_credentials(payload):
username = payload.get('username')
try:
User = get_user_model()
user = User.objects.get(username=username)
except Exception:
user = AnonymousUser()
return user
class ServiceConsumer(AsyncWebsocketConsumer):
async def connect(self, *args, **kwargs):
print('***********open************')
user = self.scope["user"]
user_id = ""
# todo 如果用户没有登陆 可以直接关闭连接
if not user.id:
await self.close()
import time
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "channels_demo.settings")
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
channel_layer = get_channel_layer()
# todo channel_name 是保存时 self.room_group_name 的名字
def send_channel_msg(channel_name, msg):
async_to_sync(channel_layer.group_send)(channel_name,{'type': 'user_message','text': msg})
def screen_channel_msg(channel_name, msg):
async_to_sync(channel_layer.group_send)(channel_name,{'type': 'send_message','text': msg})
if __name__ == '__main__':
send_channel_msg("user_5", {"type": "affiche","info":{
"id": 1,
"classify": "公告",
"content": "上班信息",
"create_time": "2019-05-16"
}})
screen_channel_msg("role_1",{"text":"update"})
print(time.time())
daphne -b 0.0.0.0 -p 8018 channels_demo.asgi:application -v2
nohup daphne -b 0.0.0.0 -p 8018 channels_demo.asgi:application -v2 >/dev/null 2>&1 &
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。