[Django]-Calling time consuming method inside django view without using task queue

4πŸ‘

βœ…

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.

0πŸ‘

Well, you can simply call a function directly in the view handler.

If this is a Celery task, you can call apply:

long_task.apply(args=[key])
πŸ‘€Andrew_Lvov

Leave a comment