Whenever there is time consuming logic in django view I run that as background task using celery and return response.
from my_app.task import long_task
import json
def my_view(request):
body = request.body
body = json.loads(body)
key = body['key']
long_task.delay(key) # This will run in background
return JsonResponse({'message': 'request submitted'})
Is there any way to achieve this behaviour to call long_task method without any background task queue like celery etc so I can quickly send response to user?
I guess there would be way to do this using operating system and python features.
If you're using Python >= 3.5 you can try asyncio in order to run a background task:
from my_app.task import long_task
import json
import asyncio
loop = asyncio.get_event_loop()
def my_view(request):
body = request.body
body = json.loads(body)
key = body['key']
arguments = [key]
loop.run_in_executor(None, long_task, arguments)
return JsonResponse({'message': 'request submitted'})
More info can be found here
If you want to use asyncio on lower versions of Python (2.7 for example) you should be able to do that but keep in mind that is not included in standard core library and you need to install it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With