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

查看:37
本文介绍了如何在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/

在我的其余框架视图中,我想获取Costum标头,如果自定义标头满足条件,我将继续分析我的帖子数据.

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框架在我的帖子请求中获取自定义标头的方法是什么?

¿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

您的标题将显示为:

request.META['HTTP_X_MYHEADER']

或者:

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

引用文档:

通过将所有字符都转换为大写字母,用下划线替换所有连字符,并在名称中添加一个 HTTP _ 前缀,将请求中的

HTTP标头转换为 META 键.因此,例如,名为 X-Bender 的标头将映射到 META HTTP_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天全站免登陆