Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

PEP8 cleanup #540

Merged
merged 8 commits into from
Jul 11, 2016
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions oauth2client/_openssl_crypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
# limitations under the License.
"""OpenSSL Crypto-related routines for oauth2client."""

import base64

from OpenSSL import crypto

from oauth2client._helpers import _parse_pem_key
Expand Down
26 changes: 12 additions & 14 deletions oauth2client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
Tools for interacting with OAuth 2.0 protected resources.
"""

import base64
import collections
import copy
import datetime
Expand All @@ -27,7 +26,6 @@
import socket
import sys
import tempfile
import time
import shutil
import six
from six.moves import http_client
Expand Down Expand Up @@ -259,8 +257,8 @@ def _to_json(self, strip, to_serialize=None):
strip: array, An array of names of members to exclude from the
JSON.
to_serialize: dict, (Optional) The properties for this object
that will be serialized. This allows callers to modify
before serializing.
that will be serialized. This allows callers to
modify before serializing.

Returns:
string, a JSON representation of this instance, suitable to pass to
Expand Down Expand Up @@ -359,7 +357,8 @@ def __init__(self, lock=None):

Args:
lock: An optional threading.Lock-like object. Must implement at
least acquire() and release(). Does not need to be re-entrant.
least acquire() and release(). Does not need to be
re-entrant.
"""
self._lock = lock

Expand Down Expand Up @@ -1195,7 +1194,7 @@ class GoogleCredentials(OAuth2Credentials):
print(response)
"""

NON_SERIALIZED_MEMBERS = (
NON_SERIALIZED_MEMBERS = (
frozenset(['_private_key']) |
OAuth2Credentials.NON_SERIALIZED_MEMBERS)
"""Members that aren't serialized when object is converted to JSON."""
Expand Down Expand Up @@ -1253,12 +1252,11 @@ def from_json(cls, json_data):
# We handle service_account.ServiceAccountCredentials since it is a
# possible return type of GoogleCredentials.get_application_default()
if (data['_module'] == 'oauth2client.service_account' and
data['_class'] == 'ServiceAccountCredentials'):
data['_class'] == 'ServiceAccountCredentials'):
return ServiceAccountCredentials.from_json(data)
elif (data['_module'] == 'oauth2client.service_account' and
data['_class'] == '_JWTAccessCredentials'):
data['_class'] == '_JWTAccessCredentials'):
return _JWTAccessCredentials.from_json(data)


token_expiry = _parse_expiry(data.get('token_expiry'))
google_credentials = cls(
Expand Down Expand Up @@ -1468,8 +1466,7 @@ def save_to_well_known_file(credentials, well_known_file=None):

def _get_environment_variable_file():
application_default_credential_filename = (
os.environ.get(GOOGLE_APPLICATION_CREDENTIALS,
None))
os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None))

if application_default_credential_filename:
if os.path.isfile(application_default_credential_filename):
Expand Down Expand Up @@ -1552,8 +1549,8 @@ def _raise_exception_for_reading_json(credential_file,
extra_help,
error):
raise ApplicationDefaultCredentialsError(
'An error was encountered while reading json file: ' +
credential_file + extra_help + ': ' + str(error))
'An error was encountered while reading json file: ' +
credential_file + extra_help + ': ' + str(error))


def _get_application_default_credential_GAE():
Expand Down Expand Up @@ -2213,7 +2210,8 @@ def flow_from_clientsecrets(filename, scope, redirect_uri=None,
except clientsecrets.InvalidClientSecretsError as e:
if message is not None:
if e.args:
message = 'The client secrets were invalid: \n{0}\n{1}'.format(e, message)
message = ('The client secrets were invalid: '
'\n{0}\n{1}'.format(e, message))
sys.exit(message)
else:
raise
Expand Down
3 changes: 1 addition & 2 deletions oauth2client/contrib/django_orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import oauth2client
import base64
import pickle
import six

from django.db import models
from django.utils.encoding import smart_bytes, smart_text
Expand Down Expand Up @@ -179,4 +178,4 @@ def locked_delete(self):
"""Delete Credentials from the datastore."""

query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query).delete()
self.model_class.objects.filter(**query).delete()
22 changes: 11 additions & 11 deletions oauth2client/contrib/django_util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
"""Utilities for the Django web framework

Provides Django views and helpers the make using the OAuth2 web server
flow easier. It includes an ``oauth_required`` decorator to automatically ensure
that user credentials are available, and an ``oauth_enabled`` decorator to check
if the user has authorized, and helper shortcuts to create the authorization
URL otherwise.
flow easier. It includes an ``oauth_required`` decorator to automatically
ensure that user credentials are available, and an ``oauth_enabled`` decorator
to check if the user has authorized, and helper shortcuts to create the
authorization URL otherwise.

Only Django versions 1.8+ are supported.

Expand Down Expand Up @@ -89,8 +89,8 @@
urlpatterns += [url(r'^oauth2/', include(oauth2_urls))]

To require OAuth2 credentials for a view, use the `oauth2_required` decorator.
This creates a credentials object with an id_token, and allows you to create an
`http` object to build service clients with. These are all attached to the
This creates a credentials object with an id_token, and allows you to create
an `http` object to build service clients with. These are all attached to the
request.oauth

.. code-block:: python
Expand Down Expand Up @@ -202,9 +202,9 @@ def _get_oauth2_client_id_and_secret(settings_instance):
return client_id, client_secret
else:
raise exceptions.ImproperlyConfigured(
"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or "
" both GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET "
"in settings.py")
"Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or "
"both GOOGLE_OAUTH2_CLIENT_ID and "
"GOOGLE_OAUTH2_CLIENT_SECRET in settings.py")


class OAuth2Settings(object):
Expand Down Expand Up @@ -290,8 +290,8 @@ def get_authorize_redirect(self):
def has_credentials(self):
"""Returns True if there are valid credentials for the current user
and required scopes."""
return (self.credentials and not self.credentials.invalid
and self.credentials.has_scopes(self.scopes))
return (self.credentials and not self.credentials.invalid and
self.credentials.has_scopes(self.scopes))

@property
def credentials(self):
Expand Down
3 changes: 2 additions & 1 deletion oauth2client/contrib/django_util/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ def oauth2_callback(request):
try:
server_csrf = request.session[_CSRF_KEY]
except KeyError:
return http.HttpResponseBadRequest("No existing session for this flow.")
return http.HttpResponseBadRequest(
"No existing session for this flow.")

try:
state = json.loads(encoded_state)
Expand Down
4 changes: 2 additions & 2 deletions oauth2client/contrib/flask_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,8 @@ def has_credentials(self):
if not self.credentials:
return False
# Is the access token expired? If so, do we have an refresh token?
elif (self.credentials.access_token_expired
and not self.credentials.refresh_token):
elif (self.credentials.access_token_expired and
not self.credentials.refresh_token):
return False
else:
return True
Expand Down
3 changes: 2 additions & 1 deletion oauth2client/contrib/gce.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ def _retrieve_info(self, http_request):
"""
if self.invalid:
info = _metadata.get_service_account_info(
http_request, service_account=self.service_account_email or 'default')
http_request,
service_account=self.service_account_email or 'default')
self.invalid = False
self.service_account_email = info['email']
self.scopes = info['scopes']
Expand Down
31 changes: 15 additions & 16 deletions oauth2client/service_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,15 @@

from oauth2client import GOOGLE_REVOKE_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client._helpers import _json_encode
from oauth2client._helpers import _from_bytes
from oauth2client._helpers import _urlsafe_b64encode
from oauth2client import util
from oauth2client.client import _apply_user_agent
from oauth2client.client import _initialize_headers
from oauth2client.client import AccessTokenInfo
from oauth2client.client import AssertionCredentials
from oauth2client.client import clean_headers
from oauth2client.client import EXPIRY_FORMAT
from oauth2client.client import GoogleCredentials
from oauth2client.client import SERVICE_ACCOUNT
from oauth2client.client import TokenRevokeError
from oauth2client.client import _UTCNOW
from oauth2client import crypt

Expand Down Expand Up @@ -94,7 +90,7 @@ class ServiceAccountCredentials(AssertionCredentials):
MAX_TOKEN_LIFETIME_SECS = 3600
"""Max lifetime of the token (one hour, in seconds)."""

NON_SERIALIZED_MEMBERS = (
NON_SERIALIZED_MEMBERS = (
frozenset(['_signer']) |
AssertionCredentials.NON_SERIALIZED_MEMBERS)
"""Members that aren't serialized when object is converted to JSON."""
Expand Down Expand Up @@ -138,8 +134,8 @@ def _to_json(self, strip, to_serialize=None):
strip: array, An array of names of members to exclude from the
JSON.
to_serialize: dict, (Optional) The properties for this object
that will be serialized. This allows callers to modify
before serializing.
that will be serialized. This allows callers to
modify before serializing.

Returns:
string, a JSON representation of this instance, suitable to pass to
Expand Down Expand Up @@ -502,7 +498,7 @@ def create_scoped(self, scopes):
result._private_key_pkcs12 = self._private_key_pkcs12
result._private_key_password = self._private_key_password
return result

def create_with_claims(self, claims):
"""Create credentials that specify additional claims.

Expand All @@ -511,7 +507,8 @@ def create_with_claims(self, claims):

Returns:
ServiceAccountCredentials, a copy of the current service account
credentials with updated claims to use when obtaining access tokens.
credentials with updated claims to use when obtaining access
tokens.
"""
new_kwargs = dict(self._kwargs)
new_kwargs.update(claims)
Expand Down Expand Up @@ -552,11 +549,11 @@ def create_delegated(self, sub):


def _datetime_to_secs(utc_time):
# TODO(issue 298): use time_delta.total_seconds()
# time_delta.total_seconds() not supported in Python 2.6
epoch = datetime.datetime(1970, 1, 1)
time_delta = utc_time - epoch
return time_delta.days * 86400 + time_delta.seconds
# TODO(issue 298): use time_delta.total_seconds()
# time_delta.total_seconds() not supported in Python 2.6
epoch = datetime.datetime(1970, 1, 1)
time_delta = utc_time - epoch
return time_delta.days * 86400 + time_delta.seconds


class _JWTAccessCredentials(ServiceAccountCredentials):
Expand Down Expand Up @@ -607,7 +604,8 @@ def authorize(self, http):
h = credentials.authorize(h)
"""
request_orig = http.request
request_auth = super(_JWTAccessCredentials, self).authorize(http).request
request_auth = super(_JWTAccessCredentials,

This comment was marked as spam.

This comment was marked as spam.

self).authorize(http).request

# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
Expand Down Expand Up @@ -695,7 +693,8 @@ def _refresh(self, http_request):

def _create_token(self, additional_claims=None):
now = _UTCNOW()
expiry = now + datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS)
lifetime = datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS)
expiry = now + lifetime
payload = {
'iat': _datetime_to_secs(now),
'exp': _datetime_to_secs(expiry),
Expand Down
51 changes: 29 additions & 22 deletions oauth2client/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,32 @@

"""

_FAILED_START_MESSAGE = """
Failed to start a local webserver listening on either port 8080
or port 8090. Please check your firewall settings and locally
running programs that may be blocking or using those ports.

Falling back to --noauth_local_webserver and continuing with
authorization.
"""

_BROWSER_OPENED_MESSAGE = """
Your browser has been opened to visit:

%s

If your browser is on a different machine then exit and re-run this
application with the command-line parameter

--noauth_local_webserver
"""

_GO_TO_LINK_MESSAGE = """
Go to the following link in your browser:

%s
"""


def _CreateArgumentParser():
try:
Expand Down Expand Up @@ -182,14 +208,7 @@ def run_flow(flow, storage, flags=None, http=None):
break
flags.noauth_local_webserver = not success
if not success:
print('Failed to start a local webserver listening '
'on either port 8080')
print('or port 8090. Please check your firewall settings and locally')
print('running programs that may be blocking or using those ports.')
print()
print('Falling back to --noauth_local_webserver and continuing with')
print('authorization.')
print()
print(_FAILED_START_MESSAGE)

if not flags.noauth_local_webserver:
oauth_callback = 'http://%s:%s/' % (flags.auth_host_name, port_number)
Expand All @@ -201,21 +220,9 @@ def run_flow(flow, storage, flags=None, http=None):
if not flags.noauth_local_webserver:
import webbrowser
webbrowser.open(authorize_url, new=1, autoraise=True)
print('Your browser has been opened to visit:')
print()
print(' ' + authorize_url)
print()
print('If your browser is on a different machine then '
'exit and re-run this')
print('application with the command-line parameter ')
print()
print(' --noauth_local_webserver')
print()
print(_BROWSER_OPENED_MESSAGE % authorize_url)

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

else:
print('Go to the following link in your browser:')
print()
print(' ' + authorize_url)
print()
print(_GO_TO_LINK_MESSAGE % authorize_url)

code = None
if not flags.noauth_local_webserver:
Expand Down
Loading