Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a header to a Django RequestFactory request?

To manually send a GET request with a header, I do this with curl:

curl http://example.com/endpoint -H "Key: Value"

I want to write a unit test that makes a request (using django.test.RequestFactory) containing a header. How can I add a header to the request?

For clarity, below is an example of what I'd like to be able to do, though what I have written below is not valid code because RequestFactory.get() does not have a headers parameter:

from django.test import TestCase, RequestFactory


class TestClassForMyDjangoApp(TestCase):
    def test_for_my_app(self):
        factory = RequestFactory()
        
        my_header = dict(key=value, another_key=another_value)
        factory.get('/endpoint/', headers=my_header)
like image 961
tedtanner Avatar asked Mar 09 '26 22:03

tedtanner


1 Answers

You need to pass HTTP_* kwargs to the get(...) ( or any valid http methods) to pass a custom HTTP header in the request.


class TestClassForMyDjangoApp(TestCase):
    def test_for_my_app(self):
        factory = RequestFactory()
        my_header = {"HTTP_CUSTOM_KEY": "VALUE"}
        request = factory.get("/some/url/", **my_header)
        print(request.headers) # {'Custom-Key': 'VALUE'}
like image 77
JPG Avatar answered Mar 12 '26 13:03

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!