V
V
vikholodov2018-05-23 09:55:23
Django
vikholodov, 2018-05-23 09:55:23

Why doesn't post_save work in an asynchronous function?

Hello!
There is a function with the @asyncio.coroutine decorator, a Message model object is created in it, the entry is saved in the database, but there is no post_save signal, as well as pre_save, at least it cannot be caught. When adding an object through the shell or admin panel, there is no such problem, everything works.
What needs to be done to be able to catch the signal in this case?

@asyncio.coroutine
def new_messages_handler(stream):
  """
  Saves a new chat message to db and distributes msg to connected users
  """
  # TODO: handle no user found exception
  while True:
    packet = yield from stream.get()
    session_id = packet.get('session_key')
    msg = packet.get('message')
    username_opponent = packet.get('username')
    if session_id and msg and username_opponent:
      user_owner = get_user_from_session(session_id)
      if user_owner:
        user_opponent = get_user_model().objects.get(username=username_opponent)
        dialog = get_dialogs_with_user(user_owner, user_opponent, packet.get('id'))
        if len(dialog) > 0:
          # Save the message
          
          msg = models.Message.objects.create(
            dialog=dialog[0],
            sender=user_owner,
            text=packet['message'],
            is_system=False,
            read=False
          )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2018-05-23
@vikholodov

you made an interesting attempt :) I couldn’t even guess about this - mix django and asyncio
if you want to mix them, then I think there is only one way out - work through Celery
or break the logic so that you don’t need to transfer tasks

S
Sergey Gornostaev, 2018-05-23
@sergey-gornostaev

Django is designed to be synchronous and single-threaded, it itself cannot be properly parallelized, and you cannot really use asynchronous code in its workers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question