0
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?

1 Answer 1

3

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.