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

Commit

Permalink
Merge pull request #540 from pferate/pep8_cleanup
Browse files Browse the repository at this point in the history
PEP8 cleanup.
  • Loading branch information
nathanielmanistaatgoogle authored Jul 11, 2016
2 parents f25b7ab + 09e9420 commit ac4385c
Show file tree
Hide file tree
Showing 51 changed files with 336 additions and 306 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ env:
- TOX_ENV=system-tests
- TOX_ENV=system-tests3
- TOX_ENV=gae
- TOX_ENV=flake8
global:
- GAE_PYTHONPATH=${HOME}/.cache/google_appengine
cache:
Expand Down
25 changes: 12 additions & 13 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,22 @@
#

import os
from pkg_resources import get_distribution
import sys


# In order to load django before 1.7, we need to create a faux
# settings module and load it. This assumes django has been installed
# (but it must be for the docs to build), so if it has not already
# been installed run `pip install -r docs/requirements.txt`.
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.contrib.test_django_settings'
import django
import mock
from pkg_resources import get_distribution
if django.VERSION[1] < 7:
sys.path.insert(0, '.')

# See https://read-the-docs.readthedocs.io/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules

# See
# (https://read-the-docs.readthedocs.io/en/latest/faq.html#\
# i-get-import-errors-on-libraries-that-depend-on-c-modules)

class Mock(mock.Mock):

Expand Down Expand Up @@ -61,15 +69,6 @@ def __getattr__(cls, name):

exclude_patterns = ['_build']

# In order to load django before 1.7, we need to create a faux
# settings module and load it. This assumes django has been installed
# (but it must be for the docs to build), so if it has not already
# been installed run `pip install -r docs/requirements.txt`.
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.contrib.test_django_settings'
import django
if django.VERSION[1] < 7:
sys.path.insert(0, '.')

# -- Options for HTML output ----------------------------------------------

# We fake our more expensive imports when building the docs.
Expand Down
1 change: 1 addition & 0 deletions oauth2client/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import base64
import json

import six


Expand Down
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
2 changes: 1 addition & 1 deletion oauth2client/_pycrypto_crypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
# limitations under the License.
"""pyCrypto Crypto-related routines for oauth2client."""

from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Util.asn1 import DerSequence

Expand Down
37 changes: 18 additions & 19 deletions oauth2client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,33 +17,32 @@
Tools for interacting with OAuth 2.0 protected resources.
"""

import base64
import collections
import copy
import datetime
import json
import logging
import os
import shutil
import socket
import sys
import tempfile
import time
import shutil

import httplib2
import six
from six.moves import http_client
from six.moves import urllib

import httplib2
from oauth2client import clientsecrets
from oauth2client import GOOGLE_AUTH_URI
from oauth2client import GOOGLE_DEVICE_URI
from oauth2client import GOOGLE_REVOKE_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client import GOOGLE_TOKEN_INFO_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client import util
from oauth2client._helpers import _from_bytes
from oauth2client._helpers import _to_bytes
from oauth2client._helpers import _urlsafe_b64decode
from oauth2client import clientsecrets
from oauth2client import util


__author__ = '[email protected] (Joe Gregorio)'
Expand Down Expand Up @@ -259,8 +258,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 +358,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 +1195,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 +1253,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 +1467,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 +1550,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 +2211,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
2 changes: 1 addition & 1 deletion oauth2client/clientsecrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
"""

import json
import six

import six

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

Expand Down
3 changes: 1 addition & 2 deletions oauth2client/contrib/_fcntl_opener.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
# limitations under the License.

import errno
import time

import fcntl
import time

from oauth2client.contrib.locked_file import _Opener
from oauth2client.contrib.locked_file import AlreadyLockedException
Expand Down
4 changes: 2 additions & 2 deletions oauth2client/contrib/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@
"""

import datetime
import httplib2
import json

import httplib2
from six.moves import http_client
from six.moves.urllib import parse as urlparse

from oauth2client import util
from oauth2client._helpers import _from_bytes
from oauth2client.client import _UTCNOW
from oauth2client import util


METADATA_ROOT = 'http://metadata.google.internal/computeMetadata/v1/'
Expand Down
7 changes: 3 additions & 4 deletions oauth2client/contrib/appengine.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,18 @@
import pickle
import threading

import httplib2
import webapp2 as webapp

from google.appengine.api import app_identity
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp.util import login_required
import httplib2
import webapp2 as webapp

from oauth2client import clientsecrets
from oauth2client import GOOGLE_AUTH_URI
from oauth2client import GOOGLE_REVOKE_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client import clientsecrets
from oauth2client import util
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import AssertionCredentials
Expand Down
2 changes: 1 addition & 1 deletion oauth2client/contrib/devshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
import os
import socket

from oauth2client._helpers import _to_bytes
from oauth2client import client
from oauth2client._helpers import _to_bytes

# Expose utcnow() at module level to allow for
# easier testing (by replacing with a stub).
Expand Down
6 changes: 3 additions & 3 deletions oauth2client/contrib/django_orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@
Only Django versions 1.8+ are supported.
"""

import oauth2client
import base64
import pickle
import six

from django.db import models
from django.utils.encoding import smart_bytes, smart_text

import oauth2client
from oauth2client.client import Storage as BaseStorage


Expand Down Expand Up @@ -179,4 +179,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()
35 changes: 19 additions & 16 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 @@ -124,8 +124,9 @@ def optional_oauth2(request):
return HttpResponse("User email: %s"
% 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())
return HttpResponse(
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
% 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 @@ -144,8 +145,9 @@ def drive_required(request):
events = service.files().list().execute()['items']
return HttpResponse(str(events))
else:
return HttpResponse('Here is an OAuth Authorize link:
<a href="%s">Authorize</a>' % request.oauth.get_authorize_redirect())
return HttpResponse(
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
% request.oauth.get_authorize_redirect())
To provide a callback on authorization being completed, use the
Expand All @@ -168,9 +170,10 @@ def test_callback(sender, request, credentials, **kwargs):
from django.core import exceptions
from django.core import urlresolvers
import httplib2
from six.moves.urllib import parse

from oauth2client import clientsecrets
from oauth2client.contrib.django_util import storage
from six.moves.urllib import parse

GOOGLE_OAUTH2_DEFAULT_SCOPES = ('email',)
GOOGLE_OAUTH2_REQUEST_ATTRIBUTE = 'oauth'
Expand Down Expand Up @@ -202,9 +205,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 +293,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
5 changes: 3 additions & 2 deletions oauth2client/contrib/django_util/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
# limitations under the License.

from django import shortcuts
from oauth2client.contrib import django_util
from six import wraps

from oauth2client.contrib import django_util


def oauth_required(decorated_function=None, scopes=None, **decorator_kwargs):
""" Decorator to require OAuth2 credentials for a view
Expand All @@ -36,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: %s, calendar: %s" % (email, str(events)))
:param decorated_function: View function to decorate, must have the Django
request object as the first argument
Expand Down
Loading

0 comments on commit ac4385c

Please sign in to comment.