在 Django Rest FrameWork 中检索 HTTP Header

Retrieve HTTP Header in Django RestFrameWork

我正在使用django rest framework实现一个小功能,就是提供一个API给合作伙伴访问一些数据。后端已经写好了,我只写了 API 来利用它来获取一些数据,所以我只是使用 function-based 视图来简化事情。这是我的测试代码:

@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})

因此 logged-in 用户首先通过调用 get_key(request) 获得一个 API 密钥。然后他使用 API 键来获取数据。问题是我无法检索放入 Authorization header:

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

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

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

来自 request.META:

上的 Django 文档

With the exception of CONTENT_LENGTH and CONTENT_TYPE, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

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

API_key = request.META.get('HTTP_AUTHORIZATION')