[Python] How to use transaction with "async" functions in Django?

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    When async def call_test(request): called async def test(): as shown below (I use Django==3.1.7):

    async def test():
    for _ in range(0, 3):
    print("Test")

    async def call_test(request):

    await test() # Here

    return HttpResponse("Call_test")


    There was no error displaying the proper result below on console:

    Test
    Test
    Test


    But, when I put @transaction.atomic() on async def test(): as shown below:

    @transaction.atomic # Here
    async def test():
    for _ in range(0, 3):
    print("Test")

    # ...


    The error below occurred:


    django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
    ​

    So, I put @sync_to_async under @transaction.atomic() as shown below:

    @transaction.atomic
    @sync_to_async # Here
    async def test():
    for _ in range(0, 3):
    print("Test")

    # ...


    But, the same error below occurred:


    django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
    ​

    So, I put @sync_to_async on @transaction.atomic() as shown below:

    @sync_to_async # Here
    @transaction.atomic
    async def test():
    for _ in range(0, 3):
    print("Test")

    # ...


    But, other error below occurred:


    RuntimeWarning: coroutine 'test' was never awaited handle = None # Needed to break cycles when an exception occurs. RuntimeWarning: Enable tracemalloc to get the object allocation traceback
    ​

    So, how can I use transaction with async functions in Django?

    Continue reading...

Compartilhe esta Página