Skip to content
This repository has been archived by the owner on Nov 5, 2019. It is now read-only.

Commit

Permalink
Update string formatters to new style
Browse files Browse the repository at this point in the history
Changing `%` style string formatters to `.format()`.
Leaving `logging` strings in old style for Python 2 compatibility.

Resolves: Issue #541
  • Loading branch information
pferate committed Jul 18, 2016
1 parent cd635f4 commit cd198d6
Show file tree
Hide file tree
Showing 20 changed files with 114 additions and 103 deletions.
4 changes: 2 additions & 2 deletions oauth2client/_helpers.py
Expand Up @@ -68,7 +68,7 @@ def _to_bytes(value, encoding='ascii'):
if isinstance(result, six.binary_type):
return result
else:
raise ValueError('%r could not be converted to bytes' % (value,))
raise ValueError('{0!r} could not be converted to bytes'.format(value))


def _from_bytes(value):
Expand All @@ -89,7 +89,7 @@ def _from_bytes(value):
if isinstance(result, six.text_type):
return result
else:
raise ValueError('%r could not be converted to unicode' % (value,))
raise ValueError('{0!r} could not be converted to unicode'.format(value))


def _urlsafe_b64encode(raw_bytes):
Expand Down
25 changes: 13 additions & 12 deletions oauth2client/client.py
Expand Up @@ -927,7 +927,7 @@ def _do_refresh_request(self, http_request):
# An {'error':...} response body means the token is expired or
# revoked, so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s', content)
error_msg = 'Invalid response %s.' % (resp['status'],)
error_msg = 'Invalid response {0}.'.format(resp['status'])
try:
d = json.loads(content)
if 'error' in d:
Expand Down Expand Up @@ -972,7 +972,7 @@ def _do_revoke(self, http_request, token):
if resp.status == http_client.OK:
self.invalid = True
else:
error_msg = 'Invalid response %s.' % resp.status
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
d = json.loads(_from_bytes(content))
if 'error' in d:
Expand Down Expand Up @@ -1018,7 +1018,7 @@ def _do_retrieve_scopes(self, http_request, token):
d = json.loads(content)
self.scopes = set(util.string_to_scopes(d.get('scope', '')))
else:
error_msg = 'Invalid response %s.' % (resp.status,)
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
d = json.loads(content)
if 'error_description' in d:
Expand Down Expand Up @@ -1459,7 +1459,8 @@ def save_to_well_known_file(credentials, well_known_file=None):

config_dir = os.path.dirname(well_known_file)
if not os.path.isdir(config_dir):
raise OSError('Config directory does not exist: %s' % config_dir)
raise OSError(
'Config directory does not exist: {0}'.format(config_dir))

credentials_data = credentials.serialization_data
_save_private_file(well_known_file, credentials_data)
Expand Down Expand Up @@ -1690,7 +1691,7 @@ def verify_id_token(id_token, audience, http=None,
certs = json.loads(_from_bytes(content))
return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
else:
raise VerifyJwtTokenError('Status code: %d' % resp.status)
raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))


def _extract_id_token(id_token):
Expand All @@ -1711,7 +1712,7 @@ def _extract_id_token(id_token):

if len(segments) != 3:
raise VerifyJwtTokenError(
'Wrong number of segments in token: %s' % id_token)
'Wrong number of segments in token: {0}'.format(id_token))

return json.loads(_from_bytes(_urlsafe_b64decode(segments[1])))

Expand Down Expand Up @@ -2036,15 +2037,15 @@ def step1_get_device_and_user_codes(self, http=None):
flow_info = json.loads(content)
except ValueError as exc:
raise OAuth2DeviceCodeError(
'Could not parse server response as JSON: "%s", '
'error: "%s"' % (content, exc))
'Could not parse server response as JSON: "{0}", '
'error: "{1}"'.format(content, exc))
return DeviceFlowInfo.FromResponse(flow_info)
else:
error_msg = 'Invalid response %s.' % (resp.status,)
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
error_dict = json.loads(content)
if 'error' in error_dict:
error_msg += ' Error: %s' % (error_dict['error'],)
error_msg += ' Error: {0}'.format(error_dict['error'])
except ValueError:
# Couldn't decode a JSON response, stick with the
# default message.
Expand Down Expand Up @@ -2144,7 +2145,7 @@ def step2_exchange(self, code=None, http=None, device_flow_info=None):
error_msg = (str(d['error']) +
str(d.get('error_description', '')))
else:
error_msg = 'Invalid response: %s.' % str(resp.status)
error_msg = 'Invalid response: {0}.'.format(str(resp.status))
raise FlowExchangeError(error_msg)


Expand Down Expand Up @@ -2218,4 +2219,4 @@ def flow_from_clientsecrets(filename, scope, redirect_uri=None,
raise
else:
raise UnknownClientSecretsFlowError(
'This OAuth 2.0 flow is unsupported: %r' % (client_type,))
'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))
8 changes: 4 additions & 4 deletions oauth2client/clientsecrets.py
Expand Up @@ -93,17 +93,17 @@ def _validate_clientsecrets(clientsecrets_dict):

if client_type not in VALID_CLIENT:
raise InvalidClientSecretsError(
'Unknown client type: %s.' % (client_type,))
'Unknown client type: {0}.'.format(client_type))

for prop_name in VALID_CLIENT[client_type]['required']:
if prop_name not in client_info:
raise InvalidClientSecretsError(
'Missing property "%s" in a client type of "%s".' %
(prop_name, client_type))
'Missing property "{0}" in a client type of "{1}".'.format(
prop_name, client_type))
for prop_name in VALID_CLIENT[client_type]['string']:
if client_info[prop_name].startswith('[['):
raise InvalidClientSecretsError(
'Property "%s" is not configured.' % prop_name)
'Property "{0}" is not configured.'.format(prop_name))
return client_type, client_info


Expand Down
12 changes: 6 additions & 6 deletions oauth2client/contrib/_appengine_ndb.py
Expand Up @@ -76,9 +76,9 @@ def _validate(self, value):
"""
_LOGGER.info('validate: Got type %s', type(value))
if value is not None and not isinstance(value, client.Flow):
raise TypeError('Property %s must be convertible to a flow '
'instance; received: %s.' % (self._name,
value))
raise TypeError(
'Property {0} must be convertible to a flow '
'instance; received: {1}.'.format(self._name, value))


class CredentialsNDBProperty(ndb.BlobProperty):
Expand All @@ -104,9 +104,9 @@ def _validate(self, value):
"""
_LOGGER.info('validate: Got type %s', type(value))
if value is not None and not isinstance(value, client.Credentials):
raise TypeError('Property %s must be convertible to a '
'credentials instance; received: %s.' %
(self._name, value))
raise TypeError(
'Property {0} must be convertible to a credentials '
'instance; received: {1}.'.format(self._name, value))

def _to_base_type(self, value):
"""Converts our validated value to a JSON serialized string.
Expand Down
4 changes: 2 additions & 2 deletions oauth2client/contrib/_fcntl_opener.py
Expand Up @@ -39,8 +39,8 @@ def open_and_lock(self, timeout, delay):
link.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
raise AlreadyLockedException(
'File {0} is already locked'.format(self._filename))
start_time = time.time()

validate_file(self._filename)
Expand Down
8 changes: 4 additions & 4 deletions oauth2client/contrib/_win32_opener.py
Expand Up @@ -50,8 +50,8 @@ def open_and_lock(self, timeout, delay):
link.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
raise AlreadyLockedException('File {0} is already locked'.format(
self._filename))
start_time = time.time()

validate_file(self._filename)
Expand Down Expand Up @@ -86,8 +86,8 @@ def open_and_lock(self, timeout, delay):

# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
logger.warn('Could not lock %s in %s seconds',
self._filename, timeout)
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
Expand Down
20 changes: 10 additions & 10 deletions oauth2client/contrib/appengine.py
Expand Up @@ -251,9 +251,9 @@ def make_value_from_datastore(self, value):

def validate(self, value):
if value is not None and not isinstance(value, Flow):
raise db.BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
raise db.BadValueError(
'Property {0} must be convertible '
'to a FlowThreeLegged instance ({1})'.format(self.name, value))
return super(FlowProperty, self).validate(value)

def empty(self, value):
Expand Down Expand Up @@ -298,9 +298,9 @@ def validate(self, value):
value = super(CredentialsProperty, self).validate(value)
logger.info("validate: Got type " + str(type(value)))
if value is not None and not isinstance(value, Credentials):
raise db.BadValueError('Property %s must be convertible '
'to a Credentials instance (%s)' %
(self.name, value))
raise db.BadValueError(
'Property {0} must be convertible '
'to a Credentials instance ({1})'.format(self.name, value))
return value


Expand Down Expand Up @@ -356,8 +356,8 @@ def _is_ndb(self):
elif issubclass(self._model, db.Model):
return False

raise TypeError('Model class not an NDB or DB model: %s.' %
(self._model,))
raise TypeError('Model class not an NDB or DB model: {0}.'.format(
self._model))

def _get_entity(self):
"""Retrieve entity from datastore.
Expand Down Expand Up @@ -790,8 +790,8 @@ def get(self):
if error:
errormsg = self.request.get('error_description', error)
self.response.out.write(
'The authorization request failed: %s' %
_safe_html(errormsg))
'The authorization request failed: {0}'.format(
_safe_html(errormsg)))
else:
user = users.get_current_user()
decorator._create_flow(self)
Expand Down
2 changes: 1 addition & 1 deletion oauth2client/contrib/devshell.py
Expand Up @@ -83,7 +83,7 @@ def _SendRecv():
sock.connect(('localhost', port))

data = CREDENTIAL_INFO_REQUEST_JSON
msg = '%s\n%s' % (len(data), data)
msg = '{0}\n{1}'.format(len(data), data)
sock.sendall(_to_bytes(msg, encoding='utf-8'))

header = sock.recv(6).decode()
Expand Down
17 changes: 9 additions & 8 deletions oauth2client/contrib/django_util/__init__.py
Expand Up @@ -106,7 +106,7 @@ def requires_default_scopes(request):
http=request.oauth.http,
developerKey=API_KEY)
events = service.events().list(calendarId='primary').execute()['items']
return HttpResponse("email: %s , calendar: %s" % (email, str(events)))
return HttpResponse("email: {0} , calendar: {1}".format(email, str(events)))
To make OAuth2 optional and provide an authorization link in your own views.
Expand All @@ -121,12 +121,12 @@ def optional_oauth2(request):
if request.oauth.has_credentials():
# this could be passed into a view
# request.oauth.http is also initialized
return HttpResponse("User email: %s"
% request.oauth.credentials.id_token['email'])
return HttpResponse("User email: {0}".format(
request.oauth.credentials.id_token['email']))
else:
return HttpResponse(
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
% request.oauth.get_authorize_redirect())
'Here is an OAuth Authorize link: <a href="{0}">Authorize</a>'.format(
request.oauth.get_authorize_redirect()))
If a view needs a scope not included in the default scopes specified in
the settings, you can use [incremental auth](https://developers.google.com/identity/sign-in/web/incremental-auth)
Expand All @@ -146,8 +146,8 @@ def drive_required(request):
return HttpResponse(str(events))
else:
return HttpResponse(
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
% request.oauth.get_authorize_redirect())
'Here is an OAuth Authorize link: <a href="{0}">Authorize</a>'.format(
request.oauth.get_authorize_redirect()))
To provide a callback on authorization being completed, use the
Expand All @@ -160,7 +160,8 @@ def drive_required(request):
from oauth2client.contrib.django_util.signals import oauth2_authorized
def test_callback(sender, request, credentials, **kwargs):
print "Authorization Signal Received %s" % credentials.id_token['email']
print("Authorization Signal Received {0}".format(
credentials.id_token['email']))
oauth2_authorized.connect(test_callback)
Expand Down
10 changes: 5 additions & 5 deletions oauth2client/contrib/django_util/decorators.py
Expand Up @@ -37,7 +37,7 @@ def requires_default_scopes(request):
developerKey=API_KEY)
events = service.events().list(
calendarId='primary').execute()['items']
return HttpResponse("email: %s, calendar: %s" % (email, str(events)))
return HttpResponse("email: {0}, calendar: {1}".format(email, str(events)))
:param decorated_function: View function to decorate, must have the Django
request object as the first argument
Expand Down Expand Up @@ -85,12 +85,12 @@ def optional_oauth2(request):
if request.oauth.has_credentials():
# this could be passed into a view
# request.oauth.http is also initialized
return HttpResponse("User email: %s" %
request.oauth.credentials.id_token['email'])
return HttpResponse("User email: {0}".format(
request.oauth.credentials.id_token['email']))
else:
return HttpResponse('Here is an OAuth Authorize link:
<a href="%s">Authorize</a>' %
request.oauth.get_authorize_redirect())
<a href="{0}">Authorize</a>'.format(
request.oauth.get_authorize_redirect()))
:param decorated_function: View function to decorate
Expand Down
2 changes: 1 addition & 1 deletion oauth2client/contrib/django_util/views.py
Expand Up @@ -77,7 +77,7 @@ def oauth2_callback(request):
reason = request.GET.get(
'error_description', request.GET.get('error', ''))
return http.HttpResponseBadRequest(
'Authorization failed %s' % reason)
'Authorization failed {0}'.format(reason))

try:
encoded_state = request.GET['state']
Expand Down
8 changes: 4 additions & 4 deletions oauth2client/contrib/locked_file.py
Expand Up @@ -57,7 +57,7 @@ class AlreadyLockedException(Exception):
def validate_file(filename):
if os.path.islink(filename):
raise CredentialsFileSymbolicLinkError(
'File: %s is a symbolic link.' % filename)
'File: {0} is a symbolic link.'.format(filename))


class _Opener(object):
Expand Down Expand Up @@ -122,8 +122,8 @@ def open_and_lock(self, timeout, delay):
CredentialsFileSymbolicLinkError if the file is a symbolic link.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
raise AlreadyLockedException('File {0} is already locked'.format(
self._filename))
self._locked = False

validate_file(self._filename)
Expand Down Expand Up @@ -170,7 +170,7 @@ def unlock_and_close(self):

def _posix_lockfile(self, filename):
"""The name of the lock file to use for posix locking."""
return '%s.lock' % filename
return '{0}.lock'.format(filename)


class LockedFile(object):
Expand Down
4 changes: 2 additions & 2 deletions oauth2client/contrib/multistore_file.py
Expand Up @@ -390,8 +390,8 @@ def _refresh_data_cache(self):
'corrupt or an old version. Overwriting.')
if version > 1:
raise NewerCredentialStoreError(
'Credential file has file_version of %d. '
'Only file_version of 1 is supported.' % version)
'Credential file has file_version of {0}. '
'Only file_version of 1 is supported.'.format(version))

credentials = []
try:
Expand Down

0 comments on commit cd198d6

Please sign in to comment.