diff --git a/galaxy_ng/app/access_control/access_policy.py b/galaxy_ng/app/access_control/access_policy.py index 54f4810b30..4f759bc39d 100644 --- a/galaxy_ng/app/access_control/access_policy.py +++ b/galaxy_ng/app/access_control/access_policy.py @@ -228,10 +228,10 @@ def scope_queryset(self, view, qs): # if access_policy := self.get_access_policy(view): if access_policy.queryset_scoping: scope = access_policy.queryset_scoping["function"] - if scope == "scope_queryset" or not (function := getattr(self, scope, None)): + if scope == "scope_queryset" or not (func := getattr(self, scope, None)): return qs kwargs = access_policy.queryset_scoping.get("parameters") or {} - qs = function(view, qs, **kwargs) + qs = func(view, qs, **kwargs) return qs # Define global conditions here @@ -333,9 +333,8 @@ def has_ansible_repo_perms(self, request, view, action, permission): repo = obj.repository.cast() - if permission == "ansible.view_ansiblerepository": - if not repo.private: - return True + if permission == "ansible.view_ansiblerepository" and not repo.private: + return True return request.user.has_perm(permission, repo) @@ -605,15 +604,15 @@ class AIDenyIndexAccessPolicy(AccessPolicyBase): def can_edit_ai_deny_index(self, request, view, permission): """This permission applies to Namespace or LegacyNamespace on ai_deny_index/.""" - object = view.get_object() + obj = view.get_object() has_permission = False - if isinstance(object, models.Namespace): + if isinstance(obj, models.Namespace): has_permission = has_model_or_object_permissions( request.user, "galaxy.change_namespace", - object + obj ) - elif isinstance(object, LegacyNamespace): + elif isinstance(obj, LegacyNamespace): has_permission = LegacyAccessPolicy().is_namespace_owner( request, view, permission ) diff --git a/galaxy_ng/app/api/ui/v1/views/landing_page.py b/galaxy_ng/app/api/ui/v1/views/landing_page.py index d7dfe42470..6743a16d80 100644 --- a/galaxy_ng/app/api/ui/v1/views/landing_page.py +++ b/galaxy_ng/app/api/ui/v1/views/landing_page.py @@ -132,7 +132,7 @@ def get(self, request, *args, **kwargs): "shape": { "title": "Learn about namespaces", "description": ( - "Organize collections content into " "namespaces users can access." + "Organize collections content into namespaces users can access." ), "link": { "title": "Learn more", diff --git a/galaxy_ng/app/api/ui/v1/views/search.py b/galaxy_ng/app/api/ui/v1/views/search.py index 3bbc4bc304..fa20eef0bb 100644 --- a/galaxy_ng/app/api/ui/v1/views/search.py +++ b/galaxy_ng/app/api/ui/v1/views/search.py @@ -157,8 +157,8 @@ def get_queryset(self): def get_search_results(self, filter_params, sort): """Validates filter_params, builds each queryset and then unionize and apply filters.""" - type = filter_params.get("type", "").lower() - if type not in ("role", "collection", ""): + type_ = filter_params.get("type", "").lower() + if type_ not in ("role", "collection", ""): raise ValidationError("'type' must be ['collection', 'role']") search_type = filter_params.get("search_type", DEFAULT_SEARCH_TYPE) @@ -171,7 +171,14 @@ def get_search_results(self, filter_params, sort): collections = self.get_collection_queryset(query=query) roles = self.get_role_queryset(query=query) - result_qs = self.filter_and_sort(collections, roles, filter_params, sort, type, query=query) + result_qs = self.filter_and_sort( + collections, + roles, + filter_params, + sort, + type_, + query=query + ) return result_qs def get_filter_params(self, request): @@ -268,7 +275,7 @@ def get_role_queryset(self, query=None): ).values(*QUERYSET_VALUES) return qs - def filter_and_sort(self, collections, roles, filter_params, sort, type="", query=None): + def filter_and_sort(self, collections, roles, filter_params, sort, type_="", query=None): """Apply filters individually on each queryset and then combine to sort.""" facets = {} if deprecated := filter_params.get("deprecated"): @@ -297,7 +304,7 @@ def filter_and_sort(self, collections, roles, filter_params, sort, type="", quer if query: collections = collections.filter(search=query) roles = roles.filter(search=query) - elif keywords := filter_params.get("keywords"): # search_type=sql + elif keywords := filter_params.get("keywords"): query = ( Q(name__icontains=keywords) | Q(namespace_name__icontains=keywords) @@ -308,9 +315,9 @@ def filter_and_sort(self, collections, roles, filter_params, sort, type="", quer collections = collections.filter(query) roles = roles.filter(query) - if type.lower() == "role": + if type_.lower() == "role": qs = roles.order_by(*sort) - elif type.lower() == "collection": + elif type_.lower() == "collection": qs = collections.order_by(*sort) else: qs = collections.union(roles, all=True).order_by(*sort) diff --git a/galaxy_ng/app/api/ui/v1/viewsets/my_synclist.py b/galaxy_ng/app/api/ui/v1/viewsets/my_synclist.py index 10d1a312c5..239f1c8092 100644 --- a/galaxy_ng/app/api/ui/v1/viewsets/my_synclist.py +++ b/galaxy_ng/app/api/ui/v1/viewsets/my_synclist.py @@ -26,7 +26,6 @@ def get_queryset(self): return get_objects_for_user( self.request.user, "galaxy.change_synclist", - # any_perm=True, qs=models.SyncList.objects.all(), ) diff --git a/galaxy_ng/app/api/ui/v2/permissions.py b/galaxy_ng/app/api/ui/v2/permissions.py index 3c26d5d64f..d505ebff96 100644 --- a/galaxy_ng/app/api/ui/v2/permissions.py +++ b/galaxy_ng/app/api/ui/v2/permissions.py @@ -92,17 +92,19 @@ def has_object_permission(self, request, view, obj): return False # we can't allow the last superuser to get demoted - if request.data.get('is_superuser') is False: - if User.objects.filter(is_superuser=True).count() == 1 and obj.is_superuser: - return False + if ( + request.data.get('is_superuser') is False + and User.objects.filter(is_superuser=True).count() == 1 + and obj.is_superuser + ): + return False # superuser can set the value to True or False if request.user.is_superuser: return True # user can set themself only to False - if request.user == obj: - if request.data.get('is_superuser') is False: - return True + if request.user == obj and request.data.get('is_superuser') is False: + return True return False diff --git a/galaxy_ng/app/api/ui/v2/serializers.py b/galaxy_ng/app/api/ui/v2/serializers.py index 5045f2820f..3d51e8ee60 100644 --- a/galaxy_ng/app/api/ui/v2/serializers.py +++ b/galaxy_ng/app/api/ui/v2/serializers.py @@ -1,4 +1,3 @@ -# from django.contrib.auth.models import User from rest_framework import serializers from rest_framework.exceptions import ValidationError from django.contrib.auth import password_validation diff --git a/galaxy_ng/app/api/ui/v2/views.py b/galaxy_ng/app/api/ui/v2/views.py index 511952257f..37cee25524 100644 --- a/galaxy_ng/app/api/ui/v2/views.py +++ b/galaxy_ng/app/api/ui/v2/views.py @@ -62,7 +62,6 @@ class UserViewSet(BaseViewSet): queryset = User.objects.all().order_by('id') filterset_class = UserViewFilter permission_classes = [ComplexUserPermissions] - # permission_classes = [IsSuperUserOrReadOnly] def get_serializer_class(self): # FIXME - a single serializer for this viewset diff --git a/galaxy_ng/app/api/utils.py b/galaxy_ng/app/api/utils.py index 5dd5ede40a..84af11f4ea 100644 --- a/galaxy_ng/app/api/utils.py +++ b/galaxy_ng/app/api/utils.py @@ -21,7 +21,7 @@ LOCALHOST = "localhost" FILENAME_REGEXP = re.compile( - r"^(?P\w+)-(?P\w+)-" r"(?P[0-9a-zA-Z.+-]+)\.tar\.gz$" + r"^(?P\w+)-(?P\w+)-(?P[0-9a-zA-Z.+-]+)\.tar\.gz$" ) VERSION_REGEXP = re.compile(r""" ^ diff --git a/galaxy_ng/app/api/v1/filtersets.py b/galaxy_ng/app/api/v1/filtersets.py index c85582da1e..73e77475ec 100644 --- a/galaxy_ng/app/api/v1/filtersets.py +++ b/galaxy_ng/app/api/v1/filtersets.py @@ -19,7 +19,7 @@ class LegacyNamespaceFilter(filterset.FilterSet): sort = filters.OrderingFilter( fields=( ('created', 'created'), - ('name', 'name') + ('name', 'name'), ) ) @@ -63,14 +63,12 @@ class LegacyUserFilter(filterset.FilterSet): sort = filters.OrderingFilter( fields=( - # ('created', 'created'), - ('username', 'username') + ('username', 'username'), ) ) class Meta: model = User - # fields = ['created', 'username'] fields = ['username'] def username_filter(self, queryset, name, value): diff --git a/galaxy_ng/app/api/v1/serializers.py b/galaxy_ng/app/api/v1/serializers.py index 6975edb288..f6965ce3bb 100644 --- a/galaxy_ng/app/api/v1/serializers.py +++ b/galaxy_ng/app/api/v1/serializers.py @@ -120,7 +120,6 @@ class LegacyUserSerializer(serializers.ModelSerializer): summary_fields = serializers.SerializerMethodField() date_joined = serializers.SerializerMethodField() created = serializers.SerializerMethodField() - # active = serializers.SerializerMethodField() full_name = serializers.SerializerMethodField() url = serializers.SerializerMethodField() username = serializers.SerializerMethodField() @@ -158,7 +157,6 @@ def get_created(self, obj): return self.get_date_joined(obj) def get_date_joined(self, obj): - # return obj.created if hasattr(obj, '_created'): return obj._created if hasattr(obj, 'date_joined'): @@ -557,7 +555,7 @@ class LegacySyncSerializer(serializers.Serializer): class Meta: model = None fields = [ - 'baseurl' + 'baseurl', 'github_user', 'role_name', 'role_version', diff --git a/galaxy_ng/app/api/v1/tasks.py b/galaxy_ng/app/api/v1/tasks.py index c5bbd6233b..262e17a55e 100644 --- a/galaxy_ng/app/api/v1/tasks.py +++ b/galaxy_ng/app/api/v1/tasks.py @@ -37,7 +37,6 @@ ) -# logger = logging.getLogger(__name__) logger = logging.getLogger("galaxy_ng.app.api.v1.tasks.legacy_role_import") @@ -158,7 +157,7 @@ def do_git_checkout(clone_url, checkout_path, github_reference): ) if pid.returncode != 0: error = pid.stdout.decode('utf-8') - logger.error('{cmd} failed: {error}') + logger.error(f'{cmd} failed: {error}') raise Exception(f'{cmd} failed') last_commit = [x for x in gitrepo.iter_commits()][0] @@ -500,7 +499,6 @@ def legacy_role_import( 'imported': datetime.datetime.now().isoformat(), 'clone_url': clone_url, 'tags': galaxy_info.get("galaxy_tags", []), - 'commit': github_commit, 'github_user': real_github_user, 'github_repo': real_github_repo, 'github_branch': github_reference, @@ -627,7 +625,6 @@ def legacy_sync_from_upstream( rkey = (github_user, role_name) remote_id = rdata['id'] role_versions = rversions[:] - # github_user = rdata['github_user'] github_repo = rdata['github_repo'] github_branch = rdata['github_branch'] clone_url = f'https://github.com/{github_user}/{github_repo}' @@ -637,7 +634,6 @@ def legacy_sync_from_upstream( commit_msg = rdata.get('commit_message') commit_url = rdata.get('commit_url') issue_tracker = rdata.get('issue_tracker_url', clone_url + '/issues') - # role_versions = sfields.get('versions', []) role_description = rdata.get('description') role_license = rdata.get('license') role_readme = rdata.get('readme') diff --git a/galaxy_ng/app/api/v1/viewsets/namespaces.py b/galaxy_ng/app/api/v1/viewsets/namespaces.py index 0f40997bc0..255c3000ea 100644 --- a/galaxy_ng/app/api/v1/viewsets/namespaces.py +++ b/galaxy_ng/app/api/v1/viewsets/namespaces.py @@ -117,7 +117,6 @@ class LegacyNamespaceOwnersViewSet(viewsets.GenericViewSet, mixins.ListModelMixi authentication_classes = GALAXY_AUTHENTICATION_CLASSES def get_queryset(self): - # return get_object_or_404(LegacyNamespace, pk=self.kwargs["pk"]).owners.all() ns = get_object_or_404(LegacyNamespace, pk=self.kwargs["pk"]) if ns.namespace: return get_v3_namespace_owners(ns.namespace) diff --git a/galaxy_ng/app/api/v1/viewsets/roles.py b/galaxy_ng/app/api/v1/viewsets/roles.py index 65d66d9aa4..efe2e5cb0b 100644 --- a/galaxy_ng/app/api/v1/viewsets/roles.py +++ b/galaxy_ng/app/api/v1/viewsets/roles.py @@ -95,9 +95,7 @@ def list(self, request): counter.save() except DatabaseInternalError as e: # Fail gracefully if the database is in read-only mode. - if "read-only" in str(e): - pass - else: + if "read-only" not in str(e): raise e return super().list(request) diff --git a/galaxy_ng/app/api/v1/viewsets/tasks.py b/galaxy_ng/app/api/v1/viewsets/tasks.py index 762d3dbcd1..8057367ba4 100644 --- a/galaxy_ng/app/api/v1/viewsets/tasks.py +++ b/galaxy_ng/app/api/v1/viewsets/tasks.py @@ -73,18 +73,20 @@ def get_task(self, request, id=None): } # generate a message for the response + # FIXME(cutwater): Begin of the code that does nothing msg = '' if state == 'SUCCESS': msg = 'role imported successfully' elif state == 'RUNNING': msg = 'running' - if this_task.error: - if this_task.error.get('traceback'): - msg = ( - this_task.error['description'] - + '\n' - + this_task.error['traceback'] - ) + + if this_task.error and this_task.error.get('traceback'): + msg = ( + this_task.error['description'] + + '\n' + + this_task.error['traceback'] + ) + # FIXME(cutwater): End of the code that does nothing task_messages = [] diff --git a/galaxy_ng/app/common/openapi.py b/galaxy_ng/app/common/openapi.py index d55fff5fb2..623e0090d4 100644 --- a/galaxy_ng/app/common/openapi.py +++ b/galaxy_ng/app/common/openapi.py @@ -16,11 +16,6 @@ def preprocess_debug_logger(endpoints, **kwargs): path, path_regex, method, callback) return endpoints - # return [ - # (path, path_regex, method, callback) for path, path_regex, method, callback in endpoints - # if log.debug('path=%s, path_regex=%s, method=%s, callback=%s', - # path, path_regex, method, callback) - # ] def preprocess_exclude_endpoints(endpoints, **kwargs): diff --git a/galaxy_ng/app/dynaconf_hooks.py b/galaxy_ng/app/dynaconf_hooks.py index efe5897d54..0837f3dd4f 100755 --- a/galaxy_ng/app/dynaconf_hooks.py +++ b/galaxy_ng/app/dynaconf_hooks.py @@ -129,7 +129,6 @@ def configure_keycloak(settings: Dynaconf) -> Dict[str, Any]: "SOCIAL_AUTH_LOGIN_REDIRECT_URL", default="/ui/" ) data["SOCIAL_AUTH_JSONFIELD_ENABLED"] = True - # data["SOCIAL_AUTH_JSONFIELD_CUSTOM"] = "django.db.models.JSONField" data["SOCIAL_AUTH_URL_NAMESPACE"] = "social" data["SOCIAL_AUTH_KEYCLOAK_EXTRA_DATA"] = [ ("refresh_token", "refresh_token"), @@ -209,11 +208,6 @@ def configure_socialauth(settings: Dynaconf) -> Dict[str, Any]: data = {} - # SOCIAL_AUTH_GITHUB_BASE_URL = \ - # settings.get('SOCIAL_AUTH_GITHUB_BASE_URL', default='https://github.com') - # SOCIAL_AUTH_GITHUB_API_URL = \ - # settings.get('SOCIAL_AUTH_GITHUB_BASE_URL', default='https://api.github.com') - SOCIAL_AUTH_GITHUB_KEY = settings.get("SOCIAL_AUTH_GITHUB_KEY", default=None) SOCIAL_AUTH_GITHUB_SECRET = settings.get("SOCIAL_AUTH_GITHUB_SECRET", default=None) diff --git a/galaxy_ng/app/tasks/namespaces.py b/galaxy_ng/app/tasks/namespaces.py index 24b0a116a5..00c6fb92df 100644 --- a/galaxy_ng/app/tasks/namespaces.py +++ b/galaxy_ng/app/tasks/namespaces.py @@ -46,9 +46,14 @@ def _download_avatar(url, namespace_name): try: downloader = HttpDownloader(url, session=session) img = downloader.fetch() - except: # noqa + except Exception: # noqa + # FIXME(cutwater): Handling base exception class is a bad practice, as well as ignoring it. return finally: + # FIXME(cutwater): The `asyncio.get_event_loop()` must not be used in the code. + # It is deprecated and it's original behavior may change in future. + # Users must not rely on the original behavior. + # https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop asyncio.get_event_loop().run_until_complete(session.close()) # Limit size of the avatar to avoid memory issues when validating it