Login

Add Extra Headers to Test Client Requests

Author:
luftyluft
Posted:
July 3, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

As Simon Willison mentions in his Debugging Django presentation, using the Test Client in the interpreter can be a great way to take a peek at the raw results from a view. In some cases you may need to add additional headers to the request (for instance a piece of middleware may rely on them).

Though it is not mentioned in the reference documentation, a quick peek at the code confirmed my hopes that it would be possible to add data to the request. The Client get and post methods both accept an extra kwargs parameter that allow you to populate the request with additional data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
"""
example of using the **extra kwarg param to add headers to the test client request
"""
from django.test.utils import setup_test_environment
setup_test_environment()
from django.test.client import Client
c = Client()

#example using a query string param
c.get('/some/path/', {'qs_param':'foo'}, **{'HTTP_USER_AGENT':'silly-human', 'REMOTE_ADDR':'127.0.0.1'})

#example without a query string param
c.get('/some/path/', **{'HTTP_USER_AGENT':'silly-human', 'REMOTE_ADDR':'127.0.0.1'})

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

belavaishalichuphal (on April 18, 2019):

response = self.client.post('/api/v2/chatbot/update-complete-flag/5cb81d51ae637b5cc6256f97/', {"data": {"chat_complete_flag": True, "bot_id": "5c864c61ae637b54fb596c96"}}, HTTP_AUTHORIZATION='Basic API-KEY:generatesomesecurekeyforthis')

Tried with above for HTTP_AUTHORIZATION header 'Malformed function' return

#

belavaishalichuphal (on April 18, 2019):

self.client.post('/api/v2/chatbot/update-complete-flag/5cb81d51ae637b5cc6256f97/', {"data": {"chat_complete_flag": True, "bot_id": "5c864c61ae637b54fb596c96"}}, **{'HTTP_AUTHORIZATION':'Basic QVBJLUtFWTpnZW5lcmF0ZXNvbWVzZWN1cmVrZXlmb3J0aGlz'})

tried with the above one too.

#

Please login first before commenting.