gpt4 book ai didi

python - 在 Django Rest FrameWork 中检索 HTTP header

转载 作者:行者123 更新时间:2023-12-04 14:38:24 26 4
gpt4 key购买 nike

我使用django rest框架实现了一个小功能,就是为我们的合作伙伴提供一个API来访问一些数据。后端已经写好了,我只是在编写 API 来利用它来获取一些数据,所以我只是使用基于函数的 View 来简化事情。这是我的测试代码:

@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 key .然后他使用 API key 来获取数据。问题是我无法检索放入 Authorization 的 key 。标题:
headers = {'Authorization': 'yNd5vdL4f6d4f6dfsdF29DPh9vUtg=='}
r = requests.get('http://localhost:8000/api/getdata', headers=headers)

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

最佳答案

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

来自 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 key ,您需要执行以下操作:
API_key = request.META.get('HTTP_AUTHORIZATION')

关于python - 在 Django Rest FrameWork 中检索 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com