Alok
Alok

Reputation: 10624

Calling time consuming method inside django view without using task queue

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.

Upvotes: 3

Views: 518

Answers (2)

Andrew_Lvov
Andrew_Lvov

Reputation: 4668

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])

Upvotes: 0

Moldovan Daniel
Moldovan Daniel

Reputation: 1581

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.

Upvotes: 4

Related Questions