def _do_request(self, uri, method, body=None, query=None, headers=None): """ Wrapper for api_lib.do_request that includes auth logic. """ if headers == None: headers = {} self.auth.set_header_token(headers) try: return api_lib.do_request(uri, method, body=body, query=query, headers=headers) except exc.HTTPUnauthorized: # Try one more time after logging in self.auth.set_header_token(headers, force=True) return api_lib.do_request(uri, method, body=body, query=query, headers=headers)
def login(self): """Login a user Make sure only one thread tries to login. The other threads would block until the first thread succeeds in setting the global _token variable. """ global _sem global _token if _sem.acquire(blocking=False): try: auth = base64.encodestring(self.username + ":" + self.password) headers = {"Authorization": "Basic " + auth} if self.project_id != None: headers["X-Auth-Project"] = self.project_id resp, _body = api_lib.do_request(self.uri, "POST", body={}, headers=headers) set_cookie = resp["set-cookie"] session, sep, exp = set_cookie.partition(";") session_key, sep, _token = session.partition("=") finally: _sem.release() else: LOG.debug("Waiting for token to get reset") # Wait for another thread to set the token and release _sem.acquire(blocking=True) _sem.release()