5555import hashlib
5656import json
5757import logging
58+
5859try :
5960 from secrets import SystemRandom
6061except ImportError : # pragma: NO COVER
@@ -94,9 +95,14 @@ class Flow(object):
9495 """
9596
9697 def __init__ (
97- self , oauth2session , client_type , client_config ,
98- redirect_uri = None , code_verifier = None ,
99- autogenerate_code_verifier = False ):
98+ self ,
99+ oauth2session ,
100+ client_type ,
101+ client_config ,
102+ redirect_uri = None ,
103+ code_verifier = None ,
104+ autogenerate_code_verifier = False ,
105+ ):
100106 """
101107 Args:
102108 oauth2session (requests_oauthlib.OAuth2Session):
@@ -150,32 +156,30 @@ def from_client_config(cls, client_config, scopes, **kwargs):
150156 https://developers.google.com/api-client-library/python/guide
151157 /aaa_client_secrets
152158 """
153- if ' web' in client_config :
154- client_type = ' web'
155- elif ' installed' in client_config :
156- client_type = ' installed'
159+ if " web" in client_config :
160+ client_type = " web"
161+ elif " installed" in client_config :
162+ client_type = " installed"
157163 else :
158- raise ValueError (
159- 'Client secrets must be for a web or installed app.' )
164+ raise ValueError ("Client secrets must be for a web or installed app." )
160165
161166 # these args cannot be passed to requests_oauthlib.OAuth2Session
162- code_verifier = kwargs .pop ('code_verifier' , None )
163- autogenerate_code_verifier = kwargs .pop (
164- 'autogenerate_code_verifier' , None )
167+ code_verifier = kwargs .pop ("code_verifier" , None )
168+ autogenerate_code_verifier = kwargs .pop ("autogenerate_code_verifier" , None )
165169
166- session , client_config = (
167- google_auth_oauthlib . helpers . session_from_client_config (
168- client_config , scopes , ** kwargs ) )
170+ session , client_config = google_auth_oauthlib . helpers . session_from_client_config (
171+ client_config , scopes , ** kwargs
172+ )
169173
170- redirect_uri = kwargs .get (' redirect_uri' , None )
174+ redirect_uri = kwargs .get (" redirect_uri" , None )
171175
172176 return cls (
173177 session ,
174178 client_type ,
175179 client_config ,
176180 redirect_uri ,
177181 code_verifier ,
178- autogenerate_code_verifier
182+ autogenerate_code_verifier ,
179183 )
180184
181185 @classmethod
@@ -193,7 +197,7 @@ def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs):
193197 Returns:
194198 Flow: The constructed Flow instance.
195199 """
196- with open (client_secrets_file , 'r' ) as json_file :
200+ with open (client_secrets_file , "r" ) as json_file :
197201 client_config = json .load (json_file )
198202
199203 return cls .from_client_config (client_config , scopes = scopes , ** kwargs )
@@ -232,23 +236,24 @@ def authorization_url(self, **kwargs):
232236 :class:`Flow` instance to obtain the token, you will need to
233237 specify the ``state`` when constructing the :class:`Flow`.
234238 """
235- kwargs .setdefault (' access_type' , ' offline' )
239+ kwargs .setdefault (" access_type" , " offline" )
236240 if self .autogenerate_code_verifier :
237- chars = ascii_letters + digits + ' -._~'
241+ chars = ascii_letters + digits + " -._~"
238242 rnd = SystemRandom ()
239243 random_verifier = [rnd .choice (chars ) for _ in range (0 , 128 )]
240- self .code_verifier = '' .join (random_verifier )
244+ self .code_verifier = "" .join (random_verifier )
241245
242246 if self .code_verifier :
243247 code_hash = hashlib .sha256 ()
244248 code_hash .update (str .encode (self .code_verifier ))
245249 unencoded_challenge = code_hash .digest ()
246250 b64_challenge = urlsafe_b64encode (unencoded_challenge )
247- code_challenge = b64_challenge .decode ().split ('=' )[0 ]
248- kwargs .setdefault (' code_challenge' , code_challenge )
249- kwargs .setdefault (' code_challenge_method' , ' S256' )
251+ code_challenge = b64_challenge .decode ().split ("=" )[0 ]
252+ kwargs .setdefault (" code_challenge" , code_challenge )
253+ kwargs .setdefault (" code_challenge_method" , " S256" )
250254 url , state = self .oauth2session .authorization_url (
251- self .client_config ['auth_uri' ], ** kwargs )
255+ self .client_config ["auth_uri" ], ** kwargs
256+ )
252257
253258 return url , state
254259
@@ -275,10 +280,9 @@ def fetch_token(self, **kwargs):
275280 :meth:`credentials` to obtain a
276281 :class:`~google.auth.credentials.Credentials` instance.
277282 """
278- kwargs .setdefault ('client_secret' , self .client_config ['client_secret' ])
279- kwargs .setdefault ('code_verifier' , self .code_verifier )
280- return self .oauth2session .fetch_token (
281- self .client_config ['token_uri' ], ** kwargs )
283+ kwargs .setdefault ("client_secret" , self .client_config ["client_secret" ])
284+ kwargs .setdefault ("code_verifier" , self .code_verifier )
285+ return self .oauth2session .fetch_token (self .client_config ["token_uri" ], ** kwargs )
282286
283287 @property
284288 def credentials (self ):
@@ -295,7 +299,8 @@ def credentials(self):
295299 ValueError: If there is no access token in the session.
296300 """
297301 return google_auth_oauthlib .helpers .credentials_from_session (
298- self .oauth2session , self .client_config )
302+ self .oauth2session , self .client_config
303+ )
299304
300305 def authorized_session (self ):
301306 """Returns a :class:`requests.Session` authorized with credentials.
@@ -308,8 +313,7 @@ class using this flow's :attr:`credentials`.
308313 google.auth.transport.requests.AuthorizedSession: The constructed
309314 session.
310315 """
311- return google .auth .transport .requests .AuthorizedSession (
312- self .credentials )
316+ return google .auth .transport .requests .AuthorizedSession (self .credentials )
313317
314318
315319class InstalledAppFlow (Flow ):
@@ -353,25 +357,28 @@ class InstalledAppFlow(Flow):
353357 https://developers.google.com/api-client-library/python/auth
354358 /installed-app
355359 """
356- _OOB_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
360+
361+ _OOB_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"
357362
358363 _DEFAULT_AUTH_PROMPT_MESSAGE = (
359- 'Please visit this URL to authorize this application: {url}' )
364+ "Please visit this URL to authorize this application: {url}"
365+ )
360366 """str: The message to display when prompting the user for
361367 authorization."""
362- _DEFAULT_AUTH_CODE_MESSAGE = (
363- 'Enter the authorization code: ' )
368+ _DEFAULT_AUTH_CODE_MESSAGE = "Enter the authorization code: "
364369 """str: The message to display when prompting the user for the
365370 authorization code. Used only by the console strategy."""
366371
367372 _DEFAULT_WEB_SUCCESS_MESSAGE = (
368- 'The authentication flow has completed. You may close this window.' )
373+ "The authentication flow has completed. You may close this window."
374+ )
369375
370376 def run_console (
371- self ,
372- authorization_prompt_message = _DEFAULT_AUTH_PROMPT_MESSAGE ,
373- authorization_code_message = _DEFAULT_AUTH_CODE_MESSAGE ,
374- ** kwargs ):
377+ self ,
378+ authorization_prompt_message = _DEFAULT_AUTH_PROMPT_MESSAGE ,
379+ authorization_code_message = _DEFAULT_AUTH_CODE_MESSAGE ,
380+ ** kwargs
381+ ):
375382 """Run the flow using the console strategy.
376383
377384 The console strategy instructs the user to open the authorization URL
@@ -391,7 +398,7 @@ def run_console(
391398 google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
392399 for the user.
393400 """
394- kwargs .setdefault (' prompt' , ' consent' )
401+ kwargs .setdefault (" prompt" , " consent" )
395402
396403 self .redirect_uri = self ._OOB_REDIRECT_URI
397404
@@ -406,11 +413,14 @@ def run_console(
406413 return self .credentials
407414
408415 def run_local_server (
409- self , host = 'localhost' , port = 8080 ,
410- authorization_prompt_message = _DEFAULT_AUTH_PROMPT_MESSAGE ,
411- success_message = _DEFAULT_WEB_SUCCESS_MESSAGE ,
412- open_browser = True ,
413- ** kwargs ):
416+ self ,
417+ host = "localhost" ,
418+ port = 8080 ,
419+ authorization_prompt_message = _DEFAULT_AUTH_PROMPT_MESSAGE ,
420+ success_message = _DEFAULT_WEB_SUCCESS_MESSAGE ,
421+ open_browser = True ,
422+ ** kwargs
423+ ):
414424 """Run the flow using the server strategy.
415425
416426 The server strategy instructs the user to open the authorization URL in
@@ -440,10 +450,10 @@ def run_local_server(
440450 """
441451 wsgi_app = _RedirectWSGIApp (success_message )
442452 local_server = wsgiref .simple_server .make_server (
443- host , port , wsgi_app , handler_class = _WSGIRequestHandler )
453+ host , port , wsgi_app , handler_class = _WSGIRequestHandler
454+ )
444455
445- self .redirect_uri = 'http://{}:{}/' .format (
446- host , local_server .server_port )
456+ self .redirect_uri = "http://{}:{}/" .format (host , local_server .server_port )
447457 auth_url , _ = self .authorization_url (** kwargs )
448458
449459 if open_browser :
@@ -455,8 +465,7 @@ def run_local_server(
455465
456466 # Note: using https here because oauthlib is very picky that
457467 # OAuth 2.0 should only occur over https.
458- authorization_response = wsgi_app .last_request_uri .replace (
459- 'http' , 'https' )
468+ authorization_response = wsgi_app .last_request_uri .replace ("http" , "https" )
460469 self .fetch_token (authorization_response = authorization_response )
461470
462471 return self .credentials
@@ -467,6 +476,7 @@ class _WSGIRequestHandler(wsgiref.simple_server.WSGIRequestHandler):
467476
468477 Uses a named logger instead of printing to stderr.
469478 """
479+
470480 def log_message (self , format , * args ):
471481 # pylint: disable=redefined-builtin
472482 # (format is the argument name defined in the superclass.)
@@ -499,6 +509,6 @@ def __call__(self, environ, start_response):
499509 Returns:
500510 Iterable[bytes]: The response body.
501511 """
502- start_response (' 200 OK' , [(' Content-type' , ' text/plain' )])
512+ start_response (" 200 OK" , [(" Content-type" , " text/plain" )])
503513 self .last_request_uri = wsgiref .util .request_uri (environ )
504- return [self ._success_message .encode (' utf-8' )]
514+ return [self ._success_message .encode (" utf-8" )]
0 commit comments