From 6e6a70916541283e1050f408e2835546375c86b5 Mon Sep 17 00:00:00 2001 From: Matthew Jones Date: Tue, 3 Feb 2015 13:46:58 -0500 Subject: [PATCH] Fixing up some pep8 issues --- awx/api/authentication.py | 2 +- awx/api/generics.py | 6 ++-- awx/api/permissions.py | 3 +- awx/api/renderers.py | 4 +-- awx/api/serializers.py | 17 +++++----- awx/api/tests/decorator_paginated.py | 1 + awx/api/views.py | 48 ++++++++++++---------------- awx/main/access.py | 12 +++---- awx/main/registrar.py | 2 -- awx/main/signals.py | 1 + awx/main/tasks.py | 16 +++++----- awx/main/utils.py | 6 ++-- 12 files changed, 54 insertions(+), 64 deletions(-) diff --git a/awx/api/authentication.py b/awx/api/authentication.py index bbe96dbacd..902c7a35fa 100644 --- a/awx/api/authentication.py +++ b/awx/api/authentication.py @@ -20,7 +20,7 @@ class TokenAuthentication(authentication.TokenAuthentication): def _get_x_auth_token_header(self, request): auth = request.META.get('HTTP_X_AUTH_TOKEN', '') - if type(auth) == type(''): + if isinstance(auth, type('')): # Work around django test client oddness auth = auth.encode(HTTP_HEADER_ENCODING) return auth diff --git a/awx/api/generics.py b/awx/api/generics.py index 30def04f42..344d67b28a 100644 --- a/awx/api/generics.py +++ b/awx/api/generics.py @@ -176,7 +176,7 @@ class GenericAPIView(generics.GenericAPIView, APIView): # Override when called from browsable API to generate raw data form; # always remove read only fields from sample raw data. if hasattr(self, '_raw_data_form_marker'): - for name, field in serializer.fields.items(): + for name, field in serializer.fields.items(): if getattr(field, 'read_only', None): del serializer.fields[name] return serializer @@ -476,9 +476,9 @@ class RetrieveDestroyAPIView(RetrieveAPIView, generics.RetrieveDestroyAPIView): # somewhat lame that delete has to call it's own permissions check obj = self.get_object() # FIXME: Why isn't the active check being caught earlier by RBAC? - if getattr(obj, 'active', True) == False: + if not getattr(obj, 'active', True): raise Http404() - if getattr(obj, 'is_active', True) == False: + if not getattr(obj, 'is_active', True): raise Http404() if not request.user.can_access(self.model, 'delete', obj): raise PermissionDenied() diff --git a/awx/api/permissions.py b/awx/api/permissions.py index e5165a32c8..92af524b2f 100644 --- a/awx/api/permissions.py +++ b/awx/api/permissions.py @@ -107,8 +107,7 @@ class ModelAccessPermission(permissions.BasePermission): # Check permissions for the given view and object, based on the request # method used. - check_method = getattr(self, 'check_%s_permissions' % \ - request.method.lower(), None) + check_method = getattr(self, 'check_%s_permissions' % request.method.lower(), None) result = check_method and check_method(request, view, obj) if not result: raise PermissionDenied() diff --git a/awx/api/renderers.py b/awx/api/renderers.py index 2b575832ac..c38b02941a 100644 --- a/awx/api/renderers.py +++ b/awx/api/renderers.py @@ -30,9 +30,9 @@ class BrowsableAPIRenderer(renderers.BrowsableAPIRenderer): '''Never show auto-generated form (only raw form).''' obj = getattr(view, 'object', None) if not self.show_form_for_method(view, method, request, obj): - return + return if method in ('DELETE', 'OPTIONS'): - return True # Don't actually need to return a form + return True # Don't actually need to return a form def get_context(self, data, accepted_media_type, renderer_context): context = super(BrowsableAPIRenderer, self).get_context(data, accepted_media_type, renderer_context) diff --git a/awx/api/serializers.py b/awx/api/serializers.py index c6a2dbd2f5..6b14696b1c 100644 --- a/awx/api/serializers.py +++ b/awx/api/serializers.py @@ -42,7 +42,7 @@ from awx.main.utils import update_scm_url, get_type_for_model, get_model_for_typ logger = logging.getLogger('awx.api.serializers') # Fields that should be summarized regardless of object type. -DEFAULT_SUMMARY_FIELDS = ('name', 'description')#, 'created_by', 'modified_by')#, 'type') +DEFAULT_SUMMARY_FIELDS = ('name', 'description')# , 'created_by', 'modified_by')#, 'type') # Keys are fields (foreign keys) where, if found on an instance, summary info # should be added to the serialized data. Values are a tuple of field names on @@ -93,7 +93,7 @@ class ChoiceField(fields.ChoiceField): # Remove extra blank option if one is already present (for writable # field) or if present at all for read-only fields. if ([x[0] for x in self.choices].count(u'') > 1 or self.read_only) \ - and BLANK_CHOICE_DASH[0] in self.choices: + and BLANK_CHOICE_DASH[0] in self.choices: self.choices = [x for x in self.choices if x != BLANK_CHOICE_DASH[0]] @@ -450,10 +450,10 @@ class UnifiedJobListSerializer(UnifiedJobSerializer): 'result_stdout') def get_types(self): - if type(self) is UnifiedJobListSerializer: - return ['project_update', 'inventory_update', 'job', 'system_job'] - else: - return super(UnifiedJobListSerializer, self).get_types() + if type(self) is UnifiedJobListSerializer: + return ['project_update', 'inventory_update', 'job', 'system_job'] + else: + return super(UnifiedJobListSerializer, self).get_types() def to_native(self, obj): serializer_class = None @@ -495,7 +495,7 @@ class UnifiedJobStdoutSerializer(UnifiedJobSerializer): class UserSerializer(BaseSerializer): password = serializers.WritableField(required=False, default='', - help_text='Write-only field used to change the password.') + help_text='Write-only field used to change the password.') ldap_dn = serializers.Field(source='profile.ldap_dn') class Meta: @@ -805,8 +805,7 @@ class HostSerializer(BaseSerializerWithVariables): pass d.update({'recent_jobs': [{ 'id': j.job.id, - 'name': j.job.job_template.name if j.job.job_template is not None - else "", + 'name': j.job.job_template.name if j.job.job_template is not None else "", 'status': j.job.status, 'finished': j.job.finished, } for j in obj.job_host_summaries.filter(job__active=True).select_related('job__job_template').order_by('-created')[:5]]}) diff --git a/awx/api/tests/decorator_paginated.py b/awx/api/tests/decorator_paginated.py index 0e63327fa0..e7b43cd6e2 100644 --- a/awx/api/tests/decorator_paginated.py +++ b/awx/api/tests/decorator_paginated.py @@ -23,6 +23,7 @@ class PaginatedDecoratorTests(TestCase): # that the paginator wraps in the way we expect. class View(APIView): permission_classes = (AllowAny,) + @paginated def get(self, request, limit, ordering, offset): return ['a', 'b', 'c', 'd', 'e'], 26, None diff --git a/awx/api/views.py b/awx/api/views.py index 8b53bf872f..a4ee137a28 100644 --- a/awx/api/views.py +++ b/awx/api/views.py @@ -82,11 +82,11 @@ class ApiRootView(APIView): current = reverse('api:api_v1_root_view', args=[]) data = dict( - description = 'Ansible Tower REST API', - current_version = current, - available_versions = dict( - v1 = current - ) + description = 'Ansible Tower REST API', + current_version = current, + available_versions = dict( + v1 = current + ) ) return Response(data) @@ -335,7 +335,7 @@ class DashboardView(APIView): data['organizations'] = {'url': reverse('api:organization_list'), 'total': organization_list.count()} data['teams'] = {'url': reverse('api:team_list'), - 'total': team_list.count()} + 'total': team_list.count()} data['credentials'] = {'url': reverse('api:credential_list'), 'total': credential_list.count()} data['job_templates'] = {'url': reverse('api:job_template_list'), @@ -421,7 +421,7 @@ class DashboardInventoryGraphView(APIView): host_data = [] for element in created_hosts.time_series(end_date, start_date, interval=interval)[::-1]: host_data.append([time.mktime(element[0].timetuple()), - count_hosts - last_delta]) + count_hosts - last_delta]) count_hosts -= last_delta last_delta = element[1] @@ -1068,9 +1068,9 @@ class GroupHostsList(SubListCreateAPIView): def create(self, request, *args, **kwargs): parent_group = Group.objects.get(id=self.kwargs['pk']) existing_hosts = Host.objects.filter(inventory=parent_group.inventory, name=request.DATA['name']) - if existing_hosts.count() > 0 and ('variables' not in request.DATA or \ - request.DATA['variables'] == '' or \ - request.DATA['variables'] == '{}' or \ + if existing_hosts.count() > 0 and ('variables' not in request.DATA or + request.DATA['variables'] == '' or + request.DATA['variables'] == '{}' or request.DATA['variables'] == '---'): request.DATA['id'] = existing_hosts[0].id return self.attach(request, *args, **kwargs) @@ -1121,9 +1121,9 @@ class GroupDetail(RetrieveUpdateDestroyAPIView): def destroy(self, request, *args, **kwargs): obj = self.get_object() # FIXME: Why isn't the active check being caught earlier by RBAC? - if getattr(obj, 'active', True) == False: + if not getattr(obj, 'active', True): raise Http404() - if getattr(obj, 'is_active', True) == False: + if not getattr(obj, 'is_active', True): raise Http404() if not request.user.can_access(self.model, 'delete', obj): raise PermissionDenied() @@ -1178,8 +1178,7 @@ class InventoryScriptView(RetrieveAPIView): model = Inventory serializer_class = InventoryScriptSerializer - authentication_classes = [JobTaskAuthentication] + \ - api_settings.DEFAULT_AUTHENTICATION_CLASSES + authentication_classes = [JobTaskAuthentication] + api_settings.DEFAULT_AUTHENTICATION_CLASSES permission_classes = (JobTaskPermission,) filter_backends = () @@ -1319,9 +1318,9 @@ class InventoryInventorySourcesList(SubListAPIView): class InventorySourceList(ListAPIView): - model = InventorySource - serializer_class = InventorySourceSerializer - new_in_14 = True + model = InventorySource + serializer_class = InventorySourceSerializer + new_in_14 = True class InventorySourceDetail(RetrieveUpdateAPIView): @@ -1950,8 +1949,7 @@ class GroupJobEventsList(BaseJobEventsList): class JobJobEventsList(BaseJobEventsList): parent_model = Job - authentication_classes = [JobTaskAuthentication] + \ - api_settings.DEFAULT_AUTHENTICATION_CLASSES + authentication_classes = [JobTaskAuthentication] + api_settings.DEFAULT_AUTHENTICATION_CLASSES permission_classes = (JobTaskPermission,) # Post allowed for job event callback only. @@ -1973,8 +1971,7 @@ class JobJobPlaysList(BaseJobEventsList): parent_model = Job view_name = 'Job Plays List' - authentication_classes = [JobTaskAuthentication] + \ - api_settings.DEFAULT_AUTHENTICATION_CLASSES + authentication_classes = [JobTaskAuthentication] + api_settings.DEFAULT_AUTHENTICATION_CLASSES permission_classes = (JobTaskPermission,) new_in_200 = True @@ -2028,7 +2025,7 @@ class JobJobPlaysList(BaseJobEventsList): elif event_aggregate['event'] == 'runner_on_unreachable': unreachable_count = event_aggregate['id__count'] for change_aggregate in change_aggregates: - if change_aggregate['changed'] == False: + if not change_aggregate['changed']: ok_count = change_aggregate['id__count'] else: changed_count = change_aggregate['id__count'] @@ -2050,8 +2047,7 @@ class JobJobTasksList(BaseJobEventsList): and their completion status. """ parent_model = Job - authentication_classes = [JobTaskAuthentication] + \ - api_settings.DEFAULT_AUTHENTICATION_CLASSES + authentication_classes = [JobTaskAuthentication] + api_settings.DEFAULT_AUTHENTICATION_CLASSES permission_classes = (JobTaskPermission,) view_name = 'Job Play Tasks List' new_in_200 = True @@ -2141,9 +2137,7 @@ class JobJobTasksList(BaseJobEventsList): 'host_count': 0, 'id': task_start_event.id, 'modified': task_start_event.modified, - 'name': 'Gathering Facts' if - task_start_event.event == 'playbook_on_setup' else - task_start_event.task, + 'name': 'Gathering Facts' if task_start_event.event == 'playbook_on_setup' else task_start_event.task, 'reported_hosts': 0, 'skipped_count': 0, 'unreachable_count': 0, diff --git a/awx/main/access.py b/awx/main/access.py index b43c18dc1a..69c0c5cf40 100644 --- a/awx/main/access.py +++ b/awx/main/access.py @@ -355,7 +355,7 @@ class HostAccess(BaseAccess): inventory_pk = get_pk_from_dict(data, 'inventory') inventory = get_object_or_400(Inventory, pk=inventory_pk) if not self.user.can_access(Inventory, 'change', inventory, None): - return False + return False # Check to see if we have enough licenses reader = TaskSerializer() @@ -1000,8 +1000,7 @@ class JobTemplateAccess(BaseAccess): obj.job_type == PERM_INVENTORY_CHECK: has_perm = True - dep_access = self.user.can_access(Inventory, 'read', obj.inventory) and \ - self.user.can_access(Project, 'read', obj.project) + dep_access = self.user.can_access(Inventory, 'read', obj.inventory) and self.user.can_access(Project, 'read', obj.project) return dep_access and has_perm def can_change(self, obj, data): @@ -1150,8 +1149,7 @@ class JobAccess(BaseAccess): has_perm = False if obj.job_template is not None and self.user.can_access(JobTemplate, 'start', obj.job_template): has_perm = True - dep_access = self.user.can_access(Inventory, 'read', obj.inventory) and \ - self.user.can_access(Project, 'read', obj.project) + dep_access = self.user.can_access(Inventory, 'read', obj.inventory) and self.user.can_access(Project, 'read', obj.project) return self.can_read(obj) and dep_access and has_perm def can_cancel(self, obj): @@ -1317,8 +1315,8 @@ class ScheduleAccess(BaseAccess): inventory_source_qs = self.user.get_queryset(InventorySource) project_qs = self.user.get_queryset(Project) unified_qs = UnifiedJobTemplate.objects.filter(jobtemplate__in=job_template_qs) | \ - UnifiedJobTemplate.objects.filter(Q(project__in=project_qs)) | \ - UnifiedJobTemplate.objects.filter(Q(inventorysource__in=inventory_source_qs)) + UnifiedJobTemplate.objects.filter(Q(project__in=project_qs)) | \ + UnifiedJobTemplate.objects.filter(Q(inventorysource__in=inventory_source_qs)) return qs.filter(unified_job_template__in=unified_qs) def can_read(self, obj): diff --git a/awx/main/registrar.py b/awx/main/registrar.py index dd28844528..d5f4dad030 100644 --- a/awx/main/registrar.py +++ b/awx/main/registrar.py @@ -18,7 +18,6 @@ class ActivityStreamRegistrar(object): return from awx.main.signals import activity_stream_create, activity_stream_update, activity_stream_delete, activity_stream_associate - #(receiver, sender=model, dispatch_uid=self._dispatch_uid(signal, model)) if model not in self.models: self.models.append(model) post_save.connect(activity_stream_create, sender=model, dispatch_uid=str(self.__class__) + str(model) + "_create") @@ -32,7 +31,6 @@ class ActivityStreamRegistrar(object): dispatch_uid=str(self.__class__) + str(m2m_attr.through) + "_associate") except AttributeError: pass - #logger.warning("Failed to attach m2m activity stream tracker on class %s attribute %s" % (model, m2mfield.name)) def disconnect(self, model): if model in self.models: diff --git a/awx/main/signals.py b/awx/main/signals.py index 265d032df3..73b65c1f15 100644 --- a/awx/main/signals.py +++ b/awx/main/signals.py @@ -270,6 +270,7 @@ def update_host_last_job_after_job_deleted(sender, **kwargs): class ActivityStreamEnabled(threading.local): def __init__(self): self.enabled = getattr(settings, 'ACTIVITY_STREAM_ENABLED', True) + def __nonzero__(self): return bool(self.enabled) diff --git a/awx/main/tasks.py b/awx/main/tasks.py index 59b38d1142..d4ad114bdf 100644 --- a/awx/main/tasks.py +++ b/awx/main/tasks.py @@ -74,6 +74,7 @@ def tower_periodic_scheduler(self): return last_run except Exception, e: return None + def write_last_run(last_run): fd = open(settings.SCHEDULE_METADATA_LOCATION, 'w') fd.write(last_run.isoformat()) @@ -208,7 +209,8 @@ class BaseTask(Task): # tried too many times. if _attempt < 5: time.sleep(5) - return self.update_model(pk, + return self.update_model( + pk, _attempt=_attempt + 1, output_replacements=output_replacements, **updates @@ -238,7 +240,7 @@ class BaseTask(Task): Create a temporary directory for job-related files. ''' path = tempfile.mkdtemp(prefix='ansible_tower_') - os.chmod(path, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR) + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) return path def build_private_data_file(self, instance, **kwargs): @@ -251,7 +253,7 @@ class BaseTask(Task): f = os.fdopen(handle, 'w') f.write(private_data) f.close() - os.chmod(path, stat.S_IRUSR|stat.S_IWUSR) + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR) return path else: return '' @@ -750,11 +752,9 @@ class RunProjectUpdate(BaseTask): passwords = super(RunProjectUpdate, self).build_passwords(project_update, **kwargs) if project_update.credential: - passwords['scm_key_unlock'] = decrypt_field(project_update.credential, - 'ssh_key_unlock') + passwords['scm_key_unlock'] = decrypt_field(project_update.credential, 'ssh_key_unlock') passwords['scm_username'] = project_update.credential.username - passwords['scm_password'] = decrypt_field(project_update.credential, - 'password') + passwords['scm_password'] = decrypt_field(project_update.credential, 'password') return passwords def build_env(self, project_update, **kwargs): @@ -1113,7 +1113,7 @@ class RunInventoryUpdate(BaseTask): raise RuntimeError('Inventory Script does not exist') f.write(inventory_update.source_script.script.encode('utf-8')) f.close() - os.chmod(path, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR) + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) args.append(runpath) args.append("--custom") # try: diff --git a/awx/main/utils.py b/awx/main/utils.py index 4da65e79bf..b5754de8bd 100644 --- a/awx/main/utils.py +++ b/awx/main/utils.py @@ -431,7 +431,7 @@ def build_proot_temp_dir(): Create a temporary directory for proot to use. ''' path = tempfile.mkdtemp(prefix='ansible_tower_proot_') - os.chmod(path, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR) + os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) return path def wrap_args_with_proot(args, cwd, **kwargs): @@ -455,11 +455,11 @@ def wrap_args_with_proot(args, cwd, **kwargs): continue if os.path.isdir(path): new_path = tempfile.mkdtemp(dir=kwargs['proot_temp_dir']) - os.chmod(new_path, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR) + os.chmod(new_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) else: handle, new_path = tempfile.mkstemp(dir=kwargs['proot_temp_dir']) os.close(handle) - os.chmod(new_path, stat.S_IRUSR|stat.S_IWUSR) + os.chmod(new_path, stat.S_IRUSR | stat.S_IWUSR) new_args.extend(['-b', '%s:%s' % (new_path, path)]) if 'private_data_dir' in kwargs: show_paths = [cwd, kwargs['private_data_dir']]