Skip to content

Commit fb7fcd6

Browse files
authored
chore: blacken (#66)
1 parent 3758d8c commit fb7fcd6

File tree

8 files changed

+391
-359
lines changed

8 files changed

+391
-359
lines changed

google_auth_oauthlib/flow.py

Lines changed: 64 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
import hashlib
5656
import json
5757
import logging
58+
5859
try:
5960
from secrets import SystemRandom
6061
except 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

315319
class 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")]

google_auth_oauthlib/helpers.py

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import google.oauth2.credentials
2828
import requests_oauthlib
2929

30-
_REQUIRED_CONFIG_KEYS = frozenset(('auth_uri', 'token_uri', 'client_id'))
30+
_REQUIRED_CONFIG_KEYS = frozenset(("auth_uri", "token_uri", "client_id"))
3131

3232

3333
def session_from_client_config(client_config, scopes, **kwargs):
@@ -55,21 +55,19 @@ def session_from_client_config(client_config, scopes, **kwargs):
5555
/aaa_client_secrets
5656
"""
5757

58-
if 'web' in client_config:
59-
config = client_config['web']
60-
elif 'installed' in client_config:
61-
config = client_config['installed']
58+
if "web" in client_config:
59+
config = client_config["web"]
60+
elif "installed" in client_config:
61+
config = client_config["installed"]
6262
else:
63-
raise ValueError(
64-
'Client secrets must be for a web or installed app.')
63+
raise ValueError("Client secrets must be for a web or installed app.")
6564

6665
if not _REQUIRED_CONFIG_KEYS.issubset(config.keys()):
67-
raise ValueError('Client secrets is not in the correct format.')
66+
raise ValueError("Client secrets is not in the correct format.")
6867

6968
session = requests_oauthlib.OAuth2Session(
70-
client_id=config['client_id'],
71-
scope=scopes,
72-
**kwargs)
69+
client_id=config["client_id"], scope=scopes, **kwargs
70+
)
7371

7472
return session, client_config
7573

@@ -94,7 +92,7 @@ def session_from_client_secrets_file(client_secrets_file, scopes, **kwargs):
9492
https://developers.google.com/api-client-library/python/guide
9593
/aaa_client_secrets
9694
"""
97-
with open(client_secrets_file, 'r') as json_file:
95+
with open(client_secrets_file, "r") as json_file:
9896
client_config = json.load(json_file)
9997

10098
return session_from_client_config(client_config, scopes, **kwargs)
@@ -126,17 +124,17 @@ def credentials_from_session(session, client_config=None):
126124

127125
if not session.token:
128126
raise ValueError(
129-
'There is no access token for this session, did you call '
130-
'fetch_token?')
127+
"There is no access token for this session, did you call " "fetch_token?"
128+
)
131129

132130
credentials = google.oauth2.credentials.Credentials(
133-
session.token['access_token'],
134-
refresh_token=session.token.get('refresh_token'),
135-
id_token=session.token.get('id_token'),
136-
token_uri=client_config.get('token_uri'),
137-
client_id=client_config.get('client_id'),
138-
client_secret=client_config.get('client_secret'),
139-
scopes=session.scope)
140-
credentials.expiry = datetime.datetime.utcfromtimestamp(
141-
session.token['expires_at'])
131+
session.token["access_token"],
132+
refresh_token=session.token.get("refresh_token"),
133+
id_token=session.token.get("id_token"),
134+
token_uri=client_config.get("token_uri"),
135+
client_id=client_config.get("client_id"),
136+
client_secret=client_config.get("client_secret"),
137+
scopes=session.scope,
138+
)
139+
credentials.expiry = datetime.datetime.utcfromtimestamp(session.token["expires_at"])
142140
return credentials

0 commit comments

Comments
 (0)