DJANGO : how to run API-request in the background so my users experience no delay?

Viewed 472

I've a script that get's data from an API. The API needs some time to calculate and return the values.

This means that my my user experiences a lot of delay (9sec) to go to the next page, until the API has returned the values.

Is there a way to run the script with the API in the background? So the user can continue their experience without any hinder ? (I wonder if async functions can help?)

the code I use to run the API:

import requests            
body = {...}
headers = {
            'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
            'Authorization': '...',
            'Content-Type': 'application/json; charset=utf-8'
        }

        call = requests.post('https://api....', json=body, headers=headers)

        print(call.status_code, call.reason)
        print(call.text)

UPDATE:

For those that are new to celery (like me) a quick update on the things I did to get it working.

  1. Get a Redis Server up and running : This link explains how to do it. It's from Digital Ocean, but I used a server on Hetzner and it worked perfectly fine.
  2. ... I'll update the rest as I proceed
1 Answers

The classical way is to send any long-running tasks to celery worker

Related