如何访问 Django Rest Framework 上的自定义 HTTP 请求标头? [英] How to access custom HTTP request headers on Django Rest Framework?

查看:21
本文介绍了如何访问 Django Rest Framework 上的自定义 HTTP 请求标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向使用 django rest 框架创建的 API 发送一个发布请求:

I'm sending a post request to my API made using django rest framework:

curl --header "X-MyHeader: 123" --data "test=test" http://127.0.0.1:8000/api/update_log/

在我的rest framework视图中,我想获取我的costum header,如果自定义header满足条件,我会继续分析我的post数据.

In my rest framework view, I want to get my costum header, and if the custom header satisfies a condition, I will proceed to analyze my post data.

好的,我的视图如下:

class PostUpdateLogView(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (
        parsers.FormParser,
        parsers.MultiPartParser,
        parsers.JSONParser,
    )  

    renderer_classes = (renderers.JSONRenderer,)

    def post(self, request):
        print request.Meta
        # Get custom header
        # Validate custom header
        # Proceed to analize post data

        # Make response
        content = {
            'response': 'response',
        }

        return Response(content)

我试图在 request.Meta 元素上找到我的自定义标头,但是当我打印 request.Meta 时,我收到 500 错误.如果我打印 request.data,我会得到预期的响应.

I'm trying to find my custom header on request.Meta element, but when I print request.Meta, I get a 500 error. If I print request.data, I get the expected response.

¿使用 django rest 框架在我的 post 请求中获取自定义标头的方法是什么?

¿What is the way to get a custom header on my post request using django rest framework?

推荐答案

请求的元数据属性名称为大写:

The name of the meta data attribute of request is in upper case:

print request.META

如果您的标头名为My-Header",您的标头将显示为:

If your header is called "My-Header", your header will be available as:

request.META['HTTP_MY_HEADER']

或者:

request.META.get('HTTP_MY_HEADER') # return `None` if no such header

引用自文档:

请求中的 HTTP 标头通过将所有字符转换为大写、用下划线替换任何连字符并在名称中添加 HTTP_ 前缀来转换为 META 键.因此,例如,名为 X-Bender 的标头将映射到 METAHTTP_X_BENDER.

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.

这篇关于如何访问 Django Rest Framework 上的自定义 HTTP 请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆