Django Channels Group / channel_session如何运作?

时间:2016-06-21 06:01:17

标签: django-channels

似乎Group和channel_session可以在多个消息会话和消费者中持续存在。渠道如何实现这一目标?

@channel_session_user_from_http
def ws_connect(message):
    # Add them to the right group
    message.channel_session['room'] = 'room name'
    Group("chat-%s" % message.user.username[0]).add(message.reply_channel)

@channel_session_user
def ws_disconnect(message):
    if 'room' in message.channel_session:
        print('room====', message.channel_session['room'])
    Group("chat-%s" % message.user.username[0]).discard(message.reply_channel)

我想设置一个长的现有对象,就像每个消费者都可以访问的全局对象一样。

1 个答案:

答案 0 :(得分:0)

您可以使用@channel_session(或@channel_session_user)装饰器来实现此目的。确保您的对象是可序列化的,然后将其添加到用户的频道会话中,如下所示:

@channel_session_user_from_http
def ws_connect(message):
    message.session.myobject = {'test': True}

@channel_session_user
def ws_connect(message):
    print(message.session.myobject)   # should output {'test': True}

或者,只需使用您的数据库或redis来保存像Django中通常那样的东西:

@channel_session_user_from_http
def ws_connect(message):
    redis_conn.set('my-persisted-key', "{'test': True}")

@channel_session_user
def ws_connect(message):
    print(redis_conn.get('my-persisted-key'))  # should output "{'test': True}"