4

Suppose that I have a Django view and that I would like to call two APIs at the same time.

def djangoview(request):
    #Call API 1
    #Call API 2 before API Call 1 finishes
    #Wait for both calls to finish
    output = [Apicall1.response, Apicall2.response]
    return(HttpResponse)

I've been trying to use multiprocessing library and pools without success. I'm using Apache2 and Wsgi, how can I make this work? Maybe making the call on a different thread?

Juanvulcano
  • 1,354
  • 3
  • 26
  • 44
  • This might help: https://stackoverflow.com/questions/1352678/is-there-any-way-to-make-an-asynchronous-function-call-from-python-django – xyres Jun 21 '17 at 18:01
  • 1
    Basically, you'll need to use an async framework for this and run it as a separate process. There are many async libraries available for Python: aiohttp, celery, tornado, twisted, and many more. – xyres Jun 21 '17 at 18:03
  • Thanks @xyres I just tried with Asyncio, think that my solution is fine? https://stackoverflow.com/questions/44667242/python-asyncio-in-django-view/44683173#44683173 – Juanvulcano Jun 21 '17 at 18:16
  • I think that would not make api calls asynchronously. Given that Django is a blocking framework, and if you run asyncio in the same process as Django, it will also block. You're not getting any benefits this way. But I might be wrong. Did you try it? Does it work as expected? – xyres Jun 21 '17 at 20:22
  • @xyres Those were my initial thoughts at the beginning, but it certainly works. Was looking to have a more experienced developer explain the why – Juanvulcano Jun 22 '17 at 02:44

0 Answers0