首页 > 解决方案 > 如何在请求中传递/引用字典

问题描述

我已经使用下面的函数进行了 API 调用,我正在 Postman 上进行测试。它接受一个 id(dictionary) 并删除具有该 id 的医生。所以解决方案按原样工作。问题是,id 是硬编码的 - id = {"id": 11} 。我如何引用它以便我可以在邮递员中提供它而不是硬编码?我已经尝试使用 id = request.GET.get("id")并将其添加为参数,但它对我不起作用。任何帮助将不胜感激

视图.py

class DoctorBillingPayments(GenericAPIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    @classmethod
    @encryption_check
        def delete(self, request, *args, **kwargs):
            id = {"id": 11}
            try:
                result = {}
                auth = cc_authenticate()
                res = deleteDoctor(auth["key"],id)
                result = res
                return Response(result, status=status.HTTP_200_OK)
            except Exception as e:
                error = getattr(e, "message", repr(e))
                result["errors"] = error
                result["status"] = "error"

            return Response(result, status=status.HTTP_400_BAD_REQUEST)

api_service.py

def deleteDoctor(auth, data):
try:
    
    headers = {
                "Authorization": f'Token {auth}'
    }
    url = f'{CC_URL}/doctors/'
    print(url)
    res = requests.delete(url, json=data, headers=headers)

    return res.json()

except ConnectionError as err:
    print("connection exception occurred")
    print(err)

    return err        

标签: pythondjangorequest

解决方案


我建议在此处使用 REST 样式并使用路径参数将 id 传递给视图,如下所示:

  • DELETE /doctor/{id}

为此,您将在您的内部定义参数urls

url(r'^doctor/(?P<id>[0-9]+)/$', DoctorBillingPayments.as_view(), name="doctors")

然后您可以从kwargs一个示例请求中访问它,例如DELETE /doctor/123

class DoctorBillingPayments(GenericAPIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    @classmethod
    @encryption_check
    def delete(self, request, *args, **kwargs):
        id = int(kwargs['id'])
        try:
            result = {}
            auth = cc_authenticate()
            res = deleteDoctor(auth["key"],id)
            result = res
            return Response(result, status=status.HTTP_200_OK)
        except Exception as e:
            error = getattr(e, "message", repr(e))
            result["errors"] = error
            result["status"] = "error"

        return Response(result, status=status.HTTP_400_BAD_REQUEST)

推荐阅读