Is the Django Rest APIClient class a valid request?

I am wondering if the request is actually being made over http. In my application, I have a test that looks like

class Authenticate(APITestCase):

    def setUp(self):
        self.client = APIClient()
        self.password_for_admin = '123456'
        self.admin = User.objects.create_superuser(username='myname', email='email@email.com', password='123456')
        self.token = Token.objects.create(user=self.admin)

    def test_authenticate(self):
        """ comment """
        self.client.credentials(HTTP_AUTHORIZATION='Basic ' + base64.b64encode('{}:{}'.format(self.admin.username, self.password_for_admin)))
        response = self.client.post('/api/authenticate/')
        print response

      

And in my opinion I have:

@api_view(('POST',))
def authenticate(request, format=None):
    """ comment """
    import pprint
    log.debug(pprint.pprint(request))

    try:
        "asdlfjl"
    except Exception, e:
        response = "An error occurred, {}".format(e)
    return Response(response)

      

My settings look like this:

INSTALLED_APPS = (
    ...
    'django.contrib.sessions',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
)

      

In my log file, the request prints as None. I need to get a session. I tried request.session (which was None) and that led me to this question.

+3


source to share


1 answer


I understood that. The server sends a request using the testerver domain. It was kind of a misleading question and the code was wrong. The user is already authenticated with the underlying underlying backend by the time they reach this view method.

Through extensive research, it appears that the user authenticated using the rest principle, but the login method is not called by the rest of the backend. Since the login is not called from a backup, the session is never tied to the request. I changed the authentication method for login and I just called login by doing the following:



...

@api_view(('POST',))
def login(request, format=None):
    try:
        from django.contrib.auth import login
        if request.user and request.user.is_active:
            login(request, request.user)
            ...
            response = ...
        else:
            response = {}
    except Exception, e:
        response = "An error occurred, {}".format(e)
    return Response(response)

      

+1


source







All Articles