Django Rest Framework和外部API

3

我想从外部API (https://example.com/consumers) 获取数据。我可以像这样构建我的urls.py吗?

url(r'^(?P<test.com/consumers)>[0-9]+)$/', views.get, name="get"),

或者你还有其他好的想法吗?

谢谢。

2个回答

12

我认为最好创建自己的URL端点,将其映射到视图,由视图发出请求外部API。

# urls.py
url(r'^external-api/$', external_api_view)

# views.py
import requests
import time
from rest_framework import status
from rest_framework.response import Response

MAX_RETRIES = 5  # Arbitrary number of times we want to try

def external_api_view(request):
    if request.method == "GET":
        attempt_num = 0  # keep track of how many times we've retried
        while attempt_num < MAX_RETRIES:
            r = requests.get("https://example.com/consumers", timeout=10)
            if r.status_code == 200:
                data = r.json()
                return Response(data, status=status.HTTP_200_OK)
            else:
                attempt_num += 1
                # You can probably use a logger to log the error here
                time.sleep(5)  # Wait for 5 seconds before re-trying
        return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

只是一个例子。你也可以将其作为基于类的视图来完成。


你应该为外部API调用设置超时限制,否则你的视图可能会阻塞其他请求数分钟。 - Toan Nguyen
感谢@ToanNguyen指出这一点,我添加了超时并包括最大重试次数。 - Thomas Jiang
谢谢@ThomasJiang,我会按照那样尝试,并在之后实现基于类的视图。谢谢大家。 - Kebson

0

无论你想要实现什么,这段代码都不会起作用。

首先,?P<name> 结构只是一种给组命名的方式。它不接受字符 '.'、'/' 和 ')'。因此正确的名称应该是类似于 ?P<consumer_id>

其次,即使你在正则表达式中纠正了错误(例如:r'^(?P<consumer_id>[0-9]+$)/'),它也只会匹配任何形如 YOURDOMAIN.COM/<integer_number>/ 的 URL。

我建议你先学习Python 正则表达式的工作原理


在哪里输入用户名和密码以连接外部API? - richa verma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接