<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:

def token(self):
        " Get token when needed."

        if hasattr(self, '_token'):
            return getattr(self, '_token')

        # Json formatted auth.
        data = json.dumps({'customer_name': self.customer,
                           'user_name': self.username,
                           'password': self.password})

        # Start session.
        response = requests.post(
            'https://api2.dynect.net/REST/Session/', data=data,
            headers={'Content-Type': 'application/json'})

        # convert to data.
        content = json.loads(response.content)

        if response.status_code != 200:
            # Check for errors.
            if self.check_error(content, 'failure', 'INVALID_DATA'):
                raise self.CredentialsError(
                    self.response_message(content, 'ERROR'))

            raise self.Failure(self.response_message(content, 'ERROR'),
                               'Unhandled failure')

        # Extract token from content
        if 'data' in content and 'token' in content['data']:
            token = content['data']['token']
        else:
            raise self.AuthenticationError(response)

        setattr(self, '_token', token)
        return token