Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Linting and deprecation fixes #234

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
14 changes: 8 additions & 6 deletions authomatic/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,9 @@
"""

import abc
from authomatic.core import Response


class BaseAdapter(object):
class BaseAdapter():
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
class BaseAdapter():
class BaseAdapter:

"""
Base class for platform adapters.

Expand All @@ -69,7 +68,8 @@ class BaseAdapter(object):

__metaclass__ = abc.ABCMeta

@abc.abstractproperty
@property
@abc.abstractmethod
def params(self):
"""
Must return a :class:`dict` of all request parameters of any HTTP
Expand All @@ -80,7 +80,8 @@ def params(self):

"""

@abc.abstractproperty
@property
@abc.abstractmethod
def url(self):
"""
Must return the url of the actual request including path but without
Expand All @@ -91,7 +92,8 @@ def url(self):

"""

@abc.abstractproperty
@property
@abc.abstractmethod
def cookies(self):
"""
Must return cookies as a :class:`dict`.
Expand Down Expand Up @@ -173,7 +175,7 @@ def set_header(self, key, value):
self.response[key] = value

def set_status(self, status):
status_code, reason = status.split(' ', 1)
status_code = status.split(' ', 1)[0]
self.response.status_code = int(status_code)


Expand Down
61 changes: 26 additions & 35 deletions authomatic/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def normalize_dict(dict_):

"""

return dict([(k, v[0] if not isinstance(v, str) and len(v) == 1 else v)
for k, v in list(dict_.items())])
return {[(k, v[0] if not isinstance(v, str) and len(v) == 1 else v)
for k, v in list(dict_.items())]}
Comment on lines +53 to +54
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it could be rewritten like this:

Suggested change
return {[(k, v[0] if not isinstance(v, str) and len(v) == 1 else v)
for k, v in list(dict_.items())]}
return {k: v[0] if not isinstance(v, str) and len(v) == 1 else v for k, v in dict_.items()}



def items_to_dict(items):
Expand All @@ -75,7 +75,7 @@ def items_to_dict(items):
return normalize_dict(dict(res))


class Counter(object):
class Counter():
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
class Counter():
class Counter:

"""
A simple counter to be used in the config to generate unique `id` values.
"""
Expand Down Expand Up @@ -181,8 +181,7 @@ def import_string(import_name, silent=False):
if '.' in import_name:
module, obj = import_name.rsplit('.', 1)
return getattr(__import__(module, None, None, [obj]), obj)
else:
return __import__(import_name)
return __import__(import_name)
except (ImportError, AttributeError) as e:
if not silent:
raise ImportStringError('Import from string failed for path {0}'
Expand All @@ -205,8 +204,7 @@ def resolve_provider_class(class_):
# try to import class by string from providers module or by fully
# qualified path
return import_string(class_, True) or import_string(path)
else:
return class_
return class_


def id_to_name(config, short_name):
Expand All @@ -228,7 +226,7 @@ def id_to_name(config, short_name):
'No provider with id={0} found in the config!'.format(short_name))


class ReprMixin(object):
class ReprMixin():
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
class ReprMixin():
class ReprMixin:

"""
Provides __repr__() method with output *ClassName(arg1=value, arg2=value)*.

Expand Down Expand Up @@ -302,7 +300,7 @@ def __init__(self, func, *args, **kwargs):
passed to :data:`func`.
"""

super(Future, self).__init__()
super().__init__()
self._func = func
self._args = args
self._kwargs = kwargs
Expand Down Expand Up @@ -335,7 +333,7 @@ def get_result(self, timeout=None):
return self._result


class Session(object):
class Session():
"""
A dictionary-like secure cookie session implementation.
"""
Expand Down Expand Up @@ -754,8 +752,7 @@ def expiration_date(self):

if self.expire_in < 0:
return None
else:
return datetime.datetime.fromtimestamp(self.expiration_time)
return datetime.datetime.fromtimestamp(self.expiration_time)

@property
def valid(self):
Expand All @@ -765,8 +762,7 @@ def valid(self):

if self.expiration_time:
return self.expiration_time > int(time.time())
else:
return True
return True
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even simpler:

        return  self.expiration_time and self.expiration_time > int(time.time())


def expire_soon(self, seconds):
"""
Expand All @@ -783,8 +779,7 @@ def expire_soon(self, seconds):

if self.expiration_time:
return self.expiration_time < int(time.time()) + int(seconds)
else:
return False
return False
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here:

return self.expiration_time and self.expiration_time < int(time.time()) + int(seconds)


def refresh(self, force=False, soon=86400):
"""
Expand Down Expand Up @@ -1066,7 +1061,7 @@ def user(self):
return self.provider.user if self.provider else None

def to_dict(self):
return dict(provider=self.provider, user=self.user, error=self.error)
return {'provider': self.provider, 'user': self.user, 'error': self.error}

def to_json(self, indent=4):
return json.dumps(self, default=lambda obj: obj.to_dict(
Expand Down Expand Up @@ -1180,7 +1175,7 @@ class UserInfoResponse(Response):
"""

def __init__(self, user, *args, **kwargs):
super(UserInfoResponse, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

#: :class:`.User` instance.
self.user = user
Expand Down Expand Up @@ -1254,14 +1249,16 @@ def full_url(self):
return self.url + '?' + self.query_string

def to_json(self):
return json.dumps(dict(url=self.url,
method=self.method,
params=self.params,
headers=self.headers,
body=self.body))
return json.dumps({
'url': self.url,
'method': self.method,
'params': self.params,
'headers': self.headers,
'body': self.body
})


class Authomatic(object):
class Authomatic():
def __init__(
self, config, secret, session_max_age=600, secure_cookie=False,
session=None, session_save_method=None, report_errors=True,
Expand Down Expand Up @@ -1373,10 +1370,7 @@ def login(self, adapter, provider_name, callback=None,
raise ConfigError('Provider name "{0}" not specified!'
.format(provider_name))

if not (session is None or session_saver is None):
session = session
session_saver = session_saver
else:
if session is None or session_saver is None:
session = Session(adapter=adapter,
secret=self.secret,
max_age=self.session_max_age,
Expand Down Expand Up @@ -1408,9 +1402,8 @@ def login(self, adapter, provider_name, callback=None,
# return login result
return provider.login()

else:
# Act like backend.
self.backend(adapter)
# Act like backend.
self.backend(adapter)

def credentials(self, credentials):
"""
Expand Down Expand Up @@ -1600,9 +1593,7 @@ def request_elements(

if return_json:
return request_elements.to_json()

else:
return request_elements
return request_elements

def backend(self, adapter):
"""
Expand Down Expand Up @@ -1714,7 +1705,7 @@ def get(self):
jsonp = params.get('callback')

# JSONP is possible only with GET method.
if ProviderClass.supports_jsonp and method is 'GET':
if ProviderClass.supports_jsonp and method == 'GET':
request_type = 'elements'
else:
# Remove the JSONP callback
Expand Down
2 changes: 1 addition & 1 deletion authomatic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class BaseError(Exception):
"""

def __init__(self, message, original_message='', url='', status=None):
super(BaseError, self).__init__(message)
super().__init__(message)

#: Error message.
self.message = message
Expand Down
2 changes: 1 addition & 1 deletion authomatic/extras/flask.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def decorated(*args, **kwargs):
adapter = WerkzeugAdapter(request, self.response)
login_kwargs.setdefault('session', session)
login_kwargs.setdefault('session_saver', self.session_saver)
self.result = super(FlaskAuthomatic, self).login(
self.result = super().login(
adapter,
*login_args,
**login_kwargs)
Expand Down
13 changes: 5 additions & 8 deletions authomatic/extras/gae/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,10 @@ def __init__(self, handler, session=None, secret=None,
if session is None:
if not secret:
raise GAEError('Either session or secret must be specified!')
else:
# Create new session.
cfg = config or dict(
secret_key=secret, cookie_name=cookie_name)
session_store = sessions.SessionStore(handler.request, cfg)
self.session_dict = session_store.get_session(backend=backend)
# Create new session.
cfg = config or {'secret_key': secret, 'cookie_name': cookie_name}
session_store = sessions.SessionStore(handler.request, cfg)
self.session_dict = session_store.get_session(backend=backend)
else:
# Use supplied session.
self.session_dict = session
Expand Down Expand Up @@ -160,8 +158,7 @@ def get(cls, key, default=None):
result_dict[i] = None

return result_dict
else:
return default
return default

@classmethod
def values(cls):
Expand Down
41 changes: 20 additions & 21 deletions authomatic/extras/gae/openid.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def storeAssociation(cls, server_url, association):

cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Putting OpenID association to datastore.')
'NDBOpenIDStore: Putting OpenID association to datastore.')

entity.put()

Expand All @@ -59,7 +59,7 @@ def cleanupAssociations(cls):
# query for all expired
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Querying datastore for OpenID associations.')
'NDBOpenIDStore: Querying datastore for OpenID associations.')
query = cls.query(cls.expiration_date <= datetime.datetime.now())

# fetch keys only
Expand All @@ -68,7 +68,7 @@ def cleanupAssociations(cls):
# delete all expired
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Deleting expired OpenID associations from datastore.')
'NDBOpenIDStore: Deleting expired OpenID associations from datastore.')
ndb.delete_multi(expired)

return len(expired)
Expand All @@ -81,13 +81,13 @@ def getAssociation(cls, server_url, handle=None):
key = ndb.Key('ServerUrl', server_url, cls, handle)
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Getting OpenID association from datastore by key.')
'NDBOpenIDStore: Getting OpenID association from datastore by key.')
entity = key.get()
else:
# return most recently issued association
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Querying datastore for OpenID associations by ancestor.')
'NDBOpenIDStore: Querying datastore for OpenID associations by ancestor.')
entity = cls.query(ancestor=ndb.Key(
'ServerUrl', server_url)).order(-cls.issued).get()

Expand All @@ -100,11 +100,11 @@ def removeAssociation(cls, server_url, handle):
key = ndb.Key('ServerUrl', server_url, cls, handle)
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Getting OpenID association from datastore by key.')
'NDBOpenIDStore: Getting OpenID association from datastore by key.')
if key.get():
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Deleting OpenID association from datastore.')
'NDBOpenIDStore: Deleting OpenID association from datastore.')
key.delete()
return True

Expand All @@ -123,40 +123,39 @@ def useNonce(cls, server_url, timestamp, salt):

cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Getting OpenID nonce from datastore by key.')
'NDBOpenIDStore: Getting OpenID nonce from datastore by key.')
result = key.get()

if result:
# if so, the nonce is not valid so return False
cls._log(
logging.WARNING,
u'NDBOpenIDStore: Nonce was already used!')
'NDBOpenIDStore: Nonce was already used!')
return False
else:
# if not, store the key to datastore and return True
nonce = cls(key=key)
nonce.expiration_date = datetime.datetime.fromtimestamp(
timestamp) + datetime.timedelta(0, openid.store.nonce.SKEW)
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Putting new nonce to datastore.')
nonce.put()
return True
# if not, store the key to datastore and return True
nonce = cls(key=key)
nonce.expiration_date = datetime.datetime.fromtimestamp(
timestamp) + datetime.timedelta(0, openid.store.nonce.SKEW)
cls._log(
logging.DEBUG,
'NDBOpenIDStore: Putting new nonce to datastore.')
nonce.put()
return True

@classmethod
def cleanupNonces(cls):
# get all expired nonces
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Querying datastore for OpenID nonces ordered by expiration date.')
'NDBOpenIDStore: Querying datastore for OpenID nonces ordered by expiration date.')
expired = cls.query().filter(
cls.expiration_date <= datetime.datetime.now()).fetch(
keys_only=True)

# delete all expired
cls._log(
logging.DEBUG,
u'NDBOpenIDStore: Deleting expired OpenID nonces from datastore.')
'NDBOpenIDStore: Deleting expired OpenID nonces from datastore.')
ndb.delete_multi(expired)

return len(expired)
Loading
Loading