Django休息框架&外部api

时间:2018-01-25 04:04:07

标签: django django-rest-framework

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

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

或者您还有其他好主意吗?

感谢。

2 个答案:

答案 0 :(得分:7)

我认为最好创建一个自己的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)

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

答案 1 :(得分:0)

无论您想要实现什么,此代码都无效。

首先,?P<name>构造只是为组赋予符号名称的一种方式。并且它不接受字符'。','/'和')'。所以正确的名称就像?P<consumer_id>

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

我建议你先学习how regular expressions work in Python