pythondjangocelerypython-3.6django-3.0

How to execute a value from coroutine object in sync celery task?


I have 2 functions - async, which returns the coroutine object with int value, and the sync function, whic is the @shared_task, where the variable must stores the value from the async function (int)

My async function, that returns the coroutine with int in it:

async def club_count(club_id):
    return get_number_of_club(club_id).get_clients_in_club_count(club_id)

There is my sync function that shared_task with making a record into the Django admin Problem with the variable "club_load" that must stores the value from my async function But when I try to run the celery, I get the error of operation between coroutine and int in "procent_club_load"

@shared_task
def get_club_load():

    all_clubs = Club.objects.all()
    
    for club in all_clubs:
        
        if club.monitoring_club_load == True:

            club_load = club_load_json(club.id)
            club_capacity = club.club_load
            procent_club_load = None
            
            if club_capacity:
                procent_club_load = int((club_load / club_capacity)*100)
                        
            club_load_record = ClubLoadModel(
                club_id = club.id,
                created_at = timezone.now(),
                weekday = timezone.localtime().weekday() + 1,
                club_load = club_load,  
                procent_club_load = procent_club_load
            )
            club_load_record.save()
        else:
            pass

What the solution that I can execute the value from coroutine object into the variable of sync function that a shared task?

I'm trying to store a value from my async function in the variable of sync celery task

Problem is that celery couldn't make operations with async functions The second problem, that I'm trying to make a periodic task with that shared task, but receive the error with coroutine object in sync function


Solution

  • You can use asgiref.sync.async_to_sync:

    You can run:

    from asgiref.sync import async_to_sync
    
    result = async_to_sync(club_count)()