在 Django RestFrameWork 中检索 HTTP 标头

J F*_*ird 2 python django django-views http-headers django-rest-framework

我使用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})
Run Code Online (Sandbox Code Playgroud)

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

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

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

Rah*_*pta 10

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

来自request.META上的 Django 文档

除了CONTENT_LENGTHand 之外CONTENT_TYPE,通过将所有字符转换为大写,将所有连字符替换为下划线并在 name 中添加 HTTP_ 前缀,请求中的任何 HTTP 标头都会转换为 META 键。因此,例如,调用的标头X-Bender将映射到 META 键HTTP_X_BENDER

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

API_key = request.META.get('HTTP_AUTHORIZATION')
Run Code Online (Sandbox Code Playgroud)