V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
endpain
V2EX  ›  Python

django 使用 channels 搭建在线客服疑惑

  •  
  •   endpain · 2020-05-14 23:43:58 +08:00 · 1577 次点击
    这是一个创建于 1436 天前的主题,其中的信息可能已经有所发展或是发生改变。

    版本: python == 3.8.1 Django 3.0.4
    channels 2.4.0
    channels-redis 2.4.2
    疑问如下,因为百度搜索的答案实在是一言难尽,都是千篇一律的一样,根据我的个人理解,和查看官网,在 channels 里面包括官方教程都是着重再讲多人聊天和群组聊天( group ),我想实现的是通过 layim 一对一聊天

    整体都能跑通,但是不知道为什么,a 用户发给 b 用户的消息,b 是收不到的,这块我实在是不明白以下几个问题,希望有懂的大神可以指点一下

    1 、a 用户发给 b 用户,我如何能给 b 用户去进行推送,

                async_to_sync(self.channel_layer.send)(
                    to_user_id,
                    {
                        'type': 'chat_messages',  # 调用的发送方法
                        'event':data_json
    
                    }
                )
    

    上面的代码貌似没生效,b 用户是没有收到的

    2 、channels 如何能获取当前有几个人在连接,他们存储在 redis 的 channel_name 如何获取?

    附上我的代码,感谢~

    from asgiref.sync import async_to_sync
    from channels.layers import get_channel_layer
    from channels.generic.websocket import WebsocketConsumer
    from channels.exceptions import *
    from channels.db import database_sync_to_async
    from rest_framework_jwt.authentication import jwt_decode_handler
    import json
    import redis
    import time
    from chat import models
    
    pool = redis.ConnectionPool(
        host='localhost',
        port=6379,
        max_connections=10,
        decode_responses=True
    )
    conn = redis.Redis(connection_pool=pool, decode_responses=True)
    
    
    class ChatConsumer(WebsocketConsumer):
        chats = {}
    
        def connect(self):
            try:
                jwt = self.scope['query_string'].decode() #获取 jwt
                if not jwt:
                    # 请求存在问题
                    raise DenyConnection("jwt 信息错误")
                payload = jwt_decode_handler(jwt)
            except:
                print("jwt 信息错误")
    
            print(payload)
            self.user_id = str(payload['user_id'])
    
            async_to_sync(self.channel_layer.group_add)(
                self.user_id,
                self.channel_name
            )
            # ChatConsumer.chats[user_id] = {'self':self,'last_time':int(time.time())}
            self.accept()
    
        def disconnect(self, close_code):
    
            async_to_sync(self.channel_layer.group_discard)(
                self.user_id,
                self.channel_name
            )
    
            ChatConsumer.chats[self.group_name].remove(self)
    
            self.close()
    
    
        def receive(self, text_data):
            data_json = json.loads(text_data)
            type = data_json.get('type') # 类型
    
            if type == 'chatMessage':
                # 发送消息
                mine_user_id = data_json.get('data').get('mine').get('id') # 发送者 id
                to_user_id = data_json.get('data').get('to').get('id') # 接受者 id
                message = data_json.get('data').get('mine').get('content') #发送内容
    
                # 接受成功消息,返回结果
                self.send(text_data=json.dumps({
                    'server_socket_type': 'MessageReceivedSuccessfully',
                    'result': True,
                    'time': int(time.time()),
                }))
    
                async_to_sync(self.channel_layer.send)(
                    to_user_id,
                    {
                        'type': 'chat_messages',  # 调用的发送方法
                        'event':data_json
    
                    }
                )
    
    
    
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   941 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:02 · PVG 04:02 · LAX 13:02 · JFK 16:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.