Srikanth
Srikanth

Reputation: 47

From Django project achieve an asynchronous request to external API?

In my Django project, I have to implement an asynchronous HTTP request to the external API and get the result. I found that by using Django channels and celery we can do. There is a package in the tornado simpleAsynchronousHttp package is there anything in Django. please, can anyone suggest which is the better way to achieve asynchronous HTTP call to external API and get data in Django?

Upvotes: 1

Views: 1143

Answers (1)

anurag
anurag

Reputation: 2246

Requests is a python package, which makes it pretty easy to do HTTP requests. In order to do it asynchronously, you can leverage Celery. For celery setup, you can follow the docs. You can use redis as a broker.

Create a task inside your app.

# proj/tasks.py
from __future__ import absolute_import, unicode_literals
from .celery import app
import requests # https://github.com/requests/requests


@app.task
def call_api():
    r = requests.get('https://api.github.com/events')

In the file wherever you want to call the function, e.g. in your views

# proj/views.py
from tasks import call_api
call_api.delay()

Upvotes: 1

Related Questions