gpt4 book ai didi

python - 使用请求和 session 正确验证 API 调用

转载 作者:行者123 更新时间:2023-12-01 07:25:44 25 4
gpt4 key购买 nike

我想在我编写的自定义 View 中调用我自己的 API。通常我在 API 调用中使用 JWT 身份验证。但在这个特定的 View 中,我想使用不同的身份验证。

我希望登录的用户能够成功进行 get 调用(无需 token )。未登录的用户不应该能够调用该电话。我尝试使用基本身份验证和 session 身份验证,但并没有真正发挥作用。

这是我进行 API 调用的 View :

def visualize_buildings(request, id):
passed_id = id
endpoint = 'linktomyendpoint' + str(passed_id)

response = requests.get(endpoint)
building_group_data = response.json()
# print(building_group_data)

if 'buildings' in building_group_data:
building_data = building_group_data['buildings']
context = {'building' : building_data}
return render(request, 'building_group_visualize_api.html', context)
else:
return HttpResponseNotFound("Ups. We are sorry but no Building Group was found with that id")

这是我的 API View :

class BuildingGroupRetrieveAPIView(RetrieveAPIView):

authentication_classes = [JSONWebTokenAuthentication,
SessionAuthentication, BasicAuthentication]
serializer_class = BuildingGroupSerializer
queryset = BuildingGroup.objects.all()

如果我在 header 中发送 token ,则该 View 将起作用。但是我如何使用 session 身份验证呢?我尝试从请求中获取用户名和密码,然后将其传递给 API 调用。但这不起作用,因为我无法解码请求中的密码(这是有道理的)。所以我尝试遵循以下操作:https://2.python-requests.org/en/master/user/advanced/ 但我仍然无法验证我的请求。

有人能指出我正确的方向吗?非常感谢帮助!提前致谢!

最佳答案

session ID 作为 Cookie 保存在用户设备上,并将作为 header 名称 Cookie 发送到服务器。因此,如果您想使用 cookie 而不是 JWT token ,那么您应该使用 session ID 作为 cookie header 来发送请求。

当您直接访问站点时,这是让 Django 知道您的 session ID 的 header :

Cookie: csrftoken=some-csrf-token; sessionid=your-session-id

现在让您的请求包含类似的内容:

cookies = {'sessionid': 'your-session-id'}
response = requests.get(endpoint, cookies=cookies)

请注意,根据您的设置,Django 可能仍会出现 csrf token 错误。

您可以在浏览器上找到您的 session ID。如果您不知道在哪里以及如何访问它们,只需谷歌搜索即可。根据您使用的浏览器而有所不同。

关于python - 使用请求和 session 正确验证 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57461366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com