1 Star 0 Fork 1

hllyzms / django websocket demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

环境

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 &

空文件

简介

django channels 示例 展开 收起
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hllyzms_hllyzms/django-websocket-demo.git
git@gitee.com:hllyzms_hllyzms/django-websocket-demo.git
hllyzms_hllyzms
django-websocket-demo
django websocket demo
master

搜索帮助