0

I try to create a chatbot. Every user can create an account and authenticate using Tokens. This is done in Django Rest Framework. After creating an account every user has own ID in PostgreSQL database. However chat is based on a websockets. I wonder how can I set session in websockets because I need to know which user sends message. So it seems to me that the best solution would be to have the same ID using both DRF and websockets. Or maybe am I wrong? I try in the way shown below but without positive results.

@channel_session_user_from_http
def msg_consumer(message):
    text = message.content.get('text')
    Message.objects.create(
        message=text,
    )
    Group("chat").send({'text': text})

@channel_session_user_from_http
def ws_connect(message):
    # Accept the connection
    message.reply_channel.send({"accept": True})
    # Add to the chat group
    Group("chat").add(message.reply_channel)

    message.reply_channel.send({
        "text": json.dumps({
            'message': 'Welcome'
        })
    })

# @enforce_ordering
@channel_session_user_from_http
def ws_receive(message):

    message.reply_channel.send({"accept": True})
    print("Backend received message: " + message.content['text'])
    Message.objects.create(
        message = message.content['text'],
    )

    Channel("chat").send({
        "text": json.dumps({
             'message': 'Can we start?'
         })
    })

@channel_session_user_from_http
def ws_disconnect(message):
    Group("chat").discard(message.reply_channel)
  • Possible lead: https://stackoverflow.com/questions/42039031/session-authentication-with-django-channels – SeedyROM Sep 25 '17 at 05:29
  • @SeedyROM Is it possible to have the same user ID using both DRF and websockets? –  Sep 25 '17 at 16:11

0 Answers0