In this example code below, if I use the Group from djando.contrib.auth.models, within the same method that created the “listener”, to create a new group, the “listener” works, but I just need to place the call Group.save() in another method that the “callback” function does not fire.
I tried using the method loop that creates the listener, but it doesn’t work.
import logging
from asgiref.sync import async_to_sync, sync_to_async
from django.dispatch import receiver
from django.contrib.auth.models import Group, Permission
import asyncio
import traceback
class ListenerDataBase():
async def create_listener(self, methodRESTSignal, ModelDataBase, async_callback):
'''
O parâmetro async_callback precisa ser uma função assíncrona com 3 parâmetros
'''
@receiver(methodRESTSignal, sender=ModelDataBase)
def trigger_async_callback(sender, instance, **kwargs):
print(f'trigguer_async_call disparada')
sync_callback = async_to_sync(async_callback)(sender, instance, **kwargs)
sync_callback()
'''if Group.save(...) is called here, trigger_async_callback is triggered, but if it is called in another method, it is not.
'''
async def create_group(self, group_name):
def wrap_sync(self, group_name):
try:
group = Group(name=group_name)
group.save()
except Exception as e:
logger.error(f'Error inside wrap_sync -> {traceback.format_exc()}')
async_create_group = sync_to_async(wrap_sync) # (group_name)
await async_create_group(self, group_name)