Django rest框架&外部API [英] Django rest framework & external api

查看:49
本文介绍了Django rest框架&外部API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i wanna get my data from an external API (https://example.com/consumers). Can I build my urls.py like this?

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

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

Or do you have any other(s) good idea(s) ?

谢谢。

推荐答案

我认为最好创建自己的url端点,该端点映射到向外部API发出请求的视图

I think it would be better to create your own url endpoint that maps to a view which makes a request to the external 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)

仅例。您也可以将其作为基于类的视图来实现。

Just an example. You can do it as a class-based view as well.

这篇关于Django rest框架&amp;外部API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆