2

I was asking myself if there is a simple way of defining a callback method when defining a DRF endpoint.

For example, let's say I want to reproduce this workflow:

  • app1 sends data to app2, calling a DRF endpoint living in app2
  • app2 immediately sends the HTTP 200/201 response to app1
  • app2 makes a "heavy" work then.

Of course, I'm aware there are cleaner alternative:

  • I know heavy work loads should live in a Celery task, or Django channel
  • I know it would make more sense in my case that app2 is the one that makes the request, and app1 sends the response.

I found ideas here but it's very related to Django itself, not Django Rest Framework.

David Dahan
  • 10,576
  • 11
  • 64
  • 137
  • What's the question? You already are aware that celery type of workers would be needed for async calls. – Jawad Dec 09 '19 at 16:01
  • Are you aware of Django Channels? https://channels.readthedocs.io/en/latest/introduction.html – schillingt Dec 09 '19 at 16:06
  • Here's an alternative to Celery: https://github.com/Koed00/django-q – Airith Dec 09 '19 at 16:08
  • Yes I know all of these solutions. But the purpose of my question is *NOT* to find an additional tool to fulfill my need. I just want to know how to do it without any tool, even if it's not elegant. Please take a look at the link I provided, I'm looking for a similar solution, but DRF related. – David Dahan Dec 09 '19 at 16:11

1 Answers1

1

Use Celery for async tasks. Anyway, you can launch a thread in a Django view and run async functions:

import logging
import threading
from time import sleep
from django.shortcuts import render

def print_async():
    for i in range(10):
        print(i, '...')
        sleep(1)

def your_view(request, template_name="home.html"):
    # ...
    t = threading.Thread(target=print_async)
    t.setDaemon(True)
    t.start()
    # ...
    return render(request, template_name, {})
Dos
  • 2,250
  • 1
  • 29
  • 39