我想在编写的自定义视图中调用自己的API。通常,我在API调用中使用JWT身份验证。不过,在这种特定视图下,我想使用其他身份验证。
我想使已登录的用户能够成功进行get调用(没有令牌)。未登录的用户应该无法拨打该电话。我尝试了基本身份验证和会话身份验证,但是并没有真正使它工作。
这是我进行API调用的观点:
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视图:
class BuildingGroupRetrieveAPIView(RetrieveAPIView):
authentication_classes = [JSONWebTokenAuthentication,
SessionAuthentication, BasicAuthentication]
serializer_class = BuildingGroupSerializer
queryset = BuildingGroup.objects.all()
如果我在标头中发送令牌,则可以使用该视图。但是,我该如何使用会话身份验证?我尝试从请求中获取用户名和密码,然后将其传递给API调用。但这是行不通的,因为我无法从请求中解码密码(这很有意义)。因此,我尝试遵循此方法:https://2.python-requests.org/en/master/user/advanced/
但是我仍然无法验证我的请求。
谁能指出我正确的方向?非常感谢您的帮助!提前致谢!
会话ID会以Cookie的形式保存在用户设备上,并将作为标头名称发送到服务器Cookie
。因此,如果要使用cookie而不是JWT令牌,则应发送带有会话ID作为cookie头的请求。
这是标头,可让Django在您直接访问站点时知道您的会话ID:
Cookie: csrftoken=some-csrf-token; sessionid=your-session-id
现在,使您的请求包含以下内容:
cookies = {'sessionid': 'your-session-id'}
response = requests.get(endpoint, cookies=cookies)
请注意,根据您的设置,Django可能仍会因csrf令牌出现错误。
您可以在浏览器中找到会话ID。如果您不知道在哪里以及如何访问它们,只需在Google上进行搜索即可。根据您使用的浏览器而有所不同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句