Getting custom header on post request with django rest framework

后端 未结 2 1787
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 17:02

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/upda         


        
相关标签:
2条回答
  • 2020-12-15 17:42

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

    print request.META
    

    Your header will be available as:

    request.META['HTTP_X_MYHEADER']
    

    Or:

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

    Quote from the documentation:

    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.

    0 讨论(0)
  • 2020-12-15 17:46

    If you provide a valid header information and get that information from backend then follow those

    client-name='ABCKD'
    

    then you have get that client information in post or get function following this-

    request.META['HTTP_CLIENT_NAME']
    

    it will give you output 'ABCKD'.

    remember that, whatever the valid variable name you provide in your header information in request, django convert it uppercase and prefix with 'HTTP_' in here it will client-name converted to CLIENT_NAME and prefix with HTTP_. so final output is HTTP_CLIENT_NAME

    0 讨论(0)
提交回复
热议问题