【发布时间】:2019-08-12 12:37:35
【问题描述】:
我想在我编写的自定义视图中调用我自己的 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/ 但我仍然无法验证我的请求。
谁能指出我正确的方向?非常感谢您的帮助!提前致谢!
【问题讨论】:
标签: python django authentication django-rest-framework python-requests