def authenticate(self, no_browser=False): if no_browser: httpd = None redirect_uri = 'urn:ietf:wg:oauth:2.0:oob' else: httpd = ClientRedirectServer(('localhost', 0), ClientRedirectHandler) redirect_uri = 'http://localhost:%d/' % httpd.server_port flow = OAuth2WebServerFlow(client_id=self.CLIENT_ID, client_secret=self.CLIENT_SECRET, scope=self.SCOPE, redirect_uri=redirect_uri) auth_url = flow.step1_get_authorize_url() if httpd is None: print('Open the following URL in a browser:\n\n%s' % auth_url) code = input('Enter verification code: ').strip() else: webbrowser.open(auth_url) print('Your browser has been opened to visit:\n\n%s\n' % auth_url) print('If your browser is on a different machine, then exit ' 'and re-run with the --no-browser command line option.') try: httpd.handle_request() finally: httpd.server_close() if 'error' in httpd.query_params: raise GAPIError('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: raise GAPIError('Failed to retreive verification code. ' 'Try running with --no-browser.') credentials = flow.step2_exchange(code) self.config.update_credentials(credentials)