Amit Yadav
Amit Yadav

Reputation: 59

How can i read the data of headers of a post request sent by python requests?

Looking for the help, I am making a post request to an django application with AUTH-TOKEN in the header and trying to access it on view but not able to.

python app
    import requests
    import json
    URL = "http://127.0.0.1:8000/test/api/" 
    request_data ={
                    'order':{
                    'id':'order.id',
                    'payment_collection_status': 'transaction_status',
                    'payment_collection_message': 'transaction_message'
                    }
                }
    
    request_headers = {'AUTH-TOKEN':'webhook_auth_token'}
    json_data = json.dumps(request_data)
    response = requests.post(url = URL,headers=request_headers, data = json_data)
    print(response)

django application view
from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt 
@csrf_exempt
def request_handle(request):
    if (request.method=='POST'):
        print(request.body)
        print(request.META["AUTH-TOKEN"])
        return HttpResponse('<h1>hello</h1>')

but not able read the header data it is throwing an error: KeyError: 'AUTH-TOKEN'

Upvotes: 1

Views: 2534

Answers (1)

Mehran
Mehran

Reputation: 1304

Try to use

  1. request.META.get('HTTP_AUTH_TOKEN')
  2. request.headers.get('AUTH-TOKEN') if you're on Django>=2.2

More details on Documentation

Upvotes: 2

Related Questions