Skip to content

Commit b02156b

Browse files
committed
Assorted import/lint cleanup.
This is mostly a cleanup around import statements and a few related pylint issues.
1 parent 817eefd commit b02156b

File tree

14 files changed

+114
-154
lines changed

14 files changed

+114
-154
lines changed

oauth2client/appengine.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,13 @@
1919

2020
__author__ = '[email protected] (Joe Gregorio)'
2121

22-
import base64
2322
import cgi
2423
import httplib2
2524
import json
2625
import logging
2726
import os
2827
import pickle
2928
import threading
30-
import time
3129

3230
from google.appengine.api import app_identity
3331
from google.appengine.api import memcache

oauth2client/client.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,9 @@
2020
__author__ = '[email protected] (Joe Gregorio)'
2121

2222
import base64
23-
import clientsecrets
23+
import collections
2424
import copy
2525
import datetime
26-
import httplib2
2726
import json
2827
import logging
2928
import os
@@ -32,10 +31,11 @@
3231
import urllib
3332
import urlparse
3433

35-
from collections import namedtuple
34+
import httplib2
3635
from oauth2client import GOOGLE_AUTH_URI
3736
from oauth2client import GOOGLE_REVOKE_URI
3837
from oauth2client import GOOGLE_TOKEN_URI
38+
from oauth2client import clientsecrets
3939
from oauth2client import util
4040

4141
HAS_OPENSSL = False
@@ -48,11 +48,6 @@
4848
except ImportError:
4949
pass
5050

51-
try:
52-
from urlparse import parse_qsl
53-
except ImportError:
54-
from cgi import parse_qsl
55-
5651
logger = logging.getLogger(__name__)
5752

5853
# Expiry is stored in RFC3339 UTC format
@@ -81,7 +76,8 @@
8176
GOOGLE_APPLICATION_CREDENTIALS = 'GOOGLE_APPLICATION_CREDENTIALS'
8277

8378
# The access token along with the seconds in which it expires.
84-
AccessTokenInfo = namedtuple('AccessTokenInfo', ['access_token', 'expires_in'])
79+
AccessTokenInfo = collections.namedtuple(
80+
'AccessTokenInfo', ['access_token', 'expires_in'])
8581

8682
class Error(Exception):
8783
"""Base error for this module."""
@@ -394,11 +390,11 @@ def _update_query_params(uri, params):
394390
Returns:
395391
The same URI but with the new query parameters added.
396392
"""
397-
parts = list(urlparse.urlparse(uri))
398-
query_params = dict(parse_qsl(parts[4])) # 4 is the index of the query part
393+
parts = urlparse.urlparse(uri)
394+
query_params = dict(urlparse.parse_qsl(parts.query))
399395
query_params.update(params)
400-
parts[4] = urllib.urlencode(query_params)
401-
return urlparse.urlunparse(parts)
396+
new_parts = parts._replace(query=urllib.urlencode(query_params))
397+
return urlparse.urlunparse(new_parts)
402398

403399

404400
class OAuth2Credentials(Credentials):
@@ -1457,7 +1453,7 @@ def _parse_exchange_token_response(content):
14571453
except StandardError:
14581454
# different JSON libs raise different exceptions,
14591455
# so we just do a catch-all here
1460-
resp = dict(parse_qsl(content))
1456+
resp = dict(urlparse.parse_qsl(content))
14611457

14621458
# some providers respond with 'expires', others with 'expires_in'
14631459
if resp and 'expires' in resp:

oauth2client/crypt.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -336,9 +336,8 @@ def verify_signed_jwt_with_certs(jwt, certs, audience):
336336
"""
337337
segments = jwt.split('.')
338338

339-
if (len(segments) != 3):
340-
raise AppIdentityError(
341-
'Wrong number of segments in token: %s' % jwt)
339+
if len(segments) != 3:
340+
raise AppIdentityError('Wrong number of segments in token: %s' % jwt)
342341
signed = '%s.%s' % (segments[0], segments[1])
343342

344343
signature = _urlsafe_b64decode(segments[2])
@@ -352,9 +351,9 @@ def verify_signed_jwt_with_certs(jwt, certs, audience):
352351

353352
# Check signature.
354353
verified = False
355-
for (keyname, pem) in certs.items():
354+
for _, pem in certs.items():
356355
verifier = Verifier.from_string(pem, True)
357-
if (verifier.verify(signed, signature)):
356+
if verifier.verify(signed, signature):
358357
verified = True
359358
break
360359
if not verified:
@@ -372,16 +371,15 @@ def verify_signed_jwt_with_certs(jwt, certs, audience):
372371
if exp is None:
373372
raise AppIdentityError('No exp field in token: %s' % json_body)
374373
if exp >= now + MAX_TOKEN_LIFETIME_SECS:
375-
raise AppIdentityError(
376-
'exp field too far in future: %s' % json_body)
374+
raise AppIdentityError('exp field too far in future: %s' % json_body)
377375
latest = exp + CLOCK_SKEW_SECS
378376

379377
if now < earliest:
380378
raise AppIdentityError('Token used too early, %d < %d: %s' %
381-
(now, earliest, json_body))
379+
(now, earliest, json_body))
382380
if now > latest:
383381
raise AppIdentityError('Token used too late, %d > %d: %s' %
384-
(now, latest, json_body))
382+
(now, latest, json_body))
385383

386384
# Check audience.
387385
if audience is not None:
@@ -390,6 +388,6 @@ def verify_signed_jwt_with_certs(jwt, certs, audience):
390388
raise AppIdentityError('No aud field in token: %s' % json_body)
391389
if aud != audience:
392390
raise AppIdentityError('Wrong recipient, %s != %s: %s' %
393-
(aud, audience, json_body))
391+
(aud, audience, json_body))
394392

395393
return parsed

oauth2client/file.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,10 @@
2121
__author__ = '[email protected] (Joe Gregorio)'
2222

2323
import os
24-
import stat
2524
import threading
2625

27-
from client import Storage as BaseStorage
28-
from client import Credentials
26+
from oauth2client.client import Storage as BaseStorage
27+
from oauth2client.client import Credentials
2928

3029

3130
class CredentialsFileSymbolicLinkError(Exception):

oauth2client/gce.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919

2020
__author__ = '[email protected] (Joe Gregorio)'
2121

22-
import httplib2
2322
import json
2423
import logging
2524
import uritemplate
@@ -90,7 +89,7 @@ def _refresh(self, http_request):
9089
else:
9190
if response.status == 404:
9291
content = content + (' This can occur if a VM was created'
93-
' with no service account or scopes.')
92+
' with no service account or scopes.')
9493
raise AccessTokenRefreshError(content)
9594

9695
@property

oauth2client/keyring_storage.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
import keyring
2323
import threading
2424

25-
from client import Storage as BaseStorage
26-
from client import Credentials
25+
from oauth2client.client import Storage as BaseStorage
26+
from oauth2client.client import Credentials
2727

2828

2929
class Storage(BaseStorage):

oauth2client/locked_file.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ def __init__(self, filename, mode, fallback_mode):
7070
self._mode = mode
7171
self._fallback_mode = fallback_mode
7272
self._fh = None
73+
self._lock_fd = None
7374

7475
def is_locked(self):
7576
"""Was the file locked."""
@@ -141,8 +142,8 @@ def open_and_lock(self, timeout, delay):
141142
if e.errno != errno.EEXIST:
142143
raise
143144
if (time.time() - start_time) >= timeout:
144-
logger.warn('Could not acquire lock %s in %s seconds' % (
145-
lock_filename, timeout))
145+
logger.warn('Could not acquire lock %s in %s seconds',
146+
lock_filename, timeout)
146147
# Close the file and open in fallback_mode.
147148
if self._fh:
148149
self._fh.close()
@@ -194,7 +195,7 @@ def open_and_lock(self, timeout, delay):
194195
self._fh = open(self._filename, self._mode)
195196
except IOError as e:
196197
# If we can't access with _mode, try _fallback_mode and don't lock.
197-
if e.errno in ( errno.EPERM, errno.EACCES ):
198+
if e.errno in (errno.EPERM, errno.EACCES):
198199
self._fh = open(self._filename, self._fallback_mode)
199200
return
200201

@@ -212,8 +213,8 @@ def open_and_lock(self, timeout, delay):
212213
raise e
213214
# We could not acquire the lock. Try again.
214215
if (time.time() - start_time) >= timeout:
215-
logger.warn('Could not lock %s in %s seconds' % (
216-
self._filename, timeout))
216+
logger.warn('Could not lock %s in %s seconds',
217+
self._filename, timeout)
217218
if self._fh:
218219
self._fh.close()
219220
self._fh = open(self._filename, self._fallback_mode)

oauth2client/multistore_file.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,6 @@
4343

4444
__author__ = '[email protected] (Joe Beda)'
4545

46-
import base64
47-
import errno
4846
import json
4947
import logging
5048
import os
@@ -53,7 +51,7 @@
5351
from oauth2client.client import Storage as BaseStorage
5452
from oauth2client.client import Credentials
5553
from oauth2client import util
56-
from locked_file import LockedFile
54+
from oauth2client.locked_file import LockedFile
5755

5856
logger = logging.getLogger(__name__)
5957

@@ -286,7 +284,7 @@ def _lock(self):
286284
if self._warn_on_readonly:
287285
logger.warn('The credentials file (%s) is not writable. Opening in '
288286
'read-only mode. Any refreshed credentials will only be '
289-
'valid for this run.' % self._file.filename())
287+
'valid for this run.', self._file.filename())
290288
if os.path.getsize(self._file.filename()) == 0:
291289
logger.debug('Initializing empty multistore file')
292290
# The multistore is empty so write out an empty file.

oauth2client/service_account.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@
1919

2020
import base64
2121
import json
22-
import rsa
2322
import time
24-
import types
2523

2624
from oauth2client import GOOGLE_REVOKE_URI
2725
from oauth2client import GOOGLE_TOKEN_URI
@@ -30,6 +28,7 @@
3028

3129
from pyasn1.codec.ber import decoder
3230
from pyasn1_modules.rfc5208 import PrivateKeyInfo
31+
import rsa
3332

3433

3534
class _ServiceAccountCredentials(AssertionCredentials):
@@ -38,8 +37,9 @@ class _ServiceAccountCredentials(AssertionCredentials):
3837
MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
3938

4039
def __init__(self, service_account_id, service_account_email, private_key_id,
41-
private_key_pkcs8_text, scopes, user_agent=None,
42-
token_uri=GOOGLE_TOKEN_URI, revoke_uri=GOOGLE_REVOKE_URI, **kwargs):
40+
private_key_pkcs8_text, scopes, user_agent=None,
41+
token_uri=GOOGLE_TOKEN_URI, revoke_uri=GOOGLE_REVOKE_URI,
42+
**kwargs):
4343

4444
super(_ServiceAccountCredentials, self).__init__(
4545
None, user_agent=user_agent, token_uri=token_uri, revoke_uri=revoke_uri)

oauth2client/tools.py

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,15 @@
2525

2626
import BaseHTTPServer
2727
import argparse
28-
import httplib2
2928
import logging
30-
import os
3129
import socket
3230
import sys
31+
import urlparse
3332
import webbrowser
3433

3534
from oauth2client import client
36-
from oauth2client import file
3735
from oauth2client import util
3836

39-
try:
40-
from urlparse import parse_qsl
41-
except ImportError:
42-
from cgi import parse_qsl
43-
4437
_CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0
4538
4639
To make this sample run you will need to populate the client_secrets.json file
@@ -57,15 +50,15 @@
5750
# ArgumentParser.
5851
argparser = argparse.ArgumentParser(add_help=False)
5952
argparser.add_argument('--auth_host_name', default='localhost',
60-
help='Hostname when running a local web server.')
53+
help='Hostname when running a local web server.')
6154
argparser.add_argument('--noauth_local_webserver', action='store_true',
62-
default=False, help='Do not run a local web server.')
55+
default=False, help='Do not run a local web server.')
6356
argparser.add_argument('--auth_host_port', default=[8080, 8090], type=int,
64-
nargs='*', help='Port web server should listen on.')
57+
nargs='*', help='Port web server should listen on.')
6558
argparser.add_argument('--logging_level', default='ERROR',
66-
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR',
67-
'CRITICAL'],
68-
help='Set the logging level of detail.')
59+
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR',
60+
'CRITICAL'],
61+
help='Set the logging level of detail.')
6962

7063

7164
class ClientRedirectServer(BaseHTTPServer.HTTPServer):
@@ -84,26 +77,25 @@ class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
8477
into the servers query_params and then stops serving.
8578
"""
8679

87-
def do_GET(s):
80+
def do_GET(self):
8881
"""Handle a GET request.
8982
9083
Parses the query parameters and prints a message
9184
if the flow has completed. Note that we can't detect
9285
if an error occurred.
9386
"""
94-
s.send_response(200)
95-
s.send_header("Content-type", "text/html")
96-
s.end_headers()
97-
query = s.path.split('?', 1)[-1]
98-
query = dict(parse_qsl(query))
99-
s.server.query_params = query
100-
s.wfile.write("<html><head><title>Authentication Status</title></head>")
101-
s.wfile.write("<body><p>The authentication flow has completed.</p>")
102-
s.wfile.write("</body></html>")
87+
self.send_response(200)
88+
self.send_header("Content-type", "text/html")
89+
self.end_headers()
90+
query = self.path.split('?', 1)[-1]
91+
query = dict(urlparse.parse_qsl(query))
92+
self.server.query_params = query
93+
self.wfile.write("<html><head><title>Authentication Status</title></head>")
94+
self.wfile.write("<body><p>The authentication flow has completed.</p>")
95+
self.wfile.write("</body></html>")
10396

10497
def log_message(self, format, *args):
10598
"""Do not log messages to stdout while running as command line program."""
106-
pass
10799

108100

109101
@util.positional(3)
@@ -233,8 +225,8 @@ def message_if_missing(filename):
233225
return _CLIENT_SECRETS_MESSAGE % filename
234226

235227
try:
236-
from old_run import run
237-
from old_run import FLAGS
228+
from oauth2client.old_run import run
229+
from oauth2client.old_run import FLAGS
238230
except ImportError:
239231
def run(*args, **kwargs):
240232
raise NotImplementedError(

0 commit comments

Comments
 (0)