kinimm
kinimm

Reputation: 1

python-requests automatically adds http header

def __init__(self):
   self.headers={'Accept':'application/json'}

def req1(self):
   headers=self.headers
   headers['bla']='bla'
   headers['Content-Type']='application/json'
   r=requests.post(url,headers=headers)

def req2(self):
   headers=self.headers
   headers['bla']='bla'
   r=requests.post(url + "/test1",headers=headers)

For some reason, when I execute those functions in this order:

   req1()
   req2()

'Content-Type' header is also sent in req2().

When I execute those functions in the reverse order:

   req2()
   req1()

'Content-Type' header is only sent in req1().

What might be the reason for that to happen? Maybe requests adds Content-Type header without asking?

For now I'm fixing the problem like so:

def req2():
   headers=self.headers
   headers['bla']='bla'
   del headers['Content-Type']
   r=requests.post(url + "/test1",headers=headers)

I'm looking for a better solution. Can someone explain what is going on?

Upvotes: 0

Views: 891

Answers (1)

alecxe
alecxe

Reputation: 473753

When you are assigning headers to self.headers, you are not actually copying the dictionary, you are just creating an another reference. Then, when you update headers, self.headers is updated cause both point to the same exact object.

If you need to actually copy a dictionary, there are different ways, please refer to:

Upvotes: 3

Related Questions