Update string formatters to new style
Changing `%` style string formatters to `.format()`. Leaving `logging` strings in old style for Python 2 compatibility. Resolves: Issue #541
This commit is contained in:
@@ -68,7 +68,7 @@ def _to_bytes(value, encoding='ascii'):
|
|||||||
if isinstance(result, six.binary_type):
|
if isinstance(result, six.binary_type):
|
||||||
return result
|
return result
|
||||||
else:
|
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):
|
def _from_bytes(value):
|
||||||
@@ -89,7 +89,8 @@ def _from_bytes(value):
|
|||||||
if isinstance(result, six.text_type):
|
if isinstance(result, six.text_type):
|
||||||
return result
|
return result
|
||||||
else:
|
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):
|
def _urlsafe_b64encode(raw_bytes):
|
||||||
|
|||||||
@@ -927,7 +927,7 @@ class OAuth2Credentials(Credentials):
|
|||||||
# An {'error':...} response body means the token is expired or
|
# An {'error':...} response body means the token is expired or
|
||||||
# revoked, so we flag the credentials as such.
|
# revoked, so we flag the credentials as such.
|
||||||
logger.info('Failed to retrieve access token: %s', content)
|
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:
|
try:
|
||||||
d = json.loads(content)
|
d = json.loads(content)
|
||||||
if 'error' in d:
|
if 'error' in d:
|
||||||
@@ -972,7 +972,7 @@ class OAuth2Credentials(Credentials):
|
|||||||
if resp.status == http_client.OK:
|
if resp.status == http_client.OK:
|
||||||
self.invalid = True
|
self.invalid = True
|
||||||
else:
|
else:
|
||||||
error_msg = 'Invalid response %s.' % resp.status
|
error_msg = 'Invalid response {0}.'.format(resp.status)
|
||||||
try:
|
try:
|
||||||
d = json.loads(_from_bytes(content))
|
d = json.loads(_from_bytes(content))
|
||||||
if 'error' in d:
|
if 'error' in d:
|
||||||
@@ -1018,7 +1018,7 @@ class OAuth2Credentials(Credentials):
|
|||||||
d = json.loads(content)
|
d = json.loads(content)
|
||||||
self.scopes = set(util.string_to_scopes(d.get('scope', '')))
|
self.scopes = set(util.string_to_scopes(d.get('scope', '')))
|
||||||
else:
|
else:
|
||||||
error_msg = 'Invalid response %s.' % (resp.status,)
|
error_msg = 'Invalid response {0}.'.format(resp.status)
|
||||||
try:
|
try:
|
||||||
d = json.loads(content)
|
d = json.loads(content)
|
||||||
if 'error_description' in d:
|
if 'error_description' in d:
|
||||||
@@ -1459,7 +1459,8 @@ def save_to_well_known_file(credentials, well_known_file=None):
|
|||||||
|
|
||||||
config_dir = os.path.dirname(well_known_file)
|
config_dir = os.path.dirname(well_known_file)
|
||||||
if not os.path.isdir(config_dir):
|
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
|
credentials_data = credentials.serialization_data
|
||||||
_save_private_file(well_known_file, credentials_data)
|
_save_private_file(well_known_file, credentials_data)
|
||||||
@@ -1690,7 +1691,7 @@ def verify_id_token(id_token, audience, http=None,
|
|||||||
certs = json.loads(_from_bytes(content))
|
certs = json.loads(_from_bytes(content))
|
||||||
return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
|
return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
|
||||||
else:
|
else:
|
||||||
raise VerifyJwtTokenError('Status code: %d' % resp.status)
|
raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))
|
||||||
|
|
||||||
|
|
||||||
def _extract_id_token(id_token):
|
def _extract_id_token(id_token):
|
||||||
@@ -1711,7 +1712,7 @@ def _extract_id_token(id_token):
|
|||||||
|
|
||||||
if len(segments) != 3:
|
if len(segments) != 3:
|
||||||
raise VerifyJwtTokenError(
|
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])))
|
return json.loads(_from_bytes(_urlsafe_b64decode(segments[1])))
|
||||||
|
|
||||||
@@ -2036,15 +2037,15 @@ class OAuth2WebServerFlow(Flow):
|
|||||||
flow_info = json.loads(content)
|
flow_info = json.loads(content)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise OAuth2DeviceCodeError(
|
raise OAuth2DeviceCodeError(
|
||||||
'Could not parse server response as JSON: "%s", '
|
'Could not parse server response as JSON: "{0}", '
|
||||||
'error: "%s"' % (content, exc))
|
'error: "{1}"'.format(content, exc))
|
||||||
return DeviceFlowInfo.FromResponse(flow_info)
|
return DeviceFlowInfo.FromResponse(flow_info)
|
||||||
else:
|
else:
|
||||||
error_msg = 'Invalid response %s.' % (resp.status,)
|
error_msg = 'Invalid response {0}.'.format(resp.status)
|
||||||
try:
|
try:
|
||||||
error_dict = json.loads(content)
|
error_dict = json.loads(content)
|
||||||
if 'error' in error_dict:
|
if 'error' in error_dict:
|
||||||
error_msg += ' Error: %s' % (error_dict['error'],)
|
error_msg += ' Error: {0}'.format(error_dict['error'])
|
||||||
except ValueError:
|
except ValueError:
|
||||||
# Couldn't decode a JSON response, stick with the
|
# Couldn't decode a JSON response, stick with the
|
||||||
# default message.
|
# default message.
|
||||||
@@ -2144,7 +2145,7 @@ class OAuth2WebServerFlow(Flow):
|
|||||||
error_msg = (str(d['error']) +
|
error_msg = (str(d['error']) +
|
||||||
str(d.get('error_description', '')))
|
str(d.get('error_description', '')))
|
||||||
else:
|
else:
|
||||||
error_msg = 'Invalid response: %s.' % str(resp.status)
|
error_msg = 'Invalid response: {0}.'.format(str(resp.status))
|
||||||
raise FlowExchangeError(error_msg)
|
raise FlowExchangeError(error_msg)
|
||||||
|
|
||||||
|
|
||||||
@@ -2218,4 +2219,4 @@ def flow_from_clientsecrets(filename, scope, redirect_uri=None,
|
|||||||
raise
|
raise
|
||||||
else:
|
else:
|
||||||
raise UnknownClientSecretsFlowError(
|
raise UnknownClientSecretsFlowError(
|
||||||
'This OAuth 2.0 flow is unsupported: %r' % (client_type,))
|
'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))
|
||||||
|
|||||||
@@ -93,17 +93,17 @@ def _validate_clientsecrets(clientsecrets_dict):
|
|||||||
|
|
||||||
if client_type not in VALID_CLIENT:
|
if client_type not in VALID_CLIENT:
|
||||||
raise InvalidClientSecretsError(
|
raise InvalidClientSecretsError(
|
||||||
'Unknown client type: %s.' % (client_type,))
|
'Unknown client type: {0}.'.format(client_type))
|
||||||
|
|
||||||
for prop_name in VALID_CLIENT[client_type]['required']:
|
for prop_name in VALID_CLIENT[client_type]['required']:
|
||||||
if prop_name not in client_info:
|
if prop_name not in client_info:
|
||||||
raise InvalidClientSecretsError(
|
raise InvalidClientSecretsError(
|
||||||
'Missing property "%s" in a client type of "%s".' %
|
'Missing property "{0}" in a client type of "{1}".'.format(
|
||||||
(prop_name, client_type))
|
prop_name, client_type))
|
||||||
for prop_name in VALID_CLIENT[client_type]['string']:
|
for prop_name in VALID_CLIENT[client_type]['string']:
|
||||||
if client_info[prop_name].startswith('[['):
|
if client_info[prop_name].startswith('[['):
|
||||||
raise InvalidClientSecretsError(
|
raise InvalidClientSecretsError(
|
||||||
'Property "%s" is not configured.' % prop_name)
|
'Property "{0}" is not configured.'.format(prop_name))
|
||||||
return client_type, client_info
|
return client_type, client_info
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -76,9 +76,9 @@ class FlowNDBProperty(ndb.PickleProperty):
|
|||||||
"""
|
"""
|
||||||
_LOGGER.info('validate: Got type %s', type(value))
|
_LOGGER.info('validate: Got type %s', type(value))
|
||||||
if value is not None and not isinstance(value, client.Flow):
|
if value is not None and not isinstance(value, client.Flow):
|
||||||
raise TypeError('Property %s must be convertible to a flow '
|
raise TypeError(
|
||||||
'instance; received: %s.' % (self._name,
|
'Property {0} must be convertible to a flow '
|
||||||
value))
|
'instance; received: {1}.'.format(self._name, value))
|
||||||
|
|
||||||
|
|
||||||
class CredentialsNDBProperty(ndb.BlobProperty):
|
class CredentialsNDBProperty(ndb.BlobProperty):
|
||||||
@@ -104,9 +104,9 @@ class CredentialsNDBProperty(ndb.BlobProperty):
|
|||||||
"""
|
"""
|
||||||
_LOGGER.info('validate: Got type %s', type(value))
|
_LOGGER.info('validate: Got type %s', type(value))
|
||||||
if value is not None and not isinstance(value, client.Credentials):
|
if value is not None and not isinstance(value, client.Credentials):
|
||||||
raise TypeError('Property %s must be convertible to a '
|
raise TypeError(
|
||||||
'credentials instance; received: %s.' %
|
'Property {0} must be convertible to a credentials '
|
||||||
(self._name, value))
|
'instance; received: {1}.'.format(self._name, value))
|
||||||
|
|
||||||
def _to_base_type(self, value):
|
def _to_base_type(self, value):
|
||||||
"""Converts our validated value to a JSON serialized string.
|
"""Converts our validated value to a JSON serialized string.
|
||||||
|
|||||||
@@ -39,8 +39,8 @@ class _FcntlOpener(_Opener):
|
|||||||
link.
|
link.
|
||||||
"""
|
"""
|
||||||
if self._locked:
|
if self._locked:
|
||||||
raise AlreadyLockedException('File %s is already locked' %
|
raise AlreadyLockedException(
|
||||||
self._filename)
|
'File {0} is already locked'.format(self._filename))
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
|
||||||
validate_file(self._filename)
|
validate_file(self._filename)
|
||||||
|
|||||||
@@ -50,8 +50,8 @@ class _Win32Opener(_Opener):
|
|||||||
link.
|
link.
|
||||||
"""
|
"""
|
||||||
if self._locked:
|
if self._locked:
|
||||||
raise AlreadyLockedException('File %s is already locked' %
|
raise AlreadyLockedException(
|
||||||
self._filename)
|
'File {0} is already locked'.format(self._filename))
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
|
||||||
validate_file(self._filename)
|
validate_file(self._filename)
|
||||||
@@ -86,8 +86,8 @@ class _Win32Opener(_Opener):
|
|||||||
|
|
||||||
# We could not acquire the lock. Try again.
|
# We could not acquire the lock. Try again.
|
||||||
if (time.time() - start_time) >= timeout:
|
if (time.time() - start_time) >= timeout:
|
||||||
logger.warn('Could not lock %s in %s seconds' % (
|
logger.warn('Could not lock %s in %s seconds',
|
||||||
self._filename, timeout))
|
self._filename, timeout)
|
||||||
if self._fh:
|
if self._fh:
|
||||||
self._fh.close()
|
self._fh.close()
|
||||||
self._fh = open(self._filename, self._fallback_mode)
|
self._fh = open(self._filename, self._fallback_mode)
|
||||||
|
|||||||
@@ -251,9 +251,9 @@ class FlowProperty(db.Property):
|
|||||||
|
|
||||||
def validate(self, value):
|
def validate(self, value):
|
||||||
if value is not None and not isinstance(value, Flow):
|
if value is not None and not isinstance(value, Flow):
|
||||||
raise db.BadValueError('Property %s must be convertible '
|
raise db.BadValueError(
|
||||||
'to a FlowThreeLegged instance (%s)' %
|
'Property {0} must be convertible '
|
||||||
(self.name, value))
|
'to a FlowThreeLegged instance ({1})'.format(self.name, value))
|
||||||
return super(FlowProperty, self).validate(value)
|
return super(FlowProperty, self).validate(value)
|
||||||
|
|
||||||
def empty(self, value):
|
def empty(self, value):
|
||||||
@@ -298,9 +298,9 @@ class CredentialsProperty(db.Property):
|
|||||||
value = super(CredentialsProperty, self).validate(value)
|
value = super(CredentialsProperty, self).validate(value)
|
||||||
logger.info("validate: Got type " + str(type(value)))
|
logger.info("validate: Got type " + str(type(value)))
|
||||||
if value is not None and not isinstance(value, Credentials):
|
if value is not None and not isinstance(value, Credentials):
|
||||||
raise db.BadValueError('Property %s must be convertible '
|
raise db.BadValueError(
|
||||||
'to a Credentials instance (%s)' %
|
'Property {0} must be convertible '
|
||||||
(self.name, value))
|
'to a Credentials instance ({1})'.format(self.name, value))
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
@@ -356,8 +356,8 @@ class StorageByKeyName(Storage):
|
|||||||
elif issubclass(self._model, db.Model):
|
elif issubclass(self._model, db.Model):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
raise TypeError('Model class not an NDB or DB model: %s.' %
|
raise TypeError(
|
||||||
(self._model,))
|
'Model class not an NDB or DB model: {0}.'.format(self._model))
|
||||||
|
|
||||||
def _get_entity(self):
|
def _get_entity(self):
|
||||||
"""Retrieve entity from datastore.
|
"""Retrieve entity from datastore.
|
||||||
@@ -790,8 +790,8 @@ class OAuth2Decorator(object):
|
|||||||
if error:
|
if error:
|
||||||
errormsg = self.request.get('error_description', error)
|
errormsg = self.request.get('error_description', error)
|
||||||
self.response.out.write(
|
self.response.out.write(
|
||||||
'The authorization request failed: %s' %
|
'The authorization request failed: {0}'.format(
|
||||||
_safe_html(errormsg))
|
_safe_html(errormsg)))
|
||||||
else:
|
else:
|
||||||
user = users.get_current_user()
|
user = users.get_current_user()
|
||||||
decorator._create_flow(self)
|
decorator._create_flow(self)
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ def _SendRecv():
|
|||||||
sock.connect(('localhost', port))
|
sock.connect(('localhost', port))
|
||||||
|
|
||||||
data = CREDENTIAL_INFO_REQUEST_JSON
|
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'))
|
sock.sendall(_to_bytes(msg, encoding='utf-8'))
|
||||||
|
|
||||||
header = sock.recv(6).decode()
|
header = sock.recv(6).decode()
|
||||||
|
|||||||
@@ -106,7 +106,8 @@ request.oauth
|
|||||||
http=request.oauth.http,
|
http=request.oauth.http,
|
||||||
developerKey=API_KEY)
|
developerKey=API_KEY)
|
||||||
events = service.events().list(calendarId='primary').execute()['items']
|
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.
|
To make OAuth2 optional and provide an authorization link in your own views.
|
||||||
|
|
||||||
@@ -121,12 +122,12 @@ To make OAuth2 optional and provide an authorization link in your own views.
|
|||||||
if request.oauth.has_credentials():
|
if request.oauth.has_credentials():
|
||||||
# this could be passed into a view
|
# this could be passed into a view
|
||||||
# request.oauth.http is also initialized
|
# request.oauth.http is also initialized
|
||||||
return HttpResponse("User email: %s"
|
return HttpResponse("User email: {0}".format(
|
||||||
% request.oauth.credentials.id_token['email'])
|
request.oauth.credentials.id_token['email']))
|
||||||
else:
|
else:
|
||||||
return HttpResponse(
|
return HttpResponse(
|
||||||
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
|
'Here is an OAuth Authorize link: <a href="{0}">Authorize'
|
||||||
% request.oauth.get_authorize_redirect())
|
'</a>'.format(request.oauth.get_authorize_redirect()))
|
||||||
|
|
||||||
If a view needs a scope not included in the default scopes specified in
|
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)
|
the settings, you can use [incremental auth](https://developers.google.com/identity/sign-in/web/incremental-auth)
|
||||||
@@ -146,8 +147,8 @@ and specify additional scopes in the decorator arguments.
|
|||||||
return HttpResponse(str(events))
|
return HttpResponse(str(events))
|
||||||
else:
|
else:
|
||||||
return HttpResponse(
|
return HttpResponse(
|
||||||
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
|
'Here is an OAuth Authorize link: <a href="{0}">Authorize'
|
||||||
% request.oauth.get_authorize_redirect())
|
'</a>'.format(request.oauth.get_authorize_redirect()))
|
||||||
|
|
||||||
|
|
||||||
To provide a callback on authorization being completed, use the
|
To provide a callback on authorization being completed, use the
|
||||||
@@ -160,7 +161,8 @@ oauth2_authorized signal:
|
|||||||
from oauth2client.contrib.django_util.signals import oauth2_authorized
|
from oauth2client.contrib.django_util.signals import oauth2_authorized
|
||||||
|
|
||||||
def test_callback(sender, request, credentials, **kwargs):
|
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)
|
oauth2_authorized.connect(test_callback)
|
||||||
|
|
||||||
|
|||||||
@@ -37,7 +37,8 @@ def oauth_required(decorated_function=None, scopes=None, **decorator_kwargs):
|
|||||||
developerKey=API_KEY)
|
developerKey=API_KEY)
|
||||||
events = service.events().list(
|
events = service.events().list(
|
||||||
calendarId='primary').execute()['items']
|
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
|
:param decorated_function: View function to decorate, must have the Django
|
||||||
request object as the first argument
|
request object as the first argument
|
||||||
@@ -85,12 +86,12 @@ def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs):
|
|||||||
if request.oauth.has_credentials():
|
if request.oauth.has_credentials():
|
||||||
# this could be passed into a view
|
# this could be passed into a view
|
||||||
# request.oauth.http is also initialized
|
# request.oauth.http is also initialized
|
||||||
return HttpResponse("User email: %s" %
|
return HttpResponse("User email: {0}".format(
|
||||||
request.oauth.credentials.id_token['email'])
|
request.oauth.credentials.id_token['email']))
|
||||||
else:
|
else:
|
||||||
return HttpResponse('Here is an OAuth Authorize link:
|
return HttpResponse('Here is an OAuth Authorize link:
|
||||||
<a href="%s">Authorize</a>' %
|
<a href="{0}">Authorize</a>'.format(
|
||||||
request.oauth.get_authorize_redirect())
|
request.oauth.get_authorize_redirect()))
|
||||||
|
|
||||||
|
|
||||||
:param decorated_function: View function to decorate
|
:param decorated_function: View function to decorate
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ def oauth2_callback(request):
|
|||||||
reason = request.GET.get(
|
reason = request.GET.get(
|
||||||
'error_description', request.GET.get('error', ''))
|
'error_description', request.GET.get('error', ''))
|
||||||
return http.HttpResponseBadRequest(
|
return http.HttpResponseBadRequest(
|
||||||
'Authorization failed %s' % reason)
|
'Authorization failed {0}'.format(reason))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
encoded_state = request.GET['state']
|
encoded_state = request.GET['state']
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ class AlreadyLockedException(Exception):
|
|||||||
def validate_file(filename):
|
def validate_file(filename):
|
||||||
if os.path.islink(filename):
|
if os.path.islink(filename):
|
||||||
raise CredentialsFileSymbolicLinkError(
|
raise CredentialsFileSymbolicLinkError(
|
||||||
'File: %s is a symbolic link.' % filename)
|
'File: {0} is a symbolic link.'.format(filename))
|
||||||
|
|
||||||
|
|
||||||
class _Opener(object):
|
class _Opener(object):
|
||||||
@@ -122,8 +122,8 @@ class _PosixOpener(_Opener):
|
|||||||
CredentialsFileSymbolicLinkError if the file is a symbolic link.
|
CredentialsFileSymbolicLinkError if the file is a symbolic link.
|
||||||
"""
|
"""
|
||||||
if self._locked:
|
if self._locked:
|
||||||
raise AlreadyLockedException('File %s is already locked' %
|
raise AlreadyLockedException(
|
||||||
self._filename)
|
'File {0} is already locked'.format(self._filename))
|
||||||
self._locked = False
|
self._locked = False
|
||||||
|
|
||||||
validate_file(self._filename)
|
validate_file(self._filename)
|
||||||
@@ -170,7 +170,7 @@ class _PosixOpener(_Opener):
|
|||||||
|
|
||||||
def _posix_lockfile(self, filename):
|
def _posix_lockfile(self, filename):
|
||||||
"""The name of the lock file to use for posix locking."""
|
"""The name of the lock file to use for posix locking."""
|
||||||
return '%s.lock' % filename
|
return '{0}.lock'.format(filename)
|
||||||
|
|
||||||
|
|
||||||
class LockedFile(object):
|
class LockedFile(object):
|
||||||
|
|||||||
@@ -390,8 +390,8 @@ class _MultiStore(object):
|
|||||||
'corrupt or an old version. Overwriting.')
|
'corrupt or an old version. Overwriting.')
|
||||||
if version > 1:
|
if version > 1:
|
||||||
raise NewerCredentialStoreError(
|
raise NewerCredentialStoreError(
|
||||||
'Credential file has file_version of %d. '
|
'Credential file has file_version of {0}. '
|
||||||
'Only file_version of 1 is supported.' % version)
|
'Only file_version of 1 is supported.'.format(version))
|
||||||
|
|
||||||
credentials = []
|
credentials = []
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -144,11 +144,11 @@ def _check_audience(payload_dict, audience):
|
|||||||
|
|
||||||
audience_in_payload = payload_dict.get('aud')
|
audience_in_payload = payload_dict.get('aud')
|
||||||
if audience_in_payload is None:
|
if audience_in_payload is None:
|
||||||
raise AppIdentityError('No aud field in token: %s' %
|
raise AppIdentityError(
|
||||||
(payload_dict,))
|
'No aud field in token: {0}'.format(payload_dict))
|
||||||
if audience_in_payload != audience:
|
if audience_in_payload != audience:
|
||||||
raise AppIdentityError('Wrong recipient, %s != %s: %s' %
|
raise AppIdentityError('Wrong recipient, {0} != {1}: {2}'.format(
|
||||||
(audience_in_payload, audience, payload_dict))
|
audience_in_payload, audience, payload_dict))
|
||||||
|
|
||||||
|
|
||||||
def _verify_time_range(payload_dict):
|
def _verify_time_range(payload_dict):
|
||||||
@@ -180,26 +180,28 @@ def _verify_time_range(payload_dict):
|
|||||||
# Make sure issued at and expiration are in the payload.
|
# Make sure issued at and expiration are in the payload.
|
||||||
issued_at = payload_dict.get('iat')
|
issued_at = payload_dict.get('iat')
|
||||||
if issued_at is None:
|
if issued_at is None:
|
||||||
raise AppIdentityError('No iat field in token: %s' % (payload_dict,))
|
raise AppIdentityError(
|
||||||
|
'No iat field in token: {0}'.format(payload_dict))
|
||||||
expiration = payload_dict.get('exp')
|
expiration = payload_dict.get('exp')
|
||||||
if expiration is None:
|
if expiration is None:
|
||||||
raise AppIdentityError('No exp field in token: %s' % (payload_dict,))
|
raise AppIdentityError(
|
||||||
|
'No exp field in token: {0}'.format(payload_dict))
|
||||||
|
|
||||||
# Make sure the expiration gives an acceptable token lifetime.
|
# Make sure the expiration gives an acceptable token lifetime.
|
||||||
if expiration >= now + MAX_TOKEN_LIFETIME_SECS:
|
if expiration >= now + MAX_TOKEN_LIFETIME_SECS:
|
||||||
raise AppIdentityError('exp field too far in future: %s' %
|
raise AppIdentityError(
|
||||||
(payload_dict,))
|
'exp field too far in future: {0}'.format(payload_dict))
|
||||||
|
|
||||||
# Make sure (up to clock skew) that the token wasn't issued in the future.
|
# Make sure (up to clock skew) that the token wasn't issued in the future.
|
||||||
earliest = issued_at - CLOCK_SKEW_SECS
|
earliest = issued_at - CLOCK_SKEW_SECS
|
||||||
if now < earliest:
|
if now < earliest:
|
||||||
raise AppIdentityError('Token used too early, %d < %d: %s' %
|
raise AppIdentityError('Token used too early, {0} < {1}: {2}'.format(
|
||||||
(now, earliest, payload_dict))
|
now, earliest, payload_dict))
|
||||||
# Make sure (up to clock skew) that the token isn't already expired.
|
# Make sure (up to clock skew) that the token isn't already expired.
|
||||||
latest = expiration + CLOCK_SKEW_SECS
|
latest = expiration + CLOCK_SKEW_SECS
|
||||||
if now > latest:
|
if now > latest:
|
||||||
raise AppIdentityError('Token used too late, %d > %d: %s' %
|
raise AppIdentityError('Token used too late, {0} > {1}: {2}'.format(
|
||||||
(now, latest, payload_dict))
|
now, latest, payload_dict))
|
||||||
|
|
||||||
|
|
||||||
def verify_signed_jwt_with_certs(jwt, certs, audience=None):
|
def verify_signed_jwt_with_certs(jwt, certs, audience=None):
|
||||||
@@ -223,7 +225,7 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None):
|
|||||||
|
|
||||||
if jwt.count(b'.') != 2:
|
if jwt.count(b'.') != 2:
|
||||||
raise AppIdentityError(
|
raise AppIdentityError(
|
||||||
'Wrong number of segments in token: %s' % (jwt,))
|
'Wrong number of segments in token: {0}'.format(jwt))
|
||||||
|
|
||||||
header, payload, signature = jwt.split(b'.')
|
header, payload, signature = jwt.split(b'.')
|
||||||
message_to_sign = header + b'.' + payload
|
message_to_sign = header + b'.' + payload
|
||||||
@@ -234,7 +236,7 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None):
|
|||||||
try:
|
try:
|
||||||
payload_dict = json.loads(_from_bytes(payload_bytes))
|
payload_dict = json.loads(_from_bytes(payload_bytes))
|
||||||
except:
|
except:
|
||||||
raise AppIdentityError('Can\'t parse token: %s' % (payload_bytes,))
|
raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes))
|
||||||
|
|
||||||
# Verify that the signature matches the message.
|
# Verify that the signature matches the message.
|
||||||
_verify_signature(message_to_sign, signature, certs.values())
|
_verify_signature(message_to_sign, signature, certs.values())
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ class Storage(BaseStorage):
|
|||||||
def _validate_file(self):
|
def _validate_file(self):
|
||||||
if os.path.islink(self._filename):
|
if os.path.islink(self._filename):
|
||||||
raise CredentialsFileSymbolicLinkError(
|
raise CredentialsFileSymbolicLinkError(
|
||||||
'File: %s is a symbolic link.' % self._filename)
|
'File: {0} is a symbolic link.'.format(self._filename))
|
||||||
|
|
||||||
def locked_get(self):
|
def locked_get(self):
|
||||||
"""Retrieve Credential from file.
|
"""Retrieve Credential from file.
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ _CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0
|
|||||||
To make this sample run you will need to populate the client_secrets.json file
|
To make this sample run you will need to populate the client_secrets.json file
|
||||||
found at:
|
found at:
|
||||||
|
|
||||||
%s
|
{file_path}
|
||||||
|
|
||||||
with information from the APIs Console <https://code.google.com/apis/console>.
|
with information from the APIs Console <https://code.google.com/apis/console>.
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ authorization.
|
|||||||
_BROWSER_OPENED_MESSAGE = """
|
_BROWSER_OPENED_MESSAGE = """
|
||||||
Your browser has been opened to visit:
|
Your browser has been opened to visit:
|
||||||
|
|
||||||
%s
|
{address}
|
||||||
|
|
||||||
If your browser is on a different machine then exit and re-run this
|
If your browser is on a different machine then exit and re-run this
|
||||||
application with the command-line parameter
|
application with the command-line parameter
|
||||||
@@ -71,7 +71,7 @@ application with the command-line parameter
|
|||||||
_GO_TO_LINK_MESSAGE = """
|
_GO_TO_LINK_MESSAGE = """
|
||||||
Go to the following link in your browser:
|
Go to the following link in your browser:
|
||||||
|
|
||||||
%s
|
{address}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -211,7 +211,8 @@ def run_flow(flow, storage, flags=None, http=None):
|
|||||||
print(_FAILED_START_MESSAGE)
|
print(_FAILED_START_MESSAGE)
|
||||||
|
|
||||||
if not flags.noauth_local_webserver:
|
if not flags.noauth_local_webserver:
|
||||||
oauth_callback = 'http://%s:%s/' % (flags.auth_host_name, port_number)
|
oauth_callback = 'http://{host}:{port}/'.format(
|
||||||
|
host=flags.auth_host_name, port=port_number)
|
||||||
else:
|
else:
|
||||||
oauth_callback = client.OOB_CALLBACK_URN
|
oauth_callback = client.OOB_CALLBACK_URN
|
||||||
flow.redirect_uri = oauth_callback
|
flow.redirect_uri = oauth_callback
|
||||||
@@ -220,9 +221,9 @@ def run_flow(flow, storage, flags=None, http=None):
|
|||||||
if not flags.noauth_local_webserver:
|
if not flags.noauth_local_webserver:
|
||||||
import webbrowser
|
import webbrowser
|
||||||
webbrowser.open(authorize_url, new=1, autoraise=True)
|
webbrowser.open(authorize_url, new=1, autoraise=True)
|
||||||
print(_BROWSER_OPENED_MESSAGE % authorize_url)
|
print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url))
|
||||||
else:
|
else:
|
||||||
print(_GO_TO_LINK_MESSAGE % authorize_url)
|
print(_GO_TO_LINK_MESSAGE.format(address=authorize_url))
|
||||||
|
|
||||||
code = None
|
code = None
|
||||||
if not flags.noauth_local_webserver:
|
if not flags.noauth_local_webserver:
|
||||||
@@ -241,7 +242,7 @@ def run_flow(flow, storage, flags=None, http=None):
|
|||||||
try:
|
try:
|
||||||
credential = flow.step2_exchange(code, http=http)
|
credential = flow.step2_exchange(code, http=http)
|
||||||
except client.FlowExchangeError as e:
|
except client.FlowExchangeError as e:
|
||||||
sys.exit('Authentication has failed: %s' % e)
|
sys.exit('Authentication has failed: {0}'.format(e))
|
||||||
|
|
||||||
storage.put(credential)
|
storage.put(credential)
|
||||||
credential.set_store(storage)
|
credential.set_store(storage)
|
||||||
@@ -252,4 +253,4 @@ def run_flow(flow, storage, flags=None, http=None):
|
|||||||
|
|
||||||
def message_if_missing(filename):
|
def message_if_missing(filename):
|
||||||
"""Helpful message to display if the CLIENT_SECRETS file is missing."""
|
"""Helpful message to display if the CLIENT_SECRETS file is missing."""
|
||||||
return _CLIENT_SECRETS_MESSAGE % filename
|
return _CLIENT_SECRETS_MESSAGE.format(file_path=filename)
|
||||||
|
|||||||
@@ -124,10 +124,12 @@ def positional(max_positional_args):
|
|||||||
plural_s = ''
|
plural_s = ''
|
||||||
if max_positional_args != 1:
|
if max_positional_args != 1:
|
||||||
plural_s = 's'
|
plural_s = 's'
|
||||||
message = ('%s() takes at most %d positional '
|
message = ('{function}() takes at most {args_max} positional '
|
||||||
'argument%s (%d given)' % (
|
'argument{plural} ({args_given} given)'.format(
|
||||||
wrapped.__name__, max_positional_args,
|
function=wrapped.__name__,
|
||||||
plural_s, len(args)))
|
args_max=max_positional_args,
|
||||||
|
args_given=len(args),
|
||||||
|
plural=plural_s))
|
||||||
if positional_parameters_enforcement == POSITIONAL_EXCEPTION:
|
if positional_parameters_enforcement == POSITIONAL_EXCEPTION:
|
||||||
raise TypeError(message)
|
raise TypeError(message)
|
||||||
elif positional_parameters_enforcement == POSITIONAL_WARNING:
|
elif positional_parameters_enforcement == POSITIONAL_WARNING:
|
||||||
|
|||||||
@@ -109,7 +109,8 @@ class Test_SendRecv(unittest2.TestCase):
|
|||||||
sock.recv(6).decode.assert_called_once_with()
|
sock.recv(6).decode.assert_called_once_with()
|
||||||
|
|
||||||
data = CREDENTIAL_INFO_REQUEST_JSON
|
data = CREDENTIAL_INFO_REQUEST_JSON
|
||||||
msg = _to_bytes('%s\n%s' % (len(data), data), encoding='utf-8')
|
msg = _to_bytes('{0}\n{1}'.format(len(data), data),
|
||||||
|
encoding='utf-8')
|
||||||
expected_sock_calls = [
|
expected_sock_calls = [
|
||||||
mock.call.recv(6), # From the set-up above
|
mock.call.recv(6), # From the set-up above
|
||||||
mock.call.connect(('localhost', non_zero_port)),
|
mock.call.connect(('localhost', non_zero_port)),
|
||||||
@@ -167,7 +168,7 @@ class _AuthReferenceServer(threading.Thread):
|
|||||||
if resp_buffer != CREDENTIAL_INFO_REQUEST_JSON:
|
if resp_buffer != CREDENTIAL_INFO_REQUEST_JSON:
|
||||||
self.bad_request = True
|
self.bad_request = True
|
||||||
l = len(self.response)
|
l = len(self.response)
|
||||||
s.sendall(('%d\n%s' % (l, self.response)).encode())
|
s.sendall('{0}\n{1}'.format(l, self.response).encode())
|
||||||
finally:
|
finally:
|
||||||
# Will fail if s is None, but these tests never encounter
|
# Will fail if s is None, but these tests never encounter
|
||||||
# that scenario.
|
# that scenario.
|
||||||
@@ -183,7 +184,7 @@ class DevshellCredentialsTests(unittest2.TestCase):
|
|||||||
def test_bad_message_to_mock_server(self):
|
def test_bad_message_to_mock_server(self):
|
||||||
request_content = CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff'
|
request_content = CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff'
|
||||||
request_message = _to_bytes(
|
request_message = _to_bytes(
|
||||||
'%d\n%s' % (len(request_content), request_content))
|
'{0}\n{1}'.format(len(request_content), request_content))
|
||||||
response_message = 'foobar'
|
response_message = 'foobar'
|
||||||
with _AuthReferenceServer(response_message) as auth_server:
|
with _AuthReferenceServer(response_message) as auth_server:
|
||||||
self.assertFalse(auth_server.bad_request)
|
self.assertFalse(auth_server.bad_request)
|
||||||
|
|||||||
@@ -1279,7 +1279,7 @@ class BasicCredentialsTests(unittest2.TestCase):
|
|||||||
'status': int(http_client.BAD_REQUEST),
|
'status': int(http_client.BAD_REQUEST),
|
||||||
})
|
})
|
||||||
content = u'Bad request'
|
content = u'Bad request'
|
||||||
error_msg = 'Invalid response %s.' % (int(response.status),)
|
error_msg = 'Invalid response {0}.'.format(int(response.status))
|
||||||
self._do_refresh_request_test_helper(response, content, error_msg)
|
self._do_refresh_request_test_helper(response, content, error_msg)
|
||||||
|
|
||||||
def test__do_refresh_request_basic_failure(self):
|
def test__do_refresh_request_basic_failure(self):
|
||||||
@@ -1287,7 +1287,7 @@ class BasicCredentialsTests(unittest2.TestCase):
|
|||||||
'status': int(http_client.INTERNAL_SERVER_ERROR),
|
'status': int(http_client.INTERNAL_SERVER_ERROR),
|
||||||
})
|
})
|
||||||
content = u'{}'
|
content = u'{}'
|
||||||
error_msg = 'Invalid response %s.' % (int(response.status),)
|
error_msg = 'Invalid response {0}.'.format(int(response.status))
|
||||||
self._do_refresh_request_test_helper(response, content, error_msg)
|
self._do_refresh_request_test_helper(response, content, error_msg)
|
||||||
|
|
||||||
def test__do_refresh_request_failure_w_json_error(self):
|
def test__do_refresh_request_failure_w_json_error(self):
|
||||||
@@ -1318,7 +1318,7 @@ class BasicCredentialsTests(unittest2.TestCase):
|
|||||||
'error': base_error,
|
'error': base_error,
|
||||||
'error_description': error_desc,
|
'error_description': error_desc,
|
||||||
})
|
})
|
||||||
error_msg = '%s: %s' % (base_error, error_desc)
|
error_msg = '{0}: {1}'.format(base_error, error_desc)
|
||||||
self._do_refresh_request_test_helper(response, content, error_msg)
|
self._do_refresh_request_test_helper(response, content, error_msg)
|
||||||
|
|
||||||
@mock.patch('oauth2client.client.logger')
|
@mock.patch('oauth2client.client.logger')
|
||||||
@@ -1371,7 +1371,7 @@ class BasicCredentialsTests(unittest2.TestCase):
|
|||||||
'status': http_client.BAD_REQUEST,
|
'status': http_client.BAD_REQUEST,
|
||||||
})
|
})
|
||||||
content = u'Bad request'
|
content = u'Bad request'
|
||||||
error_msg = 'Invalid response %s.' % (response.status,)
|
error_msg = 'Invalid response {0}.'.format(response.status)
|
||||||
self._do_revoke_test_helper(response, content, error_msg)
|
self._do_revoke_test_helper(response, content, error_msg)
|
||||||
|
|
||||||
def test__do_revoke_basic_failure(self):
|
def test__do_revoke_basic_failure(self):
|
||||||
@@ -1379,7 +1379,7 @@ class BasicCredentialsTests(unittest2.TestCase):
|
|||||||
'status': http_client.INTERNAL_SERVER_ERROR,
|
'status': http_client.INTERNAL_SERVER_ERROR,
|
||||||
})
|
})
|
||||||
content = u'{}'
|
content = u'{}'
|
||||||
error_msg = 'Invalid response %s.' % (response.status,)
|
error_msg = 'Invalid response {0}.'.format(response.status)
|
||||||
self._do_revoke_test_helper(response, content, error_msg)
|
self._do_revoke_test_helper(response, content, error_msg)
|
||||||
|
|
||||||
def test__do_revoke_failure_w_json_error(self):
|
def test__do_revoke_failure_w_json_error(self):
|
||||||
@@ -1455,7 +1455,7 @@ class BasicCredentialsTests(unittest2.TestCase):
|
|||||||
'status': http_client.BAD_REQUEST,
|
'status': http_client.BAD_REQUEST,
|
||||||
})
|
})
|
||||||
content = u'Bad request'
|
content = u'Bad request'
|
||||||
error_msg = 'Invalid response %s.' % (response.status,)
|
error_msg = 'Invalid response {0}.'.format(response.status)
|
||||||
self._do_retrieve_scopes_test_helper(response, content, error_msg)
|
self._do_retrieve_scopes_test_helper(response, content, error_msg)
|
||||||
|
|
||||||
def test__do_retrieve_scopes_basic_failure(self):
|
def test__do_retrieve_scopes_basic_failure(self):
|
||||||
@@ -1463,7 +1463,7 @@ class BasicCredentialsTests(unittest2.TestCase):
|
|||||||
'status': http_client.INTERNAL_SERVER_ERROR,
|
'status': http_client.INTERNAL_SERVER_ERROR,
|
||||||
})
|
})
|
||||||
content = u'{}'
|
content = u'{}'
|
||||||
error_msg = 'Invalid response %s.' % (response.status,)
|
error_msg = 'Invalid response {0}.'.format(response.status)
|
||||||
self._do_retrieve_scopes_test_helper(response, content, error_msg)
|
self._do_retrieve_scopes_test_helper(response, content, error_msg)
|
||||||
|
|
||||||
def test__do_retrieve_scopes_failure_w_json_error(self):
|
def test__do_retrieve_scopes_failure_w_json_error(self):
|
||||||
@@ -1824,14 +1824,14 @@ class OAuth2WebServerFlowTest(unittest2.TestCase):
|
|||||||
def test_step1_get_device_and_user_codes_non_json_failure(self):
|
def test_step1_get_device_and_user_codes_non_json_failure(self):
|
||||||
status = int(http_client.BAD_REQUEST)
|
status = int(http_client.BAD_REQUEST)
|
||||||
content = 'Nope not JSON.'
|
content = 'Nope not JSON.'
|
||||||
error_msg = 'Invalid response %s.' % (status,)
|
error_msg = 'Invalid response {0}.'.format(status)
|
||||||
self._step1_get_device_and_user_codes_fail_helper(status, content,
|
self._step1_get_device_and_user_codes_fail_helper(status, content,
|
||||||
error_msg)
|
error_msg)
|
||||||
|
|
||||||
def test_step1_get_device_and_user_codes_basic_failure(self):
|
def test_step1_get_device_and_user_codes_basic_failure(self):
|
||||||
status = int(http_client.INTERNAL_SERVER_ERROR)
|
status = int(http_client.INTERNAL_SERVER_ERROR)
|
||||||
content = b'{}'
|
content = b'{}'
|
||||||
error_msg = 'Invalid response %s.' % (status,)
|
error_msg = 'Invalid response {0}.'.format(status)
|
||||||
self._step1_get_device_and_user_codes_fail_helper(status, content,
|
self._step1_get_device_and_user_codes_fail_helper(status, content,
|
||||||
error_msg)
|
error_msg)
|
||||||
|
|
||||||
@@ -1839,7 +1839,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase):
|
|||||||
status = int(http_client.BAD_GATEWAY)
|
status = int(http_client.BAD_GATEWAY)
|
||||||
base_error = 'ZOMG user codes failure.'
|
base_error = 'ZOMG user codes failure.'
|
||||||
content = json.dumps({'error': base_error})
|
content = json.dumps({'error': base_error})
|
||||||
error_msg = 'Invalid response %s. Error: %s' % (status, base_error)
|
error_msg = 'Invalid response {0}. Error: {1}'.format(status,
|
||||||
|
base_error)
|
||||||
self._step1_get_device_and_user_codes_fail_helper(status, content,
|
self._step1_get_device_and_user_codes_fail_helper(status, content,
|
||||||
error_msg)
|
error_msg)
|
||||||
|
|
||||||
@@ -2163,7 +2164,8 @@ class FlowFromCachedClientsecrets(unittest2.TestCase):
|
|||||||
filename = object()
|
filename = object()
|
||||||
cache = object()
|
cache = object()
|
||||||
|
|
||||||
err_msg = 'This OAuth 2.0 flow is unsupported: %r' % (client_type,)
|
err_msg = ('This OAuth 2.0 flow is unsupported: '
|
||||||
|
'{0!r}'.format(client_type))
|
||||||
with self.assertRaisesRegexp(client.UnknownClientSecretsFlowError,
|
with self.assertRaisesRegexp(client.UnknownClientSecretsFlowError,
|
||||||
err_msg):
|
err_msg):
|
||||||
flow_from_clientsecrets(filename, None, cache=cache)
|
flow_from_clientsecrets(filename, None, cache=cache)
|
||||||
|
|||||||
@@ -40,7 +40,8 @@ class TestClientRedirectServer(unittest2.TestCase):
|
|||||||
httpd = tools.ClientRedirectServer(('localhost', 0),
|
httpd = tools.ClientRedirectServer(('localhost', 0),
|
||||||
tools.ClientRedirectHandler)
|
tools.ClientRedirectHandler)
|
||||||
code = 'foo'
|
code = 'foo'
|
||||||
url = 'http://localhost:%i?code=%s' % (httpd.server_address[1], code)
|
url = 'http://localhost:{0}?code={1}'.format(
|
||||||
|
httpd.server_address[1], code)
|
||||||
t = threading.Thread(target=httpd.handle_request)
|
t = threading.Thread(target=httpd.handle_request)
|
||||||
t.setDaemon(True)
|
t.setDaemon(True)
|
||||||
t.start()
|
t.start()
|
||||||
|
|||||||
Reference in New Issue
Block a user