python - 从Django项目实现对外部API的异步请求?

标签 python django asynchronous

在我的 Django 项目中,我必须实现对外部 API 的异步 HTTP 请求并获取结果。我发现通过使用 Django channel 和 celery 我们可以做到。 Django中的tornado simpleAsynchronousHttp包中有一个包吗?请问,谁能建议哪种方法可以更好地实现对外部 API 的异步 HTTP 调用并在 Django 中获取数据?

最佳答案

Requests 是一个 python 包,它使得执行 HTTP 请求变得非常容易。为了异步执行此操作,您可以利用 Celery 。对于celery设置,您可以按照 docs 。您可以使用redis作为经纪人。

在您的应用内创建一个任务。

# 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')

在文件中您想要调用该函数的任何位置,例如在你看来

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

关于python - 从Django项目实现对外部API的异步请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52160232/

相关文章:

python - 在 python 中使用 gio 访问 samba 共享

javascript - 使用 javascript/nodejs 分割 url 并存储在数组、对象或字符串中

Python/Pandas 根据列中不出现值而删除列

Python/OpenCV - 从航拍图像中检测篮球场线

python - Python中有sqlite3.connect的独占创建模式吗? (仅当文件尚不存在时才创建)

python - 在 Django 2 中使用 URLPathVersioning 处理版本控制

Django 抽象模型 + DB 迁移 : tests throw "cannot ALTER TABLE because it has pending trigger events"

Python + Django 页面重定向

C++ boost asio |同步写入到异步读取 |无法在第二次读取中接收到正确的数据

c - 与 aio_context 关联的资源