diff options
53 files changed, 252 insertions, 329 deletions
@@ -55,7 +55,6 @@ disable= duplicate-code, inconsistent-return-statements, # TODO interface-not-implemented, - no-else-return, no-self-use, # python3 way: Let's do it once we have a consensus. super-with-arguments, # TODO diff --git a/horizon/base.py b/horizon/base.py index 690e3e47b..7c577f3fb 100644 --- a/horizon/base.py +++ b/horizon/base.py @@ -768,8 +768,7 @@ class Site(Registry, HorizonComponent): key=operator.attrgetter('name')) dashboards.extend(extra) return dashboards - else: - return sorted(self._registry.values()) + return sorted(self._registry.values()) def get_default_dashboard(self): """Returns the default :class:`~horizon.Dashboard` instance. @@ -780,10 +779,9 @@ class Site(Registry, HorizonComponent): """ if self.default_dashboard: return self._registered(self.default_dashboard) - elif self._registry: + if self._registry: return self.get_dashboards()[0] - else: - raise NotRegistered("No dashboard modules have been registered.") + raise NotRegistered("No dashboard modules have been registered.") def get_user_home(self, user): """Returns the default URL for a particular user. @@ -810,13 +808,12 @@ class Site(Registry, HorizonComponent): if user_home: if callable(user_home): return user_home(user) - elif isinstance(user_home, str): + if isinstance(user_home, str): # Assume we've got a URL if there's a slash in it if '/' in user_home: return user_home - else: - mod, func = user_home.rsplit(".", 1) - return getattr(import_module(mod), func)(user) + mod, func = user_home.rsplit(".", 1) + return getattr(import_module(mod), func)(user) # If it's not callable and not a string, it's wrong. raise ValueError('The user_home setting must be either a string ' 'or a callable object (e.g. a function).') diff --git a/horizon/decorators.py b/horizon/decorators.py index 372e0c5ed..fa67761b8 100644 --- a/horizon/decorators.py +++ b/horizon/decorators.py @@ -88,8 +88,7 @@ def require_perms(view_func, required): # If we don't have any permissions, just return the original view. if required: return dec - else: - return view_func + return view_func def require_component_access(view_func, component): diff --git a/horizon/forms/fields.py b/horizon/forms/fields.py index 2710db07d..defe33106 100644 --- a/horizon/forms/fields.py +++ b/horizon/forms/fields.py @@ -365,8 +365,7 @@ class DynamicSelectWidget(SelectWidget): if self.add_item_link_args: return urls.reverse(self.add_item_link, args=self.add_item_link_args) - else: - return urls.reverse(self.add_item_link) + return urls.reverse(self.add_item_link) except urls.NoReverseMatch: return self.add_item_link diff --git a/horizon/forms/views.py b/horizon/forms/views.py index ba61131fa..50f0ecfcb 100644 --- a/horizon/forms/views.py +++ b/horizon/forms/views.py @@ -217,7 +217,7 @@ class ModalFormView(ModalFormMixin, views.HorizonFormView): # and implemented. response['X-Horizon-Location'] = success_url return response - else: - # If handled didn't return, we can assume something went - # wrong, and we should send back the form as-is. - return self.form_invalid(form) + + # If handled didn't return, we can assume something went + # wrong, and we should send back the form as-is. + return self.form_invalid(form) diff --git a/horizon/tables/actions.py b/horizon/tables/actions.py index 406575d78..617c1f508 100644 --- a/horizon/tables/actions.py +++ b/horizon/tables/actions.py @@ -401,8 +401,7 @@ class LinkAction(BaseAction): if datum: obj_id = self.table.get_object_id(datum) return urls.reverse(self.url, args=(obj_id,)) - else: - return urls.reverse(self.url) + return urls.reverse(self.url) except urls.NoReverseMatch as ex: LOG.info('No reverse found for "%(url)s": %(exception)s', {'url': self.url, 'exception': ex}) diff --git a/horizon/tables/base.py b/horizon/tables/base.py index f24045fb5..93d44f8d8 100644 --- a/horizon/tables/base.py +++ b/horizon/tables/base.py @@ -661,8 +661,7 @@ class Row(html.HTMLElement): column_names = self.table._meta.status_columns if column_names: return self.table.get_row_status_class(self.status) - else: - return '' + return '' def render(self): return render_to_string("horizon/common/_data_table_row.html", @@ -858,10 +857,9 @@ class Cell(html.HTMLElement): """Returns a css class name determined by the status value.""" if status is True: return "status_up" - elif status is False: + if status is False: return "status_down" - else: - return "warning" + return "warning" def get_default_classes(self): """Returns a flattened string of the cell's CSS classes.""" @@ -1643,7 +1641,7 @@ class DataTable(object, metaclass=DataTableMetaclass): obj_ids = [obj_id] response = action.multiple(self, self.request, obj_ids) return response - elif action and action.requires_input and not (obj_id or obj_ids): + if action and action.requires_input and not (obj_id or obj_ids): messages.info(self.request, _("Please select a row before taking that action.")) return None @@ -1688,8 +1686,7 @@ class DataTable(object, metaclass=DataTableMetaclass): if request.is_ajax(): if not error: return HttpResponse(new_row.render()) - else: - return HttpResponse(status=error.status_code) + return HttpResponse(status=error.status_code) elif new_row.ajax_cell_action_name == action_name: # inline edit of the cell actions return self.inline_edit_handle(request, table_name, @@ -1749,8 +1746,7 @@ class DataTable(object, metaclass=DataTableMetaclass): if request.is_ajax(): if not error: return HttpResponse(cell.render()) - else: - return HttpResponse(status=error.status_code) + return HttpResponse(status=error.status_code) def inline_update_action(self, request, datum, cell, obj_id, cell_name): """Handling update by POST of the cell.""" @@ -1907,10 +1903,9 @@ class DataTable(object, metaclass=DataTableMetaclass): values = statuses.values() if any([status is False for status in values]): return False - elif any([status is None for status in values]): + if any([status is None for status in values]): return None - else: - return True + return True def get_row_status_class(self, status): """Returns a css class name determined by the status value. @@ -1920,10 +1915,9 @@ class DataTable(object, metaclass=DataTableMetaclass): """ if status is True: return "status_up" - elif status is False: + if status is False: return "status_down" - else: - return "warning" + return "warning" def get_columns(self): """Returns this table's columns including auto-generated ones.""" diff --git a/horizon/tables/views.py b/horizon/tables/views.py index 3915bb527..a4f468162 100644 --- a/horizon/tables/views.py +++ b/horizon/tables/views.py @@ -383,11 +383,10 @@ class PagedTableMixin(object): prev_marker = self.request.GET.get(meta.prev_pagination_param, None) if prev_marker: return prev_marker, "asc" - else: - marker = self.request.GET.get(meta.pagination_param, None) - if marker: - return marker, "desc" - return None, "desc" + marker = self.request.GET.get(meta.pagination_param, None) + if marker: + return marker, "desc" + return None, "desc" class PagedTableWithPageMenu(object): diff --git a/horizon/tabs/views.py b/horizon/tabs/views.py index a5be35b63..50f3a9418 100644 --- a/horizon/tabs/views.py +++ b/horizon/tabs/views.py @@ -63,8 +63,7 @@ class TabView(views.HorizonTemplateView): if self.request.is_ajax(): if tab_group.selected: return http.HttpResponse(tab_group.selected.render()) - else: - return http.HttpResponse(tab_group.render()) + return http.HttpResponse(tab_group.render()) return self.render_to_response(context) def get(self, request, *args, **kwargs): diff --git a/horizon/templatetags/horizon.py b/horizon/templatetags/horizon.py index 34f7a327f..00912a2a2 100644 --- a/horizon/templatetags/horizon.py +++ b/horizon/templatetags/horizon.py @@ -141,31 +141,28 @@ def horizon_dashboard_nav(context): def quota(val, units=None): if val == float("inf"): return _("(No Limit)") - elif units is not None: + if units is not None: return "%s %s %s" % (val, force_text(units), force_text(_("Available"))) - else: - return "%s %s" % (val, force_text(_("Available"))) + return "%s %s" % (val, force_text(_("Available"))) @register.filter def quotainf(val, units=None): if val == float("inf"): return '-1' - elif units is not None: + if units is not None: return "%s %s" % (val, units) - else: - return val + return val @register.simple_tag def quotapercent(used, limit): if used >= limit or limit == 0: return 100 - elif limit == float("inf"): + if limit == float("inf"): return '[%s, true]' % used - else: - return round((float(used) / float(limit)) * 100) + return round((float(used) / float(limit)) * 100) class JSTemplateNode(template.Node): diff --git a/horizon/templatetags/truncate_filter.py b/horizon/templatetags/truncate_filter.py index 44d4e2fac..34d1637bc 100644 --- a/horizon/templatetags/truncate_filter.py +++ b/horizon/templatetags/truncate_filter.py @@ -30,5 +30,4 @@ def truncate(value, size): # pylint: disable=chained-comparison if len(value) > size and size > 3: return value[0:(size - 3)] + '...' - else: - return value[0:size] + return value[0:size] diff --git a/horizon/utils/filters.py b/horizon/utils/filters.py index c2578615f..3fcb29c19 100644 --- a/horizon/utils/filters.py +++ b/horizon/utils/filters.py @@ -51,8 +51,7 @@ def timesince_or_never(dt, default=None): if isinstance(dt, datetime.date): return timesince(dt) - else: - return default + return default @register.filter diff --git a/horizon/views.py b/horizon/views.py index 68bd836f3..9b0a4718a 100644 --- a/horizon/views.py +++ b/horizon/views.py @@ -76,8 +76,7 @@ def trace(name): if setting_utils.get_dict_config('OPENSTACK_PROFILER', 'enabled'): return profiler.trace(name, info=None, hide_args=False, allow_multiple_trace=True)(func) - else: - return func + return func return decorator diff --git a/horizon/workflows/base.py b/horizon/workflows/base.py index 35f47f206..cfd33f9e5 100644 --- a/horizon/workflows/base.py +++ b/horizon/workflows/base.py @@ -517,8 +517,7 @@ class UpdateMembersStep(Step): def get_member_field_name(self, role_id): if issubclass(self.action_class, MembershipAction): return self.action.get_member_field_name(role_id) - else: - return self.slug + "_role_" + role_id + return self.slug + "_role_" + role_id class Workflow(html.HTMLElement, metaclass=WorkflowMetaclass): @@ -794,9 +793,8 @@ class Workflow(html.HTMLElement, metaclass=WorkflowMetaclass): % cls._registerable_class.__name__) if step_class in cls._cls_registry: return False - else: - cls._cls_registry.append(step_class) - return True + cls._cls_registry.append(step_class) + return True @classmethod def unregister(cls, step_class): @@ -893,8 +891,7 @@ class Workflow(html.HTMLElement, metaclass=WorkflowMetaclass): """ if "%s" in message: return message % self.name - else: - return message + return message def verify_integrity(self): provided_keys = self.contributions | set(self.context_seed.keys()) diff --git a/openstack_auth/backend.py b/openstack_auth/backend.py index 10b865a7b..2a4f790e6 100644 --- a/openstack_auth/backend.py +++ b/openstack_auth/backend.py @@ -68,8 +68,8 @@ class KeystoneBackend(object): user = auth_user.create_user_from_token(self.request, token, endpoint, services_region) return user - else: - return None + + return None def _check_auth_expiry(self, auth_ref, margin=None): if not utils.is_token_valid(auth_ref, margin): diff --git a/openstack_auth/plugin/base.py b/openstack_auth/plugin/base.py index 011c06bae..05818b9a1 100644 --- a/openstack_auth/plugin/base.py +++ b/openstack_auth/plugin/base.py @@ -83,8 +83,7 @@ class BasePlugin(object, metaclass=abc.ABCMeta): client = v3_client.Client(session=session, auth=auth_plugin) if auth_ref.is_federated: return client.federation.projects.list() - else: - return client.projects.list(user=auth_ref.user_id) + return client.projects.list(user=auth_ref.user_id) except (keystone_exceptions.ClientException, keystone_exceptions.AuthorizationFailure): diff --git a/openstack_auth/utils.py b/openstack_auth/utils.py index 511748e09..145a313a2 100644 --- a/openstack_auth/utils.py +++ b/openstack_auth/utils.py @@ -300,11 +300,10 @@ def get_token_auth_plugin(auth_url, token, project_id=None, domain_name=None): token=token, domain_name=domain_name, reauthenticate=False) - else: - return v3_auth.Token(auth_url=auth_url, - token=token, - project_id=project_id, - reauthenticate=False) + return v3_auth.Token(auth_url=auth_url, + token=token, + project_id=project_id, + reauthenticate=False) def get_project_list(*args, **kwargs): diff --git a/openstack_auth/views.py b/openstack_auth/views.py index feef0e5e3..376d12d79 100644 --- a/openstack_auth/views.py +++ b/openstack_auth/views.py @@ -212,10 +212,10 @@ def logout(request, login_url=None, **kwargs): auth_user.unset_session_user_variables(request) return django_http.HttpResponseRedirect( settings.WEBSSO_DEFAULT_REDIRECT_LOGOUT) - else: - return django_auth_views.logout_then_login(request, - login_url=login_url, - **kwargs) + + return django_auth_views.logout_then_login(request, + login_url=login_url, + **kwargs) # TODO(stephenfin): Migrate to CBV diff --git a/openstack_dashboard/api/_nova.py b/openstack_dashboard/api/_nova.py index 0c6779d5a..264f98fb7 100644 --- a/openstack_dashboard/api/_nova.py +++ b/openstack_dashboard/api/_nova.py @@ -65,19 +65,18 @@ class Server(base.APIResourceWrapper): def image_name(self): if not self.image: return None - elif hasattr(self.image, 'name'): + if hasattr(self.image, 'name'): return self.image.name - elif 'name' in self.image: + if 'name' in self.image: return self.image['name'] - else: - try: - image = glance.image_get(self.request, self.image['id']) - self.image['name'] = image.name - return image.name - except (glance_exceptions.ClientException, - horizon_exceptions.ServiceCatalogException): - self.image['name'] = None - return None + try: + image = glance.image_get(self.request, self.image['id']) + self.image['name'] = image.name + return image.name + except (glance_exceptions.ClientException, + horizon_exceptions.ServiceCatalogException): + self.image['name'] = None + return None @property def availability_zone(self): diff --git a/openstack_dashboard/api/glance.py b/openstack_dashboard/api/glance.py index db836cf81..9de13843f 100644 --- a/openstack_dashboard/api/glance.py +++ b/openstack_dashboard/api/glance.py @@ -104,8 +104,7 @@ class Image(base.APIResourceWrapper): def property_visible(self, prop_name, show_ext_attrs=False): if show_ext_attrs: return prop_name not in self._attrs - else: - return prop_name not in (self._attrs | self._ext_attrs) + return prop_name not in (self._attrs | self._ext_attrs) def to_dict(self, show_ext_attrs=False): if not isinstance(self._apiresource, abc.Iterable): @@ -494,7 +493,8 @@ def image_create(request, **kwargs): # The image data is meant to be uploaded externally, return a # special wrapper to bypass the web server in a subsequent upload return ExternallyUploadedImage(image, request) - elif isinstance(data, TemporaryUploadedFile): + + if isinstance(data, TemporaryUploadedFile): # Hack to fool Django, so we can keep file open in the new thread. data.file._closer.close_called = True elif isinstance(data, InMemoryUploadedFile): @@ -603,8 +603,7 @@ def metadefs_namespace_get(request, namespace, resource_type=None, wrap=False): # to wrap. if wrap: return Namespace(namespace) - else: - return namespace + return namespace @profiler.trace diff --git a/openstack_dashboard/api/keystone.py b/openstack_dashboard/api/keystone.py index cd34dfc26..e9ed56ec8 100644 --- a/openstack_dashboard/api/keystone.py +++ b/openstack_dashboard/api/keystone.py @@ -90,8 +90,7 @@ class Service(base.APIDictWrapper): if(self.type == "identity"): return _("%(type)s (%(backend)s backend)") \ % {"type": self.type, "backend": keystone_backend_name()} - else: - return self.type + return self.type def __repr__(self): return "<Service: %s>" % self diff --git a/openstack_dashboard/api/neutron.py b/openstack_dashboard/api/neutron.py index 7bd3e29fb..c1c32cbaa 100644 --- a/openstack_dashboard/api/neutron.py +++ b/openstack_dashboard/api/neutron.py @@ -251,15 +251,15 @@ class SecurityGroupRule(NeutronAPIDictWrapper): # ethertype, direction (Neutron specific) def _get_secgroup_name(self, sg_id, sg_dict): - if sg_id: - if sg_dict is None: - sg_dict = {} - # If sg name not found in sg_dict, - # first two parts of UUID is used as sg name. - return sg_dict.get(sg_id, sg_id[:13]) - else: + if not sg_id: return u'' + if sg_dict is None: + sg_dict = {} + # If sg name not found in sg_dict, + # first two parts of UUID is used as sg name. + return sg_dict.get(sg_id, sg_id[:13]) + def __init__(self, sgr, sg_dict=None): # In Neutron, if both remote_ip_prefix and remote_group_id are None, # it means all remote IP range is allowed, i.e., 0.0.0.0/0 or ::/0. @@ -752,21 +752,21 @@ class FloatingIpManager(object): # have been done already. We skip all checks here. return [target for target in target_list if target['instance_id'] == instance_id] - else: - ports = self._target_ports_by_instance(instance_id) - reachable_subnets = self._get_reachable_subnets( - ports, fetch_router_ports=True) - name = self._get_server_name(instance_id) - targets = [] - for p in ports: - for ip in p.fixed_ips: - if ip['subnet_id'] not in reachable_subnets: - continue - # Floating IPs can only target IPv4 addresses. - if netaddr.IPAddress(ip['ip_address']).version != 4: - continue - targets.append(FloatingIpTarget(p, ip['ip_address'], name)) - return targets + + ports = self._target_ports_by_instance(instance_id) + reachable_subnets = self._get_reachable_subnets( + ports, fetch_router_ports=True) + name = self._get_server_name(instance_id) + targets = [] + for p in ports: + for ip in p.fixed_ips: + if ip['subnet_id'] not in reachable_subnets: + continue + # Floating IPs can only target IPv4 addresses. + if netaddr.IPAddress(ip['ip_address']).version != 4: + continue + targets.append(FloatingIpTarget(p, ip['ip_address'], name)) + return targets def _get_server_name(self, server_id): try: @@ -1343,10 +1343,9 @@ def port_list_with_trunk_types(request, **params): def _get_port_info(port): if port['id'] in parent_ports: return PortTrunkParent(port) - elif port['id'] in child_ports: + if port['id'] in child_ports: return PortTrunkSubport(port, child_ports[port['id']]) - else: - return Port(port) + return Port(port) return [_get_port_info(p) for p in ports] @@ -1807,8 +1806,7 @@ def list_extensions(request): return {} if 'extensions' in extensions_list: return tuple(extensions_list['extensions']) - else: - return () + return () @profiler.trace diff --git a/openstack_dashboard/api/nova.py b/openstack_dashboard/api/nova.py index 31c48b3b5..ae1875f60 100644 --- a/openstack_dashboard/api/nova.py +++ b/openstack_dashboard/api/nova.py @@ -1064,8 +1064,7 @@ def service_disable(request, host, binary, reason=None): if reason: return _nova.novaclient(request).services.disable_log_reason( host, binary, reason) - else: - return _nova.novaclient(request).services.disable(host, binary) + return _nova.novaclient(request).services.disable(host, binary) @profiler.trace diff --git a/openstack_dashboard/api/rest/cinder.py b/openstack_dashboard/api/rest/cinder.py index 0114b5f8f..4c9731c50 100644 --- a/openstack_dashboard/api/rest/cinder.py +++ b/openstack_dashboard/api/rest/cinder.py @@ -325,21 +325,21 @@ class Services(generic.View): Will return HTTP 501 status code if the service_list extension is not supported. """ - if api.base.is_service_enabled(request, 'volume') and \ - api.cinder.extension_supported(request, 'Services'): - result = api.cinder.service_list(request) - return {'items': [{ - 'binary': u.binary, - 'host': u.host, - 'zone': u.zone, - 'updated_at': u.updated_at, - 'status': u.status, - 'state': u.state, - 'id': idx + 1 - } for idx, u in enumerate(result)]} - else: + if not (api.base.is_service_enabled(request, 'volume') and + api.cinder.extension_supported(request, 'Services')): raise rest_utils.AjaxError(501, '') + result = api.cinder.service_list(request) + return {'items': [{ + 'binary': u.binary, + 'host': u.host, + 'zone': u.zone, + 'updated_at': u.updated_at, + 'status': u.status, + 'state': u.state, + 'id': idx + 1 + } for idx, u in enumerate(result)]} + @urls.register class DefaultQuotaSets(generic.View): @@ -353,24 +353,23 @@ class DefaultQuotaSets(generic.View): Example GET: http://localhost/api/cinder/quota-sets/defaults/ """ - if api.cinder.is_volume_service_enabled(request): - quota_set = api.cinder.default_quota_get( - request, request.user.tenant_id) - - result = [ - { - 'display_name': - quotas.QUOTA_NAMES.get( - quota.name, - quota.name.replace("_", " ").title() - ) + '', - 'name': quota.name, - 'limit': quota.limit - } - for quota in quota_set] - return {'items': result} - else: + if not api.cinder.is_volume_service_enabled(request): raise rest_utils.AjaxError(501, _('Service Cinder is disabled.')) + quota_set = api.cinder.default_quota_get( + request, request.user.tenant_id) + + result = [ + { + 'display_name': + quotas.QUOTA_NAMES.get( + quota.name, + quota.name.replace("_", " ").title() + ) + '', + 'name': quota.name, + 'limit': quota.limit + } + for quota in quota_set] + return {'items': result} @rest_utils.ajax(data_required=True) def patch(self, request): diff --git a/openstack_dashboard/api/rest/neutron.py b/openstack_dashboard/api/rest/neutron.py index bd2054f58..2bfe93c58 100644 --- a/openstack_dashboard/api/rest/neutron.py +++ b/openstack_dashboard/api/rest/neutron.py @@ -201,12 +201,11 @@ class Services(generic.View): @rest_utils.ajax() def get(self, request): """Get a list of agents""" - if api.base.is_service_enabled(request, 'network') and \ - api.neutron.is_extension_supported(request, 'agent'): + if (api.base.is_service_enabled(request, 'network') and + api.neutron.is_extension_supported(request, 'agent')): result = api.neutron.agent_list(request, **request.GET.dict()) return {'items': [n.to_dict() for n in result]} - else: - raise rest_utils.AjaxError(501, '') + raise rest_utils.AjaxError(501, '') @urls.register @@ -234,23 +233,23 @@ class DefaultQuotaSets(generic.View): @rest_utils.ajax() def get(self, request): - if api.base.is_service_enabled(request, 'network'): - quota_set = api.neutron.tenant_quota_get( - request, request.user.tenant_id) - - result = [{ - 'display_name': quotas.QUOTA_NAMES.get( - quota.name, - quota.name.replace('_', ' ').title() - ) + '', - 'name': quota.name, - 'limit': quota.limit - } for quota in quota_set] - - return {'items': result} - else: + if not api.base.is_service_enabled(request, 'network'): raise rest_utils.AjaxError(501, _('Service Neutron is disabled.')) + quota_set = api.neutron.tenant_quota_get( + request, request.user.tenant_id) + + result = [{ + 'display_name': quotas.QUOTA_NAMES.get( + quota.name, + quota.name.replace('_', ' ').title() + ) + '', + 'name': quota.name, + 'limit': quota.limit + } for quota in quota_set] + + return {'items': result} + @urls.register class QuotasSets(generic.View): diff --git a/openstack_dashboard/api/rest/nova.py b/openstack_dashboard/api/rest/nova.py index 5c53281b8..421f5e1d7 100644 --- a/openstack_dashboard/api/rest/nova.py +++ b/openstack_dashboard/api/rest/nova.py @@ -123,12 +123,11 @@ class Services(generic.View): Will return HTTP 501 status code if the service_list extension is not supported. """ - if api.base.is_service_enabled(request, 'compute') \ - and api.nova.extension_supported('Services', request): + if (api.base.is_service_enabled(request, 'compute') and + api.nova.extension_supported('Services', request)): result = api.nova.service_list(request) return {'items': [u.to_dict() for u in result]} - else: - raise rest_utils.AjaxError(501, '') + raise rest_utils.AjaxError(501, '') @urls.register @@ -727,27 +726,27 @@ class DefaultQuotaSets(generic.View): Example GET: http://localhost/api/nova/quota-sets/defaults/ """ - if api.base.is_service_enabled(request, 'compute'): - quota_set = api.nova.default_quota_get(request, - request.user.tenant_id) + if not api.base.is_service_enabled(request, 'compute'): + raise rest_utils.AjaxError(501, _('Service Nova is disabled.')) - disabled_quotas = quotas.get_disabled_quotas(request) + quota_set = api.nova.default_quota_get(request, + request.user.tenant_id) - filtered_quotas = [quota for quota in quota_set - if quota.name not in disabled_quotas] + disabled_quotas = quotas.get_disabled_quotas(request) - result = [{ - 'display_name': quotas.QUOTA_NAMES.get( - quota.name, - quota.name.replace("_", " ").title() - ) + '', - 'name': quota.name, - 'limit': quota.limit - } for quota in filtered_quotas] + filtered_quotas = [quota for quota in quota_set + if quota.name not in disabled_quotas] - return {'items': result} - else: - raise rest_utils.AjaxError(501, _('Service Nova is disabled.')) + result = [{ + 'display_name': quotas.QUOTA_NAMES.get( + quota.name, + quota.name.replace("_", " ").title() + ) + '', + 'name': quota.name, + 'limit': quota.limit + } for quota in filtered_quotas] + + return {'items': result} @rest_utils.ajax(data_required=True) def patch(self, request): diff --git a/openstack_dashboard/api/rest/utils.py b/openstack_dashboard/api/rest/utils.py index 68e6e19bd..c3eab19d6 100644 --- a/openstack_dashboard/api/rest/utils.py +++ b/openstack_dashboard/api/rest/utils.py @@ -128,7 +128,7 @@ def ajax(authenticated=True, data_required=False, data = function(self, request, *args, **kw) if isinstance(data, http.HttpResponse): return data - elif data is None: + if data is None: return JSONResponse('', status=204) return JSONResponse(data, json_encoder=json_encoder) except http_errors as e: diff --git a/openstack_dashboard/api/swift.py b/openstack_dashboard/api/swift.py index 1d289e6d7..72ff52918 100644 --- a/openstack_dashboard/api/swift.py +++ b/openstack_dashboard/api/swift.py @@ -171,8 +171,7 @@ def swift_get_containers(request, marker=None, prefix=None): container_objs = [Container(c) for c in containers] if(len(container_objs) > limit): return (container_objs[0:-1], True) - else: - return (container_objs, False) + return (container_objs, False) @profiler.trace @@ -271,8 +270,7 @@ def swift_get_objects(request, container_name, prefix=None, marker=None, if(len(object_objs) > limit): return (object_objs[0:-1], True) - else: - return (object_objs, False) + return (object_objs, False) @profiler.trace @@ -302,14 +300,14 @@ def wildcard_search(string, q): q_list = q.split('*') if all(map(lambda x: x == '', q_list)): return True - elif q_list[0] not in string: + if q_list[0] not in string: return False + + if q_list[0] == '': + tail = string else: - if q_list[0] == '': - tail = string - else: - head, delimiter, tail = string.partition(q_list[0]) - return wildcard_search(tail, '*'.join(q_list[1:])) + head, delimiter, tail = string.partition(q_list[0]) + return wildcard_search(tail, '*'.join(q_list[1:])) @profiler.trace diff --git a/openstack_dashboard/dashboards/admin/images/tables.py b/openstack_dashboard/dashboards/admin/images/tables.py index e89cd22ab..a3760942c 100644 --- a/openstack_dashboard/dashboards/admin/images/tables.py +++ b/openstack_dashboard/dashboards/admin/images/tables.py @@ -30,8 +30,7 @@ class AdminDeleteImage(project_tables.DeleteImage): def allowed(self, request, image=None): if image and image.protected: return False - else: - return True + return True class AdminEditImage(project_tables.EditImage): diff --git a/openstack_dashboard/dashboards/admin/networks/subnets/tables.py b/openstack_dashboard/dashboards/admin/networks/subnets/tables.py index f4136b760..ffffc9420 100644 --- a/openstack_dashboard/dashboards/admin/networks/subnets/tables.py +++ b/openstack_dashboard/dashboards/admin/networks/subnets/tables.py @@ -77,13 +77,11 @@ class UpdateSubnet(proj_tables.SubnetPolicyTargetMixin, tables.LinkAction): def subnet_ip_availability(availability): subnet_availability = availability.get("free_ips") - if subnet_availability: - if subnet_availability > 10000: - return ">10000" - else: - return str(subnet_availability) - else: - return str("Not Available") + if not subnet_availability: + return "Not Available" + if subnet_availability > 10000: + return ">10000" + return str(subnet_availability) class SubnetsTable(tables.DataTable): diff --git a/openstack_dashboard/dashboards/admin/networks/tables.py b/openstack_dashboard/dashboards/admin/networks/tables.py index d035aa165..3436a1d21 100644 --- a/openstack_dashboard/dashboards/admin/networks/tables.py +++ b/openstack_dashboard/dashboards/admin/networks/tables.py @@ -77,8 +77,7 @@ DISPLAY_CHOICES = ( def get_availability_zones(network): if 'availability_zones' in network and network.availability_zones: return ', '.join(network.availability_zones) - else: - return _("-") + return _("-") class AdminNetworksFilterAction(project_tables.ProjectNetworksFilterAction): diff --git a/openstack_dashboard/dashboards/identity/projects/tables.py b/openstack_dashboard/dashboards/identity/projects/tables.py index 01445e487..0332e9ce7 100644 --- a/openstack_dashboard/dashboards/identity/projects/tables.py +++ b/openstack_dashboard/dashboards/identity/projects/tables.py @@ -67,8 +67,7 @@ class UpdateMembersLink(tables.LinkAction): # domain admin or cloud admin = True # project admin or member = False return api.keystone.is_domain_admin(request) - else: - return super(UpdateMembersLink, self).allowed(request, project) + return super(UpdateMembersLink, self).allowed(request, project) class UpdateGroupsLink(tables.LinkAction): @@ -84,8 +83,7 @@ class UpdateGroupsLink(tables.LinkAction): # domain admin or cloud admin = True # project admin or member = False return api.keystone.is_domain_admin(request) - else: - return super(UpdateGroupsLink, self).allowed(request, project) + return super(UpdateGroupsLink, self).allowed(request, project) def get_link_url(self, project): step = 'update_group_members' @@ -119,8 +117,7 @@ class CreateProject(tables.LinkAction): # domain admin or cloud admin = True # project admin or member = False return api.keystone.is_domain_admin(request) - else: - return api.keystone.keystone_can_edit_project() + return api.keystone.keystone_can_edit_project() class UpdateProject(policy.PolicyTargetMixin, tables.LinkAction): @@ -137,8 +134,7 @@ class UpdateProject(policy.PolicyTargetMixin, tables.LinkAction): # domain admin or cloud admin = True # project admin or member = False return api.keystone.is_domain_admin(request) - else: - return api.keystone.keystone_can_edit_project() + return api.keystone.keystone_can_edit_project() class ModifyQuotas(tables.LinkAction): diff --git a/openstack_dashboard/dashboards/identity/projects/workflows.py b/openstack_dashboard/dashboards/identity/projects/workflows.py index 791db7945..48ba05c1b 100644 --- a/openstack_dashboard/dashboards/identity/projects/workflows.py +++ b/openstack_dashboard/dashboards/identity/projects/workflows.py @@ -486,8 +486,7 @@ class CreateProject(workflows.Workflow): def format_status_message(self, message): if "%s" in message: return message % self.context.get('name', 'unknown project') - else: - return message + return message def _create_project(self, request, data): # create the project @@ -657,8 +656,7 @@ class UpdateProject(workflows.Workflow): def format_status_message(self, message): if "%s" in message: return message % self.context.get('name', 'unknown project') - else: - return message + return message @memoized.memoized_method def _get_available_roles(self, request): @@ -748,8 +746,7 @@ class UpdateProject(workflows.Workflow): 'administrative role manually via the CLI.') messages.warning(request, msg) return True - else: - return False + return False def _update_project_members(self, request, data, project_id): # update project members diff --git a/openstack_dashboard/dashboards/identity/users/forms.py b/openstack_dashboard/dashboards/identity/users/forms.py index 706b5581e..c7630aa42 100644 --- a/openstack_dashboard/dashboards/identity/users/forms.py +++ b/openstack_dashboard/dashboards/identity/users/forms.py @@ -276,8 +276,8 @@ class UpdateUserForm(BaseUserForm, AddExtraColumnMixIn): if isinstance(response, http.HttpResponse): return response - else: - return True + + return True class ChangePasswordForm(PasswordMixin, forms.SelfHandlingForm): @@ -341,5 +341,5 @@ class ChangePasswordForm(PasswordMixin, forms.SelfHandlingForm): if isinstance(response, http.HttpResponse): return response - else: - return True + + return True diff --git a/openstack_dashboard/dashboards/project/floating_ips/tables.py b/openstack_dashboard/dashboards/project/floating_ips/tables.py index de7b0fb58..16ec1260f 100644 --- a/openstack_dashboard/dashboards/project/floating_ips/tables.py +++ b/openstack_dashboard/dashboards/project/floating_ips/tables.py @@ -143,20 +143,18 @@ def get_instance_info(fip): return (_("%(instance_name)s %(fixed_ip)s") % {'instance_name': getattr(fip, "instance_name", ''), 'fixed_ip': fip.fixed_ip}) - elif fip.instance_type == 'loadbalancer': + if fip.instance_type == 'loadbalancer': return _("Load Balancer VIP %s") % fip.fixed_ip - elif fip.instance_type: + if fip.instance_type: return fip.fixed_ip - else: - return None + return None def get_instance_link(datum): if getattr(datum, 'instance_id'): return reverse("horizon:project:instances:detail", args=(datum.instance_id,)) - else: - return None + return None STATUS_DISPLAY_CHOICES = ( diff --git a/openstack_dashboard/dashboards/project/floating_ips/workflows.py b/openstack_dashboard/dashboards/project/floating_ips/workflows.py index b3a0e0338..3d93ca0e1 100644 --- a/openstack_dashboard/dashboards/project/floating_ips/workflows.py +++ b/openstack_dashboard/dashboards/project/floating_ips/workflows.py @@ -156,8 +156,7 @@ class IPAssociationWorkflow(workflows.Workflow): if "%s" in message: return message % self.context.get('ip_address', _('unknown IP address')) - else: - return message + return message def handle(self, request, data): try: diff --git a/openstack_dashboard/dashboards/project/instances/tables.py b/openstack_dashboard/dashboards/project/instances/tables.py index 56af9b8f3..252b71da1 100644 --- a/openstack_dashboard/dashboards/project/instances/tables.py +++ b/openstack_dashboard/dashboards/project/instances/tables.py @@ -137,12 +137,11 @@ class RebootInstance(policy.PolicyTargetMixin, tables.BatchAction): ) def allowed(self, request, instance=None): - if instance is not None: - return ((instance.status in ACTIVE_STATES or - instance.status == 'SHUTOFF') and - not is_deleting(instance)) - else: + if instance is None: return True + return ((instance.status in ACTIVE_STATES or + instance.status == 'SHUTOFF') and + not is_deleting(instance)) def action(self, request, obj_id): api.nova.server_reboot(request, obj_id, soft_reboot=False) @@ -173,8 +172,7 @@ class SoftRebootInstance(RebootInstance): def allowed(self, request, instance=None): if instance is not None: return instance.status in ACTIVE_STATES - else: - return True + return True class RescueInstance(policy.PolicyTargetMixin, tables.LinkAction): diff --git a/openstack_dashboard/dashboards/project/instances/workflows/create_instance.py b/openstack_dashboard/dashboards/project/instances/workflows/create_instance.py index bb6edb13a..fcda9159c 100644 --- a/openstack_dashboard/dashboards/project/instances/workflows/create_instance.py +++ b/openstack_dashboard/dashboards/project/instances/workflows/create_instance.py @@ -319,9 +319,8 @@ class SetInstanceDetailsAction(workflows.Action): msg = _("You must select an image.") self._errors['image_id'] = self.error_class([msg]) return - else: - self._check_flavor_for_image(cleaned_data) - self._check_volume_for_image(cleaned_data) + self._check_flavor_for_image(cleaned_data) + self._check_volume_for_image(cleaned_data) def _check_source_instance_snapshot(self, cleaned_data): # using the array form of get blows up with KeyError @@ -677,31 +676,30 @@ class CustomizeAction(workflows.Action): def clean_uploaded_files(self, prefix, files): upload_str = prefix + "_upload" - has_upload = upload_str in files - if has_upload: - upload_file = files[upload_str] - log_script_name = upload_file.name - LOG.info('got upload %s', log_script_name) + if upload_str not in files: + return None - if upload_file._size > 16 * units.Ki: # 16kb - msg = _('File exceeds maximum size (16kb)') - raise forms.ValidationError(msg) + upload_file = files[upload_str] + log_script_name = upload_file.name + LOG.info('got upload %s', log_script_name) - script = upload_file.read() - if script != "": - try: - if not isinstance(script, str): - script = script.decode() - normalize_newlines(script) - except Exception as e: - msg = _('There was a problem parsing the' - ' %(prefix)s: %(error)s') - msg = msg % {'prefix': prefix, - 'error': e} - raise forms.ValidationError(msg) - return script - else: - return None + if upload_file._size > 16 * units.Ki: # 16kb + msg = _('File exceeds maximum size (16kb)') + raise forms.ValidationError(msg) + + script = upload_file.read() + if script != "": + try: + if not isinstance(script, str): + script = script.decode() + normalize_newlines(script) + except Exception as e: + msg = _('There was a problem parsing the' + ' %(prefix)s: %(error)s') + msg = msg % {'prefix': prefix, + 'error': e} + raise forms.ValidationError(msg) + return script class PostCreationStep(workflows.Step): @@ -877,8 +875,7 @@ class LaunchInstance(workflows.Workflow): if int(count) > 1: return message % {"count": _("%s instances") % count, "name": name} - else: - return message % {"count": _("instance"), "name": name} + return message % {"count": _("instance"), "name": name} @sensitive_variables('context') def handle(self, request, context): diff --git a/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py b/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py index 1fb4869a5..ebad56ccb 100644 --- a/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py +++ b/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py @@ -99,8 +99,7 @@ class ResizeInstance(workflows.Workflow): def format_status_message(self, message): if "%s" in message: return message % self.context.get('name', 'unknown instance') - else: - return message + return message @sensitive_variables('context') def handle(self, request, context): diff --git a/openstack_dashboard/dashboards/project/key_pairs/tables.py b/openstack_dashboard/dashboards/project/key_pairs/tables.py index 468e386ad..31feea6b5 100644 --- a/openstack_dashboard/dashboards/project/key_pairs/tables.py +++ b/openstack_dashboard/dashboards/project/key_pairs/tables.py @@ -63,10 +63,9 @@ class QuotaKeypairMixin(object): verbose_name=self.verbose_name, quota_exceeded=_("(Quota exceeded)")) return False - else: - classes = [c for c in self.classes if c != "disabled"] - self.classes = classes - return True + classes = [c for c in self.classes if c != "disabled"] + self.classes = classes + return True class ImportKeyPair(QuotaKeypairMixin, tables.LinkAction): diff --git a/openstack_dashboard/dashboards/project/networks/ports/extensions/allowed_address_pairs/tables.py b/openstack_dashboard/dashboards/project/networks/ports/extensions/allowed_address_pairs/tables.py index d90c61ea2..e01fc5516 100644 --- a/openstack_dashboard/dashboards/project/networks/ports/extensions/allowed_address_pairs/tables.py +++ b/openstack_dashboard/dashboards/project/networks/ports/extensions/allowed_address_pairs/tables.py @@ -50,8 +50,7 @@ class AddAllowedAddressPair(policy.PolicyTargetMixin, tables.LinkAction): def get_link_url(self, port=None): if port: return reverse(self.url, args=(port.id,)) - else: - return reverse(self.url, args=(self.table.kwargs.get('port_id'),)) + return reverse(self.url, args=(self.table.kwargs.get('port_id'),)) class DeleteAllowedAddressPair(tables.DeleteAction): diff --git a/openstack_dashboard/dashboards/project/networks/ports/tables.py b/openstack_dashboard/dashboards/project/networks/ports/tables.py index 427538b7c..ac140b5fe 100644 --- a/openstack_dashboard/dashboards/project/networks/ports/tables.py +++ b/openstack_dashboard/dashboards/project/networks/ports/tables.py @@ -39,10 +39,9 @@ def get_fixed_ips(port): def get_attached(port): if port['device_owner']: return port['device_owner'] - elif port['device_id']: + if port['device_id']: return _('Attached') - else: - return _('Detached') + return _('Detached') class UpdatePort(policy.PolicyTargetMixin, tables.LinkAction): diff --git a/openstack_dashboard/dashboards/project/networks/tables.py b/openstack_dashboard/dashboards/project/networks/tables.py index 9a1230ec1..3bbb95e65 100644 --- a/openstack_dashboard/dashboards/project/networks/tables.py +++ b/openstack_dashboard/dashboards/project/networks/tables.py @@ -171,8 +171,7 @@ STATUS_DISPLAY_CHOICES = ( def get_availability_zones(network): if 'availability_zones' in network and network.availability_zones: return ', '.join(network.availability_zones) - else: - return _("-") + return _("-") class ProjectNetworksFilterAction(tables.FilterAction): diff --git a/openstack_dashboard/dashboards/project/networks/workflows.py b/openstack_dashboard/dashboards/project/networks/workflows.py index 22ad258b4..4c55ed7ac 100644 --- a/openstack_dashboard/dashboards/project/networks/workflows.py +++ b/openstack_dashboard/dashboards/project/networks/workflows.py @@ -608,6 +608,6 @@ class CreateNetwork(workflows.Workflow): tenant_id=network.tenant_id) if subnet: return True - else: - self._delete_network(request, network) - return False + + self._delete_network(request, network) + return False diff --git a/openstack_dashboard/dashboards/project/routers/ports/tables.py b/openstack_dashboard/dashboards/project/routers/ports/tables.py index 93933ccbe..744c039d7 100644 --- a/openstack_dashboard/dashboards/project/routers/ports/tables.py +++ b/openstack_dashboard/dashboards/project/routers/ports/tables.py @@ -31,10 +31,9 @@ LOG = logging.getLogger(__name__) def get_device_owner(port): if port['device_owner'] == 'network:router_gateway': return _('External Gateway') - elif port['device_owner'] == 'network:router_interface': + if port['device_owner'] == 'network:router_interface': return _('Internal Interface') - else: - return ' ' + return ' ' class AddInterface(policy.PolicyTargetMixin, tables.LinkAction): diff --git a/openstack_dashboard/dashboards/project/routers/tables.py b/openstack_dashboard/dashboards/project/routers/tables.py index 9c24e868b..4a347ae32 100644 --- a/openstack_dashboard/dashboards/project/routers/tables.py +++ b/openstack_dashboard/dashboards/project/routers/tables.py @@ -183,15 +183,13 @@ class UpdateRow(tables.Row): def get_external_network(router): if router.external_gateway_info: return router.external_gateway_info['network'] - else: - return _("-") + return _("-") def get_availability_zones(router): if 'availability_zones' in router and router.availability_zones: return ', '.join(router.availability_zones) - else: - return _("-") + return _("-") class RoutersFilterAction(tables.FilterAction): diff --git a/openstack_dashboard/dashboards/project/security_groups/tables.py b/openstack_dashboard/dashboards/project/security_groups/tables.py index 50501fd1a..6757b1cf1 100644 --- a/openstack_dashboard/dashboards/project/security_groups/tables.py +++ b/openstack_dashboard/dashboards/project/security_groups/tables.py @@ -180,8 +180,7 @@ def get_remote_ip_prefix(rule): else: range = rule.ip_range['cidr'] return range - else: - return None + return None def get_remote_security_group(rule): @@ -196,17 +195,15 @@ def get_port_range(rule): ip_proto = rule.ip_protocol if rule.from_port == rule.to_port: return check_rule_template(rule.from_port, ip_proto) - else: - return (u"%(from)s - %(to)s" % - {'from': check_rule_template(rule.from_port, ip_proto), - 'to': check_rule_template(rule.to_port, ip_proto)}) + return (u"%(from)s - %(to)s" % + {'from': check_rule_template(rule.from_port, ip_proto), + 'to': check_rule_template(rule.to_port, ip_proto)}) def filter_direction(direction): if direction is None or direction.lower() == 'ingress': return _('Ingress') - else: - return _('Egress') + return _('Egress') def filter_protocol(protocol): diff --git a/openstack_dashboard/dashboards/project/volume_groups/tables.py b/openstack_dashboard/dashboards/project/volume_groups/tables.py index bb0ad28ab..69b1ebe0e 100644 --- a/openstack_dashboard/dashboards/project/volume_groups/tables.py +++ b/openstack_dashboard/dashboards/project/volume_groups/tables.py @@ -69,8 +69,7 @@ class ManageVolumes(policy.PolicyTargetMixin, tables.LinkAction): def allowed(self, request, group=None): if hasattr(group, 'status'): return group.status != 'error' - else: - return False + return False class CreateSnapshot(policy.PolicyTargetMixin, tables.LinkAction): @@ -83,8 +82,7 @@ class CreateSnapshot(policy.PolicyTargetMixin, tables.LinkAction): def allowed(self, request, group=None): if hasattr(group, 'status'): return group.status != 'error' - else: - return False + return False class CloneGroup(policy.PolicyTargetMixin, tables.LinkAction): @@ -97,8 +95,7 @@ class CloneGroup(policy.PolicyTargetMixin, tables.LinkAction): def allowed(self, request, group=None): if hasattr(group, 'status'): return group.status != 'error' - else: - return False + return False class UpdateRow(tables.Row): diff --git a/openstack_dashboard/dashboards/project/volumes/tables.py b/openstack_dashboard/dashboards/project/volumes/tables.py index 8a7b9c87d..f26a95ad0 100644 --- a/openstack_dashboard/dashboards/project/volumes/tables.py +++ b/openstack_dashboard/dashboards/project/volumes/tables.py @@ -445,10 +445,9 @@ def get_volume_type(volume): def get_encrypted_value(volume): if not hasattr(volume, 'encrypted') or volume.encrypted is None: return _("-") - elif volume.encrypted is False: + if volume.encrypted is False: return _("No") - else: - return _("Yes") + return _("Yes") def get_encrypted_link(volume): diff --git a/openstack_dashboard/dashboards/project/volumes/views.py b/openstack_dashboard/dashboards/project/volumes/views.py index 76d93c5f3..4debe956a 100644 --- a/openstack_dashboard/dashboards/project/volumes/views.py +++ b/openstack_dashboard/dashboards/project/volumes/views.py @@ -581,8 +581,7 @@ class EditAttachmentsView(tables.DataTableView, forms.ModalFormView): form = self.get_form() if form.is_valid(): return self.form_valid(form) - else: - return self.get(request, *args, **kwargs) + return self.get(request, *args, **kwargs) class RetypeView(forms.ModalFormView): diff --git a/openstack_dashboard/management/commands/make_web_conf.py b/openstack_dashboard/management/commands/make_web_conf.py index 35000724a..feed78fe0 100644 --- a/openstack_dashboard/management/commands/make_web_conf.py +++ b/openstack_dashboard/management/commands/make_web_conf.py @@ -56,11 +56,8 @@ def _getattr(obj, name, default): attr does not exist, here, we return `default` even if attr evaluates to None or False. """ - value = getattr(obj, name, default) - if value: - return value - else: - return default + value = getattr(obj, name, default) or default + return value context = template.Context({ diff --git a/openstack_dashboard/usage/base.py b/openstack_dashboard/usage/base.py index 02b8a1c19..53f3490a7 100644 --- a/openstack_dashboard/usage/base.py +++ b/openstack_dashboard/usage/base.py @@ -42,8 +42,7 @@ class BaseUsage(object): days_range = settings.OVERVIEW_DAYS_RANGE if days_range: return self.today.date() - datetime.timedelta(days=days_range) - else: - return datetime.date(self.today.year, self.today.month, 1) + return datetime.date(self.today.year, self.today.month, 1) @staticmethod def get_start(year, month, day): diff --git a/openstack_dashboard/usage/tables.py b/openstack_dashboard/usage/tables.py index 04007f1b0..ae2b44937 100644 --- a/openstack_dashboard/usage/tables.py +++ b/openstack_dashboard/usage/tables.py @@ -74,8 +74,7 @@ def get_instance_link(datum): view = "horizon:project:instances:detail" if datum.get('instance_id', False): return urls.reverse(view, args=(datum.get('instance_id'),)) - else: - return None + return None class ProjectUsageTable(BaseUsageTable): |