我的模型后处理使用post_save
信号:
from django.core.signals import request_finished
from django.dispatch import receiver
from models import MyModel
from pipeline import this_takes_forever
@receiver(post_save, sender=MyModel)
def my_callback(sender, **kwargs):
this_takes_forever(sender)
该this_takes_forever
例程执行 IO,因此我想推迟它以避免过多阻塞请求。
我认为这是新的asyncio模块的一个很好的用例。但我很难完全理解整个过程。
我想我应该能够像这样调整信号接收器:
@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()
Providedthis_takes_forever
也适用于协程。
@coroutine
def this_takes_forever(instance):
# do something with instance
return instance
这听起来太神奇了。事实上,它停止了AssertionError
:
AssertionError at /new/
There is no current event loop in thread 'Thread-1'.
我不知道在这种情况下我应该从哪里开始循环。有人尝试过这样的事情吗?