Asynchronous signals with asyncio

前端 未结 1 1678

My model post processing is using the post_save signal:

from django.core.signals import request_finished
from django.dispatch import receiver
from m         


        
相关标签:
1条回答
  • 2021-02-09 11:33

    You get no any benefit in your case:

    @receiver(post_save, sender=MyModel)
    def my_callback(sender, **kwargs):
        this_takes_forever(sender)
    

    is equal to

    @receiver(post_save, sender=MyModel)
    def my_callback(sender, **kwargs):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(this_takes_forever(sender))
        loop.close()
    

    in terms of execution time. loop.run_until_complete waits for end of this_takes_forever(sender) coroutine call, so you get synchronous call in second case as well as in former one.

    About AssertionError: you start Django app in multithreaded mode, but asyncio makes default event loop for main thread only -- you should to register new loop for every user-created thread where you need to call asyncio code.

    But, say again, asyncio cannot solve your particular problem, it just incompatible with Django.

    The standard way for Django is to defer long-running code into celery task (see http://www.celeryproject.org/)

    0 讨论(0)
提交回复
热议问题