在Django RestFrameWork中检索HTTP标头

问题描述 投票:0回答:1

我正在使用django rest框架来实现一个小函数,即为我们的合作伙伴提供访问某些数据的API。后端已经编写完了,我只是编写API来获取它来获取一些数据,所以我只是使用基于函数的视图来简化操作。这是我的测试代码:

@api_view(['GET'])
@authentication_classes((BasicAuthentication,))
@permission_classes((IsAuthenticated,))
def get_key(request):
    username = request.user.username
    enc = encode(key, username)
    return Response({'API_key': enc, 'username': username}, status=status.HTTP_200_OK)

@api_view(['GET'])
def get_data(request):
    user = request.user
    API_key = request.META.get('Authorization') # the value is null
    return Response({'API_key': API_key})

因此,登录用户首先通过调用get_key(request)获取API密钥。然后他使用API​​密钥获取数据。问题是我无法检索放入Authorization标头的密钥:

headers = {'Authorization': 'yNd5vdL4f6d4f6dfsdF29DPh9vUtg=='}
r = requests.get('http://localhost:8000/api/getdata', headers=headers)

所以我想知道如何在django rest框架中获取头字段?

python django http-headers django-views django-rest-framework
1个回答
3
投票

您需要查找HTTP_AUTHORIZATION密钥而不是AUTHORIZATION,因为Django将HTTP_前缀附加到标头名称。

来自request.META:上的Django文档

除了CONTENT_LENGTHCONTENT_TYPE之外,请求中的任何HTTP头都将转换为META密钥,方法是将所有字符转换为大写,用下划线替换任何连字符,并在名称中添加HTTP_前缀。因此,例如,名为X-Bender的标头将映射到META密钥HTTP_X_BENDER

因此,要检索API密钥,您需要执行以下操作:

API_key = request.META.get('HTTP_AUTHORIZATION')
© www.soinside.com 2019 - 2024. All rights reserved.