mardi 30 octobre 2018

how to add token authentication to header

I tried to create a client that uses django test client and make a get request with token authentication. But I get a 401 error so something is wrong ..Of course this also happens for post. I was looking for different solutions but nothing works. this is part of the code:

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

Aucun commentaire:

Enregistrer un commentaire