How To Call Asynchronous Function In Django?
The following doesn't execute foo and gives RuntimeWarning: coroutine 'foo' was never awaited # urls.py async def foo(data): # process data ... @api_view(['POST']) def endpoi
Solution 1:
Django is an synchronous language but it supports Async behavior. Sharing the code snippet which may help.
import asyncio
from channels.db import database_sync_to_async
defget_details(tag):
response = another_sync_function()
# Creating another thread to execute function
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async_result = loop.run_until_complete(remove_tags(response, tag))
loop.close()
# Async function asyncdefremove_tags(response, tag_id):
// do something here
# calling another function only for executing database queriesawait tag_query(response, tag_id)
@database_sync_to_asyncdeftag_query(response, tag_id):
Mymodel.objects.get(all_tag_id=tag_id).delete()
This way i called async function in synchronous function.
Reference for database sync to async decorator
Solution 2:
Found a way to do it.
Create another file bar.py
in the same directory as urls.py
.
# bar.pydeffoo(data):
// process data
# urls.py
from multiprocessing import Process
from .bar import foo
@api_view(['POST'])
def endpoint(request):
data = request.data.get('data')
p = Process(target=foo, args=(data,))
p.start()
return Response({})
Solution 3:
You can't await foo in this context. Seeing that Django is mainly a synchronous library, it doesn't interact well with asynchronous code. The best advice I can give it to try avoid using an asynchronous function here, or perhaps use another method of concurrency (ie threading or multiprocessing).
Note: there is a great answer given about Django's synchronous nature that can be found here: Django is synchronous or asynchronous?.
Post a Comment for "How To Call Asynchronous Function In Django?"