如何向标头添加令牌认证

时间:2018-10-30 09:49:08

标签: django testing

我试图创建一个使用django测试客户端的客户端,并通过令牌身份验证发出get请求。但是我收到401错误,所以出了点问题..当然,发布时也会发生这种情况。 我一直在寻找不同的解决方案,但没有任何效果。 这是代码的一部分:

from django.test import Client
  class MyClient:
    def __init__(self):
        self.client = Client()
        self.token = None

    def get(self, url):
        if self.token is not None:
            new_url = base + url
            result = self.client.get(new_url, headers={'Content-Type': 'application/json','Authorization': 'Token {}'.format(self.token)})
        else:
            result = self.client.get(url)
        return result

    def login(self, username, password):
        payload = {
           "username": username,
           "password": password
        }
        response = self.post_without_auth('/api/auth/token_auth/',payload)
        if response.status_code is 200:
           self.token = response.json()['token']
        return response

    def post_without_auth(self, url, payload):
       response = self.client.post(url, payload)
       return response

     def current_user(self):
        response = self.get('/api/current_user/')
        return response

1 个答案:

答案 0 :(得分:0)

调用方法后将设置令牌值

def get(self, url):
    self.post(username, password)
    if self.token is not None:
        new_url = base + url
        result = self.client.get(new_url, headers={'Content-Type': 'application/json','Authorization': 'Token {}'.format(self.token)})
    else:
        result = self.client.get(url)
    return result

def login(self, username, password):
    payload = {
       "username": username,
       "password": password
    }
    response = self.post_without_auth('/api/auth/token_auth/',payload)
    if response.status_code is 200:
       self.token = response.json()['token']
    return response