Merge pull request #1296 from BuhtigithuB/enhancement/pep8-tools-py

Enhancement tools.py PEP8
This commit is contained in:
mdipierro committed 2016-04-15 22:10:12 -05:00
commit 4fbd612d1b
1 file changed
+62 -89
+62 -89
View File
@@ -1217,7 +1217,7 @@ class AuthJWT(object):
self.auth = auth self.auth = auth
self.algorithm = algorithm self.algorithm = algorithm
if self.algorithm not in ('HS256', 'HS384', 'HS512'): if self.algorithm not in ('HS256', 'HS384', 'HS512'):
raise NotImplementedError('Algoritm %s not allowed' % algorithm) raise NotImplementedError('Algorithm %s not allowed' % algorithm)
self.verify_expiration = verify_expiration self.verify_expiration = verify_expiration
self.leeway = leeway self.leeway = leeway
self.expiration = expiration self.expiration = expiration
@@ -1314,6 +1314,7 @@ class AuthJWT(object):
We (mis)use the heavy default auth mechanism to avoid any further computation, We (mis)use the heavy default auth mechanism to avoid any further computation,
while sticking to a somewhat-stable Auth API. while sticking to a somewhat-stable Auth API.
""" """
# TODO: Check the following comment
## is the following safe or should we use ## is the following safe or should we use
## calendar.timegm(datetime.datetime.utcnow().timetuple()) ## calendar.timegm(datetime.datetime.utcnow().timetuple())
## result seem to be the same (seconds since epoch, in UTC) ## result seem to be the same (seconds since epoch, in UTC)
@@ -1395,8 +1396,9 @@ class AuthJWT(object):
self.alter_payload(payload) self.alter_payload(payload)
ret = {'token': self.generate_token(payload)} ret = {'token': self.generate_token(payload)}
elif ret is None: elif ret is None:
raise HTTP( raise HTTP(401,
401, u'Not Authorized - need to be logged in, to pass a token for refresh or username and password for login', u'Not Authorized - need to be logged in, to pass a token '
u'for refresh or username and password for login',
**{'WWW-Authenticate': u'JWT realm="%s"' % self.realm}) **{'WWW-Authenticate': u'JWT realm="%s"' % self.realm})
response.headers['Content-Type'] = 'application/json' response.headers['Content-Type'] = 'application/json'
return serializers.json(ret) return serializers.json(ret)
@@ -1743,7 +1745,7 @@ class Auth(object):
csrf_prevention=True, propagate_extension=None, csrf_prevention=True, propagate_extension=None,
url_index=None, jwt=None, host_names=None): url_index=None, jwt=None, host_names=None):
## next two lines for backward compatibility # next two lines for backward compatibility
if not db and environment and isinstance(environment, DAL): if not db and environment and isinstance(environment, DAL):
db = environment db = environment
self.db = db self.db = db
@@ -1974,10 +1976,8 @@ class Auth(object):
else: else:
next = '?_next=' + urllib.quote(URL(args=request.args, next = '?_next=' + urllib.quote(URL(args=request.args,
vars=request.get_vars)) vars=request.get_vars))
href = lambda function: '%s/%s%s' % (action, function, next href = lambda function: \
if referrer_actions is DEFAULT '%s/%s%s' % (action, function, next if referrer_actions is DEFAULT or function in referrer_actions else '')
or function in referrer_actions
else '')
if isinstance(prefix, str): if isinstance(prefix, str):
prefix = T(prefix) prefix = T(prefix)
if prefix: if prefix:
@@ -1990,9 +1990,7 @@ class Auth(object):
if self.user_id: # User is logged in if self.user_id: # User is logged in
logout_next = self.settings.logout_next logout_next = self.settings.logout_next
items.append({'name': T('Log Out'), items.append({'name': T('Log Out'),
'href': '%s/logout?_next=%s' % (action, 'href': '%s/logout?_next=%s' % (action, urllib.quote(logout_next)),
urllib.quote(
logout_next)),
'icon': 'icon-off'}) 'icon': 'icon-off'})
if 'profile' not in self.settings.actions_disabled: if 'profile' not in self.settings.actions_disabled:
items.append({'name': T('Profile'), 'href': href('profile'), items.append({'name': T('Profile'), 'href': href('profile'),
@@ -2207,8 +2205,7 @@ class Auth(object):
if ('id' in fieldnames and if ('id' in fieldnames and
'modified_on' in fieldnames and 'modified_on' in fieldnames and
not current_record in fieldnames): not current_record in fieldnames):
table._enable_record_versioning( table._enable_record_versioning(archive_db=archive_db,
archive_db=archive_db,
archive_name=archive_names, archive_name=archive_names,
current_record=current_record, current_record=current_record,
current_record_label=current_record_label) current_record_label=current_record_label)
@@ -2478,9 +2475,7 @@ class Auth(object):
Field('expires_on', 'datetime', default=datetime.datetime(2999, 12, 31)), Field('expires_on', 'datetime', default=datetime.datetime(2999, 12, 31)),
Field('token', writable=False, default=web2py_uuid, unique=True), Field('token', writable=False, default=web2py_uuid, unique=True),
*extra_fields, *extra_fields,
**dict( **dict(migrate=self.__get_migrate(settings.table_token_name, migrate),
migrate=self.__get_migrate(
settings.table_token_name, migrate),
fake_migrate=fake_migrate)) fake_migrate=fake_migrate))
if not db._lazy_tables: if not db._lazy_tables:
settings.table_user = db[settings.table_user_name] settings.table_user = db[settings.table_user_name]
@@ -2750,7 +2745,7 @@ class Auth(object):
redirect(session._cas_service) redirect(session._cas_service)
def cas_onaccept(form, onaccept=onaccept): def cas_onaccept(form, onaccept=onaccept):
if not onaccept is DEFAULT: if onaccept is not DEFAULT:
onaccept(form) onaccept(form)
return allow_access(interactivelogin=True) return allow_access(interactivelogin=True)
return self.login(next, onvalidation, cas_onaccept, log) return self.login(next, onvalidation, cas_onaccept, log)
@@ -2837,14 +2832,14 @@ class Auth(object):
response = current.response response = current.response
session = current.session session = current.session
### use session for federated login # use session for federated login
snext = self.get_vars_next() snext = self.get_vars_next()
if snext: if snext:
session._auth_next = snext session._auth_next = snext
elif session._auth_next: elif session._auth_next:
snext = session._auth_next snext = session._auth_next
### pass # pass
if next is DEFAULT: if next is DEFAULT:
# important for security # important for security
@@ -2950,7 +2945,7 @@ class Auth(object):
) )
captcha = settings.login_captcha or \ captcha = settings.login_captcha or \
(settings.login_captcha != False and settings.captcha) (settings.login_captcha is not False and settings.captcha)
if captcha: if captcha:
addrow(form, captcha.label, captcha, captcha.comment, addrow(form, captcha.label, captcha, captcha.comment,
settings.formstyle, 'captcha__row') settings.formstyle, 'captcha__row')
@@ -2978,8 +2973,7 @@ class Auth(object):
elif temp_user.registration_key in ('disabled', 'blocked'): elif temp_user.registration_key in ('disabled', 'blocked'):
response.flash = self.messages.login_disabled response.flash = self.messages.login_disabled
return form return form
elif (temp_user.registration_key is not None elif (temp_user.registration_key is not None and temp_user.registration_key.strip()):
and temp_user.registration_key.strip()):
response.flash = \ response.flash = \
self.messages.registration_verifying self.messages.registration_verifying
return form return form
@@ -3106,8 +3100,6 @@ class Auth(object):
hideerror=settings.hideerror): hideerror=settings.hideerror):
accepted_form = True accepted_form = True
accepted_form = True
''' '''
The lists is executed after form validation for each of the corresponding action. The lists is executed after form validation for each of the corresponding action.
For example, in your model: For example, in your model:
@@ -3385,8 +3377,7 @@ class Auth(object):
not self.settings.registration_requires_verification: not self.settings.registration_requires_verification:
table_user[form.vars.id] = dict(registration_key='pending') table_user[form.vars.id] = dict(registration_key='pending')
session.flash = self.messages.registration_pending session.flash = self.messages.registration_pending
elif (not self.settings.registration_requires_verification or elif (not self.settings.registration_requires_verification or self.settings.login_after_registration):
self.settings.login_after_registration):
if not self.settings.registration_requires_verification: if not self.settings.registration_requires_verification:
table_user[form.vars.id] = dict(registration_key='') table_user[form.vars.id] = dict(registration_key='')
session.flash = self.messages.registration_successful session.flash = self.messages.registration_successful
@@ -3464,7 +3455,7 @@ class Auth(object):
response = current.response response = current.response
session = current.session session = current.session
captcha = self.settings.retrieve_username_captcha or \ captcha = self.settings.retrieve_username_captcha or \
(self.settings.retrieve_username_captcha != False and self.settings.captcha) (self.settings.retrieve_username_captcha is not False and self.settings.captcha)
if not self.settings.mailer: if not self.settings.mailer:
response.flash = self.messages.function_disabled response.flash = self.messages.function_disabled
return '' return ''
@@ -3796,8 +3787,7 @@ class Auth(object):
requires=self.table_user()[passfield].requires), requires=self.table_user()[passfield].requires),
Field('new_password2', 'password', Field('new_password2', 'password',
label=self.messages.verify_password, label=self.messages.verify_password,
requires=[IS_EXPR( requires=[IS_EXPR('value==%s' % repr(request.vars.new_password),
'value==%s' % repr(request.vars.new_password),
self.messages.mismatched_password)]), self.messages.mismatched_password)]),
submit_button=self.messages.password_reset_button, submit_button=self.messages.password_reset_button,
hidden=dict(_next=next), hidden=dict(_next=next),
@@ -3831,7 +3821,7 @@ class Auth(object):
response = current.response response = current.response
session = current.session session = current.session
captcha = self.settings.retrieve_password_captcha or \ captcha = self.settings.retrieve_password_captcha or \
(self.settings.retrieve_password_captcha != False and self.settings.captcha) (self.settings.retrieve_password_captcha is not False and self.settings.captcha)
if next is DEFAULT: if next is DEFAULT:
next = self.get_vars_next() or self.settings.request_reset_password_next next = self.get_vars_next() or self.settings.request_reset_password_next
@@ -4242,10 +4232,8 @@ class Auth(object):
else: else:
next = self.here() next = self.here()
current.session.flash = current.response.flash current.session.flash = current.response.flash
return call_or_redirect( return call_or_redirect(self.settings.on_failed_authentication,
self.settings.on_failed_authentication, self.settings.login_url + '?_next=' + urllib.quote(next))
self.settings.login_url +
'?_next=' + urllib.quote(next))
if callable(condition): if callable(condition):
flag = condition() flag = condition()
@@ -4434,10 +4422,9 @@ class Auth(object):
membership = self.table_membership() membership = self.table_membership()
self.log_event(self.messages['del_membership_log'], self.log_event(self.messages['del_membership_log'],
dict(user_id=user_id, group_id=group_id)) dict(user_id=user_id, group_id=group_id))
ret = self.db(membership.user_id ret = self.db(membership.user_id == user_id)(membership.group_id == group_id).delete()
== user_id)(membership.group_id if group_id in self.user_groups:
== group_id).delete() del self.user_groups[group_id]
if group_id in self.user_groups: del self.user_groups[group_id]
return ret return ret
def has_permission(self, def has_permission(self,
@@ -4454,8 +4441,7 @@ class Auth(object):
""" """
if not group_id and self.settings.everybody_group_id and \ if not group_id and self.settings.everybody_group_id and \
self.has_permission( self.has_permission(name, table_name, record_id, user_id=None,
name, table_name, record_id, user_id=None,
group_id=self.settings.everybody_group_id): group_id=self.settings.everybody_group_id):
return True return True
@@ -4463,25 +4449,24 @@ class Auth(object):
user_id = self.user.id user_id = self.user.id
if user_id: if user_id:
membership = self.table_membership() membership = self.table_membership()
rows = self.db(membership.user_id rows = self.db(membership.user_id == user_id).select(membership.group_id)
== user_id).select(membership.group_id)
groups = set([row.group_id for row in rows]) groups = set([row.group_id for row in rows])
if group_id and group_id not in groups: if group_id and group_id not in groups:
return False return False
else: else:
groups = set([group_id]) groups = set([group_id])
permission = self.table_permission() permission = self.table_permission()
rows = self.db(permission.name == name)(permission.table_name rows = self.db(permission.name ==
== str(table_name))(permission.record_id name)(permission.table_name ==
== record_id).select(permission.group_id) str(table_name))(permission.record_id ==
record_id).select(permission.group_id)
groups_required = set([row.group_id for row in rows]) groups_required = set([row.group_id for row in rows])
if record_id: if record_id:
rows = self.db(permission.name rows = self.db(permission.name ==
== name)(permission.table_name name)(permission.table_name ==
== str(table_name))(permission.record_id str(table_name))(permission.record_id ==
== 0).select(permission.group_id) 0).select(permission.group_id)
groups_required = groups_required.union(set([row.group_id groups_required = groups_required.union(set([row.group_id for row in rows]))
for row in rows]))
if groups.intersection(groups_required): if groups.intersection(groups_required):
r = True r = True
else: else:
@@ -4509,8 +4494,8 @@ class Auth(object):
(permission.name == name) & (permission.name == name) &
(permission.table_name == str(table_name)) & (permission.table_name == str(table_name)) &
(permission.record_id == long(record_id)), (permission.record_id == long(record_id)),
ignore_common_filters=True).select( ignore_common_filters=True
limitby=(0, 1), orderby_on_limitby=False).first() ).select(limitby=(0, 1), orderby_on_limitby=False).first()
if record: if record:
if hasattr(record, 'is_active') and not record.is_active: if hasattr(record, 'is_active') and not record.is_active:
record.update_record(is_active=True) record.update_record(is_active=True)
@@ -4539,10 +4524,11 @@ class Auth(object):
self.log_event(self.messages['del_permission_log'], self.log_event(self.messages['del_permission_log'],
dict(group_id=group_id, name=name, dict(group_id=group_id, name=name,
table_name=table_name, record_id=record_id)) table_name=table_name, record_id=record_id))
return self.db(permission.group_id == group_id)(permission.name return self.db(permission.group_id ==
== name)(permission.table_name group_id)(permission.name ==
== str(table_name))(permission.record_id name)(permission.table_name ==
== long(record_id)).delete() str(table_name))(permission.record_id ==
long(record_id)).delete()
def accessible_query(self, name, table, user_id=None): def accessible_query(self, name, table, user_id=None):
""" """
@@ -4569,8 +4555,7 @@ class Auth(object):
cquery = table cquery = table
tablenames = db._adapter.tables(cquery) tablenames = db._adapter.tables(cquery)
for tablename in tablenames: for tablename in tablenames:
cquery &= self.accessible_query(name, tablename, cquery &= self.accessible_query(name, tablename, user_id=user_id)
user_id=user_id)
return cquery return cquery
if not isinstance(table, str) and \ if not isinstance(table, str) and \
self.has_permission(name, table, 0, user_id): self.has_permission(name, table, 0, user_id):
@@ -4639,8 +4624,7 @@ class Auth(object):
you can do, for example:: you can do, for example::
db.define_table('myhistory', db.define_table('myhistory',
Field('parent_record',db.mytable), Field('parent_record', db.mytable), db.mytable)
db.mytable)
and use it as:: and use it as::
@@ -4655,7 +4639,7 @@ class Auth(object):
table = form.table table = form.table
if not archive_table: if not archive_table:
archive_table_name = '%s_archive' % table archive_table_name = '%s_archive' % table
if not archive_table_name in table._db: if archive_table_name not in table._db:
table._db.define_table( table._db.define_table(
archive_table_name, archive_table_name,
Field(current_record, table), Field(current_record, table),
@@ -4910,18 +4894,16 @@ class Crud(object):
self.deleted = False self.deleted = False
captcha = self.settings.update_captcha or self.settings.captcha captcha = self.settings.update_captcha or self.settings.captcha
if record and captcha: if record and captcha:
addrow(form, captcha.label, captcha, captcha.comment, addrow(form, captcha.label, captcha, captcha.comment, self.settings.formstyle, 'captcha__row')
self.settings.formstyle, 'captcha__row')
captcha = self.settings.create_captcha or self.settings.captcha captcha = self.settings.create_captcha or self.settings.captcha
if not record and captcha: if not record and captcha:
addrow(form, captcha.label, captcha, captcha.comment, addrow(form, captcha.label, captcha, captcha.comment, self.settings.formstyle, 'captcha__row')
self.settings.formstyle, 'captcha__row')
if request.extension not in ('html', 'load'): if request.extension not in ('html', 'load'):
(_session, _formname) = (None, None) (_session, _formname) = (None, None)
else: else:
(_session, _formname) = ( (_session, _formname) = (
session, '%s/%s' % (table._tablename, form.record_id)) session, '%s/%s' % (table._tablename, form.record_id))
if not formname is DEFAULT: if formname is not DEFAULT:
_formname = formname _formname = formname
keepvalues = self.settings.keepvalues keepvalues = self.settings.keepvalues
if request.vars.delete_this_record: if request.vars.delete_this_record:
@@ -5210,7 +5192,7 @@ class Crud(object):
elif validate: elif validate:
value, error = field.validate(txtval) value, error = field.validate(txtval)
if not error: if not error:
### TODO deal with 'starts with', 'ends with', 'contains' on GAE # TODO deal with 'starts with', 'ends with', 'contains' on GAE
query &= self.get_query(field, opval, value) query &= self.get_query(field, opval, value)
else: else:
row[3].append(DIV(error, _class='error')) row[3].append(DIV(error, _class='error'))
@@ -5223,7 +5205,7 @@ class Crud(object):
results = db(query).select(*selected, **attributes) results = db(query).select(*selected, **attributes)
for r in refsearch: for r in refsearch:
results = results.find(r) results = results.find(r)
except: # hmmm, we should do better here except: # TODO: hmmm, we should do better here
results = None results = None
return form, results return form, results
@@ -5235,7 +5217,7 @@ def fetch(url, data=None, headers=None,
cookie=Cookie.SimpleCookie(), cookie=Cookie.SimpleCookie(),
user_agent='Mozilla/5.0'): user_agent='Mozilla/5.0'):
headers = headers or {} headers = headers or {}
if not data is None: if data is not None:
data = urllib.urlencode(data) data = urllib.urlencode(data)
if user_agent: if user_agent:
headers['User-agent'] = user_agent headers['User-agent'] = user_agent
@@ -5703,7 +5685,7 @@ class Service(object):
id, method, params = data.get('id'), data.get('method'), data.get('params', []) id, method, params = data.get('id'), data.get('method'), data.get('params', [])
if id is None: if id is None:
return return_error(0, 100, 'missing id') return return_error(0, 100, 'missing id')
if not method in methods: if method not in methods:
return return_error(id, 100, 'method "%s" does not exist' % method) return return_error(id, 100, 'method "%s" does not exist' % method)
try: try:
if isinstance(params, dict): if isinstance(params, dict):
@@ -5727,8 +5709,7 @@ class Service(object):
def return_response(id, result): def return_response(id, result):
if not must_respond: if not must_respond:
return None return None
return serializers.json({'jsonrpc': '2.0', return serializers.json({'jsonrpc': '2.0', 'id': id, 'result': result})
'id': id, 'result': result})
def return_error(id, code, message=None, data=None): def return_error(id, code, message=None, data=None):
error = {'code': code} error = {'code': code}
@@ -5739,9 +5720,7 @@ class Service(object):
error['message'] = message error['message'] = message
if data is not None: if data is not None:
error['data'] = data error['data'] = data
return serializers.json({'jsonrpc': '2.0', return serializers.json({'jsonrpc': '2.0', 'id': id, 'error': error})
'id': id,
'error': error})
def validate(data): def validate(data):
""" """
@@ -5801,7 +5780,7 @@ class Service(object):
return return_error(None, e.code, e.info) return return_error(None, e.code, e.info)
id, method, params = data.get('id'), data['method'], data.get('params', '') id, method, params = data.get('id'), data['method'], data.get('params', '')
if not method in methods: if method not in methods:
return return_error(id, -32601, data='Method "%s" does not exist' % method) return return_error(id, -32601, data='Method "%s" does not exist' % method)
try: try:
if isinstance(params, dict): if isinstance(params, dict):
@@ -6501,8 +6480,7 @@ class Wiki(object):
groups = self.settings.groups groups = self.settings.groups
return ('wiki_editor' in groups or return ('wiki_editor' in groups or
(page is None and 'wiki_author' in groups) or (page is None and 'wiki_author' in groups) or
not page is None and ( page is not None and (set(groups).intersection(set(page.can_edit)) or
set(groups).intersection(set(page.can_edit)) or
page.created_by == self.auth.user.id)) page.created_by == self.auth.user.id))
def can_manage(self): def can_manage(self):
@@ -6524,7 +6502,7 @@ class Wiki(object):
return True return True
return False return False
### END POLICY # END POLICY
def automenu(self): def automenu(self):
"""adds the menu if not present""" """adds the menu if not present"""
@@ -6742,19 +6720,14 @@ class Wiki(object):
if self.settings.templates: if self.settings.templates:
fields.append( fields.append(
Field("from_template", "reference wiki_page", Field("from_template", "reference wiki_page",
requires=IS_EMPTY_OR( requires=IS_EMPTY_OR(IS_IN_DB(db(self.settings.templates), db.wiki_page._id, '%(slug)s')),
IS_IN_DB(db(self.settings.templates), comment=current.T("Choose Template or empty for new Page")))
db.wiki_page._id,
'%(slug)s')),
comment=current.T(
"Choose Template or empty for new Page")))
form = SQLFORM.factory(*fields, **dict(_class="well")) form = SQLFORM.factory(*fields, **dict(_class="well"))
form.element("[type=submit]").attributes["_value"] = \ form.element("[type=submit]").attributes["_value"] = \
current.T("Create Page from Slug") current.T("Create Page from Slug")
if form.process().accepted: if form.process().accepted:
form.vars.from_template = 0 if not form.vars.from_template \ form.vars.from_template = 0 if not form.vars.from_template else form.vars.from_template
else form.vars.from_template
redirect(URL(args=('_edit', form.vars.slug, form.vars.from_template or 0))) # added param redirect(URL(args=('_edit', form.vars.slug, form.vars.from_template or 0))) # added param
return dict(content=form) return dict(content=form)
@@ -6882,7 +6855,7 @@ class Wiki(object):
if request.vars.q: if request.vars.q:
tags = [v.strip() for v in request.vars.q.split(',')] tags = [v.strip() for v in request.vars.q.split(',')]
tags = [v.lower() for v in tags if v] tags = [v.lower() for v in tags if v]
if tags or not query is None: if tags or query is not None:
db = self.auth.db db = self.auth.db
count = db.wiki_tag.wiki_page.count() count = db.wiki_tag.wiki_page.count()
fields = [db.wiki_page.id, db.wiki_page.slug, fields = [db.wiki_page.id, db.wiki_page.slug,