Skip to content

Commit

Permalink
make files more readable
Browse files Browse the repository at this point in the history
  • Loading branch information
loechel committed Jul 27, 2017
1 parent e2ec995 commit d3bc761
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 88 deletions.
3 changes: 2 additions & 1 deletion src/plone/api/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
# flake8: noqa
# flake8: NOQA: S401

from plone.api import content
from plone.api import env
from plone.api import group
Expand Down
31 changes: 21 additions & 10 deletions src/plone/api/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,14 @@ def create(
types = [fti.getId() for fti in container.allowedContentTypes()]

raise InvalidParameterError(
"Cannot add a '{0}' object to the container.\n"
"Cannot add a '{obj_type}' object to the container.\n"
'Allowed types are:\n'
'{1}\n'
'{2}'.format(type, '\n'.join(sorted(types)), e.message),
'{allowed_types}\n'
'{message}'.format(
obj_type=type,
allowed_types='\n'.join(sorted(types)),
message=e.message,
),
)

content = container[content_id]
Expand Down Expand Up @@ -143,8 +147,11 @@ def get(path=None, UID=None):
if path:
site = portal.get()
site_absolute_path = '/'.join(site.getPhysicalPath())
if not path.startswith('{0}'.format(site_absolute_path)):
path = '{0}{1}'.format(site_absolute_path, path)
if not path.startswith('{path}'.format(path=site_absolute_path)):
path = '{site_path}{relative_path}'.format(
site_path=site_absolute_path,
relative_path=path,
)

try:
return site.restrictedTraverse(path)
Expand Down Expand Up @@ -349,6 +356,7 @@ def _find_path(maps, path, current_state, start_state):
# transitions. i.e an initial state you are not able to return to.
if current_state not in maps:
return

for new_transition, from_states in maps[current_state]:
next_path = _copy(path)
if new_transition in path:
Expand Down Expand Up @@ -388,9 +396,9 @@ def _wf_transitions_for(workflow, from_state, to_state):
"""
exit_state_maps = {}
for state in workflow.states.objectValues():
for t in state.getTransitions():
exit_state_maps.setdefault(t, [])
exit_state_maps[t].append(state.getId())
for transition in state.getTransitions():
exit_state_maps.setdefault(transition, [])
exit_state_maps[transition].append(state.getId())

transition_maps = {}
for transition in workflow.transitions.objectValues():
Expand Down Expand Up @@ -544,9 +552,12 @@ def get_view(name=None, context=None, request=None):
# Raise an error if the requested view is not available.
if name not in available_view_names:
raise InvalidParameterError(
"Cannot find a view with name '{0}'.\n"
"Cannot find a view with name '{name}'.\n"
'Available views are:\n'
'{1}'.format(name, '\n'.join(sorted(available_view_names))),
'{views}'.format(
name=name,
views='\n'.join(sorted(available_view_names)),
),
)
return getMultiAdapter((context, request), name=name)

Expand Down
16 changes: 6 additions & 10 deletions src/plone/api/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import setSecurityManager
from App.config import getConfiguration
from contextlib import closing
from contextlib import contextmanager
from pkg_resources import get_distribution
from plone.api import portal
Expand Down Expand Up @@ -115,12 +116,12 @@ def _adopt_roles(roles):
# If the stack is empty, the default security policy gets used.
overriding_context = _GlobalRoleOverridingContext(roles)

sm = getSecurityManager()
sm.addContext(overriding_context)
security_manager = getSecurityManager()
security_manager.addContext(overriding_context)

yield

sm.removeContext(overriding_context)
security_manager.removeContext(overriding_context)


class _GlobalRoleOverridingContext(object):
Expand Down Expand Up @@ -208,13 +209,8 @@ def read_only_mode():
:returns: bool isReadOnly True if ZODB is read-only
:Example: :ref:`env_read_only_mode_example`
"""
isReadOnly = True
try:
conn = Globals.DB.open()
isReadOnly = conn.isReadOnly()
finally:
conn.close()
return isReadOnly
with closing(Globals.DB.open()) as connection:
return connection.isReadOnly()


def plone_version():
Expand Down
27 changes: 16 additions & 11 deletions src/plone/api/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ def create(
"""
group_tool = portal.get_tool('portal_groups')
group_tool.addGroup(
groupname, roles, groups,
groupname,
roles,
groups,
title=title,
description=description,
)
Expand Down Expand Up @@ -241,8 +243,8 @@ def get_roles(groupname=None, group=None, obj=None, inherit=True):
pas = portal.get_tool('acl_users')
for _, lrmanager in pas.plugins.listPlugins(ILocalRolesPlugin):
for adapter in lrmanager._getAdapters(obj):
for pid in principal_ids:
roles.update(adapter.getRoles(pid))
for principal_id in principal_ids:
roles.update(adapter.getRoles(principal_id))
return list(roles)


Expand Down Expand Up @@ -278,10 +280,11 @@ def grant_roles(groupname=None, group=None, roles=None, obj=None):
# only roles persistent on the object, not from other providers
actual_roles = obj.get_local_roles_for_userid(group_id)

if actual_roles.count('Anonymous'):
actual_roles.remove('Anonymous')
if actual_roles.count('Authenticated'):
actual_roles.remove('Authenticated')
actual_roles = [
role
for role in actual_roles
if role not in ['Anonymous', 'Authenticated']
]

roles = list(set(actual_roles) | set(roles))
portal_groups = portal.get_tool('portal_groups')
Expand Down Expand Up @@ -322,10 +325,12 @@ def revoke_roles(groupname=None, group=None, roles=None, obj=None):
actual_roles = get_roles(groupname=group_id)
else:
actual_roles = get_roles(groupname=group_id, obj=obj, inherit=False)
if actual_roles.count('Anonymous'):
actual_roles.remove('Anonymous')
if actual_roles.count('Authenticated'):
actual_roles.remove('Authenticated')

actual_roles = [
role
for role in actual_roles
if role not in ['Anonymous', 'Authenticated']
]

roles = list(set(actual_roles) - set(roles))
portal_groups = portal.get_tool('portal_groups')
Expand Down
42 changes: 23 additions & 19 deletions src/plone/api/portal.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,9 @@ def get_tool(name=None):
tools.append(id)

raise InvalidParameterError(
"Cannot find a tool with name '{0}'.\n"
"Cannot find a tool with name '{name}'.\n"
'Available tools are:\n'
'{1}'.format(name, '\n'.join(tools)),
'{tools}'.format(name=name, tools='\n'.join(tools)),
)


Expand Down Expand Up @@ -308,12 +308,13 @@ def get_registry_record(name=None, interface=None, default=MISSING):
# Show all records on the interface.
records = [key for key in interface.names()]
msg = (
"Cannot find a record with name '{0}' on interface {1}.\n"
"Cannot find a record with name '{name}'"
" on interface {identifier}.\n"
'Did you mean?\n'
'{2}'.format(
name,
interface.__identifier__,
'\n'.join(records),
'{records}'.format(
name=name,
identifier=interface.__identifier__,
records='\n'.join(records),
)
)
raise InvalidParameterError(msg)
Expand All @@ -327,14 +328,14 @@ def get_registry_record(name=None, interface=None, default=MISSING):
# Show all records that 'look like' name.
# We don't dump the whole list, because it 1500+ items.
msg = (
"Cannot find a record with name '{0}'".format(name)
"Cannot find a record with name '{name}'".format(name=name)
)
records = [key for key in registry.records.keys() if name in key]
if records:
msg = (
'{0}\n'
'{message}\n'
'Did you mean?:\n'
'{1}'.format(msg, '\n'.join(records))
'{records}'.format(message=msg, records='\n'.join(records))
)
raise InvalidParameterError(msg)

Expand Down Expand Up @@ -369,19 +370,22 @@ def set_registry_record(name=None, value=None, interface=None):

from zope.schema._bootstrapinterfaces import WrongType
try:
registry['{0}.{1}'.format(interface.__identifier__, name)] = value
registry['{identifier}.{name}'.format(
identifier=interface.__identifier__,
name=name
)] = value
except WrongType:
field_type = [
f[1]
for f in interface.namesAndDescriptions()
if f[0] == 'field_one'
field[1]
for field in interface.namesAndDescriptions()
if field[0] == 'field_one'
][0]
raise InvalidParameterError(
u'The value parameter for the field {0} needs to be {1}'
u'instead of {2}'.format(
name,
str(field_type.__class__),
type(value),
u'The value parameter for the field {name} needs to be '
u'{of_class} instead of {of_type}'.format(
name=name,
of_class=str(field_type.__class__),
of_type=type(value),
),
)

Expand Down
29 changes: 15 additions & 14 deletions src/plone/api/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ def create(

try:
use_email_as_username = portal.get_registry_record(
'plone.use_email_as_login')
'plone.use_email_as_login',
)
except InvalidParameterError:
site = portal.get()
props = site.portal_properties
Expand All @@ -78,7 +79,7 @@ def create(
# Generate a random 8-char password
if not password:
chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for x in range(8))
password = ''.join(random.choice(chars) for char in range(8))

properties.update(username=user_id)
properties.update(email=email)
Expand Down Expand Up @@ -250,12 +251,12 @@ def get_roles(username=None, user=None, obj=None, inherit=True):
plone_user = user.getUser()
principal_ids = list(plone_user.getGroups())
principal_ids.insert(0, plone_user.getId())
roles = set([])
roles = set()
pas = portal.get_tool('acl_users')
for _, lrmanager in pas.plugins.listPlugins(ILocalRolesPlugin):
for adapter in lrmanager._getAdapters(obj):
for pid in principal_ids:
roles.update(adapter.getRoles(pid))
for principal_id in principal_ids:
roles.update(adapter.getRoles(principal_id))
return list(roles)
else:
return user.getRoles()
Expand Down Expand Up @@ -298,7 +299,7 @@ def get_permissions(username=None, user=None, obj=None):
result = {}
with context:
portal_membership = portal.get_tool('portal_membership')
permissions = (p[0] for p in getPermissions())
permissions = (permission[0] for permission in getPermissions())
for permission in permissions:
result[permission] = bool(
portal_membership.checkPermission(permission, obj),
Expand Down Expand Up @@ -420,23 +421,23 @@ def revoke_roles(username=None, user=None, obj=None, roles=None):
if user is None:
raise InvalidParameterError('User could not be found')

if isinstance(roles, tuple):
roles = list(roles)
roles = set(roles)

if 'Anonymous' in roles or 'Authenticated' in roles:
raise InvalidParameterError

inherit = True
if obj is not None:
# if obj, get only a list of local roles, without inherited ones
inherit = False

actual_roles = list(get_roles(user=user, obj=obj, inherit=inherit))
if actual_roles.count('Anonymous'):
actual_roles.remove('Anonymous')
if actual_roles.count('Authenticated'):
actual_roles.remove('Authenticated')
actual_roles = set([
role
for role in get_roles(user=user, obj=obj, inherit=inherit)
if role not in ['Anonymous', 'Authenticated']
])

roles = list(set(actual_roles) - set(roles))
roles = list(actual_roles - roles)

if obj is None:
user.setSecurityProfile(roles=roles)
Expand Down
Loading

1 comment on commit d3bc761

@jenkins-plone-org
Copy link

Choose a reason for hiding this comment

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

@loechel Jenkins CI reporting about code analysis
See the full report here: http://jenkins.plone.org/job/package-plone.api/39/violations

src/plone/api/content.py:53:13: C816 missing trailing comma in Python 3.6+
src/plone/api/portal.py:263:20: T000 Todo note found.
src/plone/api/portal.py:312:13: Q000 Remove bad quotes.
src/plone/api/portal.py:373:22: S100 First argument on the same line
src/plone/api/portal.py:373:50: S101 Multi-line construct missing trailing comma
src/plone/api/portal.py:375:17: S101 Multi-line construct missing trailing comma
src/plone/api/portal.py:375:26: C812 missing trailing comma
src/plone/api/tests/test_user.py:332:30: T000 Todo note found.

Follow these instructions to reproduce it locally.

Please sign in to comment.