首页 > 解决方案 > 如何在 DjangoRestFramework UI 中获得格式更好的 JSON 响应

问题描述

我在 DRF 中有一个 APIVIEW,我在其中写了一些视图以获得一些响应,我想获得一个格式更好的 JSONResponse。

视图.py

class Pay(APIView):
    def get(self, request):
        url = "https://api.paystack.co/transaction/verify/262762380"
        payload = {}
        files = {}
        headers = {
            'Authorization': 'Bearer SECRET_KEY',
            'Content-Type': 'application/json'
        }

        response = requests.request("GET", url, headers=headers, data= payload, files=files)
        return Response(response)

这是我想要改进的格式错误的 JSONResponse 的图形表示。谢谢

DRF 用户界面

标签: jsondjangoapidjango-rest-frameworkdjango-views

解决方案


因此,如果您没有模型,而是您以其他方式获得的某些数据结构(如来自第三方 API 的响应),则只需返回一个带有此数据结构作为参数的响应。

在这种情况下,您实际上是在 3rd 方 API 和您的客户端之间充当一种代理,如果这是您想要的(确保不要泄露私人数据!)

例子:

class Pay(APIView):
    def get(self, request):
        url = "https://api.paystack.co/transaction/verify/262762380"
        payload = {}
        files = {}
        headers = {
            'Authorization': 'Bearer SECRET_KEY',
            'Content-Type': 'application/json'
        }

        # no need for 'data' and 'files' arguments with method GET
        response = requests.get(url, headers=headers)

        # do some validation, at least check for response.status_code
        if response.status_code == 200:
            data = response.json()
            return Response(data)

使用requests 库时还有更多的可能性。


推荐阅读