Using Basic HTTP access authentication in Django testing framework

前端 未结 6 1463
栀梦
栀梦 2020-12-08 01:41

For some of my Django views I\'ve created a decorator that performs Basic HTTP access authentication. However, while writing test cases in Django, it took me a while to wor

6条回答
  •  长情又很酷
    2020-12-08 02:27

    Here's how I did it:

    from django.test import Client
    import base64
    auth_headers = {
        'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('username:password'),
    }
    c = Client()
    response = c.get('/my-protected-url/', **auth_headers)
    

    Note: You will also need to create a user.

提交回复
热议问题