python - 如何在请求中传递/引用字典
问题描述
我已经使用下面的函数进行了 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
解决方案
我建议在此处使用 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)
推荐阅读
- networking - IP碎片令人困惑
- highcharts - Highchart 3d:图表图形。Z轴对齐问题
- java - 检查二叉树中的所有值是否低于其他二叉树中的所有值
- html - 使用 CSS 为文本添加特定的渐变
- python - 无法通过 Python win32Process.Create Process 运行 CMD 命令
- prometheus - 时间序列中的间隙导致警报无法使用
- ios - 导航返回时出现 Swift ios 错误
- sage-erp - 设置 Sage 200C
- scala - FS2:是否可以优雅地完成队列?
- javascript - javascript将对象添加到数组