It seems Group and channel_session can persist across multiple message sessions and consumers. How does Channels achieve that?
@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)
I would like to setup a long existing object, much like a global object which is accessible by every consumer.
You can use @channel_session
(or the @channel_session_user
) decorator to achieve this. Make sure your object is serializable, then just add it to the user's channel session like this:
@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}
Alternatively, just use your DB or redis to persist things like you would normally in 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}"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments