From ed9976593854bae9816a300d54ea8fd4c6c187db Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Tue, 28 Feb 2023 01:36:41 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- accounting/api/account.py | 12 +- restauth/models.py | 2 +- .../site-packages/asgiref/compatibility.py | 9 +- .../python3.9/site-packages/asgiref/local.py | 5 +- .../python3.9/site-packages/asgiref/server.py | 3 +- .../python3.9/site-packages/asgiref/sync.py | 22 +- .../python3.9/site-packages/asgiref/wsgi.py | 10 +- .../site-packages/django/apps/config.py | 17 +- .../site-packages/django/apps/registry.py | 37 +- .../site-packages/django/conf/__init__.py | 14 +- .../site-packages/django/conf/urls/i18n.py | 32 +- .../site-packages/django/conf/urls/static.py | 6 +- .../django/contrib/admin/actions.py | 8 +- .../django/contrib/admin/checks.py | 608 +++++++++--------- .../django/contrib/admin/decorators.py | 10 +- .../django/contrib/admin/filters.py | 45 +- .../django/contrib/admin/helpers.py | 15 +- .../django/contrib/admin/models.py | 104 ++- .../django/contrib/admin/options.py | 205 +++--- .../django/contrib/admin/sites.py | 27 +- .../contrib/admin/templatetags/admin_list.py | 236 ++++--- .../admin/templatetags/admin_modify.py | 35 +- .../contrib/admin/templatetags/admin_urls.py | 15 +- .../django/contrib/admin/templatetags/base.py | 6 +- .../django/contrib/admin/templatetags/log.py | 9 +- .../django/contrib/admin/tests.py | 14 +- .../django/contrib/admin/utils.py | 97 ++- .../contrib/admin/views/autocomplete.py | 3 +- .../django/contrib/admin/views/decorators.py | 4 +- .../django/contrib/admin/views/main.py | 53 +- .../django/contrib/admin/widgets.py | 47 +- .../django/contrib/admindocs/utils.py | 36 +- .../django/contrib/admindocs/views.py | 109 ++-- .../django/contrib/auth/__init__.py | 5 +- .../django/contrib/auth/admin.py | 13 +- .../django/contrib/auth/backends.py | 10 +- .../django/contrib/auth/base_user.py | 2 +- .../django/contrib/auth/checks.py | 13 +- .../django/contrib/auth/context_processors.py | 2 +- .../django/contrib/auth/decorators.py | 9 +- .../django/contrib/auth/forms.py | 38 +- .../django/contrib/auth/handlers/modwsgi.py | 12 +- .../django/contrib/auth/hashers.py | 18 +- .../contrib/auth/management/__init__.py | 22 +- .../management/commands/changepassword.py | 20 +- .../management/commands/createsuperuser.py | 62 +- .../django/contrib/auth/middleware.py | 5 +- .../0011_update_proxy_permissions.py | 7 +- .../django/contrib/auth/mixins.py | 44 +- .../django/contrib/auth/models.py | 6 +- .../contrib/auth/password_validation.py | 5 +- .../django/contrib/auth/tokens.py | 19 +- .../django/contrib/auth/views.py | 24 +- .../django/contrib/contenttypes/admin.py | 91 ++- .../django/contrib/contenttypes/checks.py | 22 +- .../django/contrib/contenttypes/fields.py | 94 ++- .../django/contrib/contenttypes/forms.py | 18 +- .../contenttypes/management/__init__.py | 10 +- .../commands/remove_stale_contenttypes.py | 28 +- .../django/contrib/contenttypes/models.py | 12 +- .../django/contrib/contenttypes/views.py | 14 +- .../django/contrib/flatpages/models.py | 2 +- .../flatpages/templatetags/flatpages.py | 44 +- .../django/contrib/flatpages/views.py | 4 +- .../django/contrib/gis/admin/options.py | 25 +- .../django/contrib/gis/admin/widgets.py | 8 +- .../contrib/gis/db/backends/base/features.py | 3 +- .../contrib/gis/db/backends/base/models.py | 52 +- .../gis/db/backends/base/operations.py | 26 +- .../gis/db/backends/mysql/introspection.py | 2 +- .../gis/db/backends/mysql/operations.py | 4 +- .../contrib/gis/db/backends/mysql/schema.py | 2 +- .../gis/db/backends/oracle/introspection.py | 6 +- .../contrib/gis/db/backends/oracle/models.py | 2 +- .../gis/db/backends/oracle/operations.py | 43 +- .../contrib/gis/db/backends/oracle/schema.py | 2 +- .../gis/db/backends/postgis/adapter.py | 7 +- .../gis/db/backends/postgis/introspection.py | 3 +- .../gis/db/backends/postgis/operations.py | 129 ++-- .../gis/db/backends/postgis/pgraster.py | 6 +- .../contrib/gis/db/backends/postgis/schema.py | 2 +- .../db/backends/spatialite/introspection.py | 5 +- .../gis/db/backends/spatialite/operations.py | 4 +- .../gis/db/backends/spatialite/schema.py | 20 +- .../django/contrib/gis/db/backends/utils.py | 5 +- .../django/contrib/gis/db/models/fields.py | 34 +- .../django/contrib/gis/db/models/functions.py | 31 +- .../django/contrib/gis/db/models/lookups.py | 6 +- .../django/contrib/gis/db/models/proxy.py | 8 +- .../contrib/gis/db/models/sql/conversion.py | 12 +- .../site-packages/django/contrib/gis/feeds.py | 23 +- .../django/contrib/gis/forms/fields.py | 5 +- .../django/contrib/gis/forms/widgets.py | 34 +- .../django/contrib/gis/gdal/datasource.py | 20 +- .../django/contrib/gis/gdal/driver.py | 4 +- .../django/contrib/gis/gdal/envelope.py | 17 +- .../django/contrib/gis/gdal/error.py | 2 +- .../django/contrib/gis/gdal/feature.py | 4 +- .../django/contrib/gis/gdal/field.py | 7 +- .../django/contrib/gis/gdal/geometries.py | 60 +- .../django/contrib/gis/gdal/geomtype.py | 4 +- .../django/contrib/gis/gdal/layer.py | 8 +- .../django/contrib/gis/gdal/libgdal.py | 9 +- .../contrib/gis/gdal/prototypes/errcheck.py | 11 +- .../contrib/gis/gdal/prototypes/generation.py | 15 +- .../django/contrib/gis/gdal/raster/base.py | 9 +- .../django/contrib/gis/gdal/raster/source.py | 28 +- .../django/contrib/gis/gdal/srs.py | 12 +- .../django/contrib/gis/geoip2/base.py | 36 +- .../django/contrib/gis/geos/collections.py | 7 +- .../django/contrib/gis/geos/coordseq.py | 22 +- .../django/contrib/gis/geos/factory.py | 18 +- .../django/contrib/gis/geos/geometry.py | 22 +- .../django/contrib/gis/geos/libgeos.py | 7 +- .../django/contrib/gis/geos/linestring.py | 21 +- .../django/contrib/gis/geos/mutable_list.py | 35 +- .../django/contrib/gis/geos/point.py | 15 +- .../django/contrib/gis/geos/polygon.py | 13 +- .../contrib/gis/geos/prototypes/errcheck.py | 19 +- .../contrib/gis/geos/prototypes/threadsafe.py | 2 +- .../gis/management/commands/ogrinspect.py | 10 +- .../django/contrib/gis/measure.py | 16 +- .../site-packages/django/contrib/gis/ptr.py | 4 +- .../django/contrib/gis/sitemaps/kml.py | 16 +- .../django/contrib/gis/sitemaps/views.py | 10 +- .../django/contrib/gis/utils/layermapping.py | 82 +-- .../django/contrib/gis/utils/ogrinfo.py | 28 +- .../django/contrib/gis/utils/ogrinspect.py | 39 +- .../site-packages/django/contrib/gis/views.py | 6 +- .../contrib/humanize/templatetags/humanize.py | 31 +- .../django/contrib/messages/storage/base.py | 8 +- .../django/contrib/messages/views.py | 3 +- .../contrib/postgres/aggregates/mixins.py | 28 +- .../django/contrib/postgres/constraints.py | 24 +- .../django/contrib/postgres/fields/array.py | 50 +- .../django/contrib/postgres/fields/citext.py | 2 +- .../django/contrib/postgres/fields/hstore.py | 3 +- .../django/contrib/postgres/fields/ranges.py | 14 +- .../django/contrib/postgres/forms/array.py | 11 +- .../django/contrib/postgres/forms/hstore.py | 4 +- .../django/contrib/postgres/forms/ranges.py | 4 +- .../django/contrib/postgres/indexes.py | 20 +- .../django/contrib/postgres/operations.py | 47 +- .../django/contrib/postgres/search.py | 24 +- .../django/contrib/postgres/serializers.py | 2 +- .../django/contrib/postgres/validators.py | 6 +- .../django/contrib/redirects/models.py | 2 +- .../django/contrib/sessions/backends/base.py | 14 +- .../django/contrib/sessions/backends/cache.py | 2 +- .../contrib/sessions/backends/cached_db.py | 3 +- .../django/contrib/sessions/backends/db.py | 2 +- .../django/contrib/sessions/backends/file.py | 6 +- .../django/contrib/sitemaps/__init__.py | 42 +- .../django/contrib/sitemaps/views.py | 23 +- .../django/contrib/sites/management.py | 7 +- .../django/contrib/sites/managers.py | 17 +- .../django/contrib/staticfiles/finders.py | 13 +- .../django/contrib/staticfiles/handlers.py | 8 +- .../management/commands/collectstatic.py | 74 +-- .../management/commands/findstatic.py | 17 +- .../django/contrib/staticfiles/storage.py | 29 +- .../django/contrib/staticfiles/views.py | 2 +- .../django/contrib/syndication/views.py | 12 +- .../django/core/cache/__init__.py | 2 +- .../django/core/cache/backends/base.py | 15 +- .../django/core/cache/backends/db.py | 24 +- .../django/core/cache/backends/filebased.py | 11 +- .../django/core/cache/backends/locmem.py | 4 +- .../django/core/cache/backends/memcached.py | 20 +- .../django/core/cache/backends/redis.py | 21 +- .../django/core/checks/async_checks.py | 4 +- .../django/core/checks/caches.py | 8 +- .../core/checks/compatibility/django_4_0.py | 21 +- .../django/core/checks/messages.py | 4 +- .../django/core/checks/model_checks.py | 44 +- .../django/core/checks/registry.py | 7 +- .../django/core/checks/security/base.py | 6 +- .../django/core/checks/security/csrf.py | 5 +- .../site-packages/django/core/checks/urls.py | 25 +- .../site-packages/django/core/exceptions.py | 14 +- .../site-packages/django/core/files/base.py | 8 +- .../site-packages/django/core/files/images.py | 4 +- .../site-packages/django/core/files/move.py | 5 +- .../django/core/files/storage.py | 8 +- .../django/core/files/uploadedfile.py | 4 +- .../site-packages/django/core/files/utils.py | 16 +- .../django/core/handlers/asgi.py | 23 +- .../django/core/handlers/base.py | 27 +- .../django/core/handlers/exception.py | 2 +- .../django/core/handlers/wsgi.py | 20 +- .../django/core/mail/__init__.py | 4 +- .../django/core/mail/backends/filebased.py | 12 +- .../django/core/mail/backends/smtp.py | 31 +- .../site-packages/django/core/mail/message.py | 29 +- .../django/core/management/__init__.py | 31 +- .../django/core/management/base.py | 25 +- .../django/core/management/commands/check.py | 4 +- .../management/commands/compilemessages.py | 15 +- .../management/commands/createcachetable.py | 24 +- .../core/management/commands/dbshell.py | 6 +- .../core/management/commands/diffsettings.py | 22 +- .../core/management/commands/dumpdata.py | 23 +- .../core/management/commands/inspectdb.py | 40 +- .../core/management/commands/loaddata.py | 66 +- .../core/management/commands/makemessages.py | 114 ++-- .../management/commands/makemigrations.py | 62 +- .../django/core/management/sql.py | 4 +- .../django/core/management/templates.py | 88 +-- .../django/core/management/utils.py | 8 +- .../site-packages/django/core/paginator.py | 21 +- .../site-packages/django/core/signing.py | 19 +- .../site-packages/django/core/validators.py | 66 +- .../site-packages/django/shortcuts.py | 13 +- .../site-packages/typing_extensions.py | 81 +-- 214 files changed, 2282 insertions(+), 3109 deletions(-) diff --git a/accounting/api/account.py b/accounting/api/account.py index e843e616..107ada95 100644 --- a/accounting/api/account.py +++ b/accounting/api/account.py @@ -23,8 +23,7 @@ def get_all(request): }) def get_one(request, account_id: int): try: - account = Account.objects.get(id=account_id) - return account + return Account.objects.get(id=account_id) except Account.DoesNotExist: return 404, {'detail': f'Account with id {account_id} does not exist'} @@ -48,12 +47,9 @@ def get_account_balance(request, account_id: int): @account_router.get('/account-balances/', response=List[GeneralLedgerOut]) def get_account_balances(request): accounts = Account.objects.all() - result = [] - for a in accounts: - result.append({ - 'account': a.name, 'balance': list(a.balance()) - }) - + result = [ + {'account': a.name, 'balance': list(a.balance())} for a in accounts + ] return status.HTTP_200_OK, result diff --git a/restauth/models.py b/restauth/models.py index 599792b7..f014d2d5 100644 --- a/restauth/models.py +++ b/restauth/models.py @@ -6,7 +6,7 @@ class EmailAccountManager(UserManager): def get_by_natural_key(self, username): - case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) + case_insensitive_username_field = f'{self.model.USERNAME_FIELD}__iexact' return self.get(**{case_insensitive_username_field: username}) def create_user(self, first_name, last_name, email, password=None): diff --git a/unicoding_venv/lib/python3.9/site-packages/asgiref/compatibility.py b/unicoding_venv/lib/python3.9/site-packages/asgiref/compatibility.py index eccaee0d..b75fcd5f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/asgiref/compatibility.py +++ b/unicoding_venv/lib/python3.9/site-packages/asgiref/compatibility.py @@ -15,11 +15,10 @@ def is_double_callable(application): if inspect.isclass(application): return True # Instanted classes depend on their __call__ - if hasattr(application, "__call__"): - # We only check to see if its __call__ is a coroutine function - - # if it's not, it still might be a coroutine function itself. - if asyncio.iscoroutinefunction(application.__call__): - return False + if hasattr(application, "__call__") and asyncio.iscoroutinefunction( + application.__call__ + ): + return False # Non-classes we just check directly return not asyncio.iscoroutinefunction(application) diff --git a/unicoding_venv/lib/python3.9/site-packages/asgiref/local.py b/unicoding_venv/lib/python3.9/site-packages/asgiref/local.py index 17314d4e..1dec46e2 100644 --- a/unicoding_venv/lib/python3.9/site-packages/asgiref/local.py +++ b/unicoding_venv/lib/python3.9/site-packages/asgiref/local.py @@ -36,10 +36,7 @@ def __init__(self, thread_critical: bool = False) -> None: self._context_refs: "weakref.WeakSet[object]" = weakref.WeakSet() # Random suffixes stop accidental reuse between different Locals, # though we try to force deletion as well. - self._attr_name = "_asgiref_local_impl_{}_{}".format( - id(self), - "".join(random.choice(string.ascii_letters) for i in range(8)), - ) + self._attr_name = f'_asgiref_local_impl_{id(self)}_{"".join(random.choice(string.ascii_letters) for _ in range(8))}' def _get_context_id(self): """ diff --git a/unicoding_venv/lib/python3.9/site-packages/asgiref/server.py b/unicoding_venv/lib/python3.9/site-packages/asgiref/server.py index 43c28c6c..6d12d236 100644 --- a/unicoding_venv/lib/python3.9/site-packages/asgiref/server.py +++ b/unicoding_venv/lib/python3.9/site-packages/asgiref/server.py @@ -136,8 +136,7 @@ async def application_checker(self): await asyncio.sleep(self.application_checker_interval) for scope_id, details in list(self.application_instances.items()): if details["future"].done(): - exception = details["future"].exception() - if exception: + if exception := details["future"].exception(): await self.application_exception(exception, details) try: del self.application_instances[scope_id] diff --git a/unicoding_venv/lib/python3.9/site-packages/asgiref/sync.py b/unicoding_venv/lib/python3.9/site-packages/asgiref/sync.py index 62470432..55e08f32 100644 --- a/unicoding_venv/lib/python3.9/site-packages/asgiref/sync.py +++ b/unicoding_venv/lib/python3.9/site-packages/asgiref/sync.py @@ -30,15 +30,13 @@ def _iscoroutinefunction_or_partial(func: Any) -> bool: # Python < 3.8 does not correctly determine partially wrapped # coroutine functions are coroutine functions, hence the need for # this to exist. Code taken from CPython. - if sys.version_info >= (3, 8): - return asyncio.iscoroutinefunction(func) - else: + if sys.version_info < (3, 8): while inspect.ismethod(func): func = func.__func__ while isinstance(func, functools.partial): func = func.func - return asyncio.iscoroutinefunction(func) + return asyncio.iscoroutinefunction(func) class ThreadSensitiveContext: @@ -76,8 +74,7 @@ async def __aexit__(self, exc, value, tb): if not self.token: return - executor = SyncToAsync.context_to_thread_executor.pop(self, None) - if executor: + if executor := SyncToAsync.context_to_thread_executor.pop(self, None): executor.shutdown() SyncToAsync.thread_sensitive_context.reset(self.token) @@ -465,14 +462,11 @@ def thread_handler(self, loop, source_task, exc_info, func, *args, **kwargs): parent_set = True # Run the function try: - # If we have an exception, run the function inside the except block - # after raising it so exc_info is correctly populated. - if exc_info[1]: - try: - raise exc_info[1] - except BaseException: - return func(*args, **kwargs) - else: + if not exc_info[1]: + return func(*args, **kwargs) + try: + raise exc_info[1] + except BaseException: return func(*args, **kwargs) finally: # Only delete the launch_map parent if we set it, otherwise it is diff --git a/unicoding_venv/lib/python3.9/site-packages/asgiref/wsgi.py b/unicoding_venv/lib/python3.9/site-packages/asgiref/wsgi.py index 40fba205..dd911b84 100644 --- a/unicoding_venv/lib/python3.9/site-packages/asgiref/wsgi.py +++ b/unicoding_venv/lib/python3.9/site-packages/asgiref/wsgi.py @@ -56,10 +56,12 @@ def build_environ(self, scope, body): """ environ = { "REQUEST_METHOD": scope["method"], - "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"), + "SCRIPT_NAME": scope.get("root_path", "") + .encode("utf8") + .decode("latin1"), "PATH_INFO": scope["path"].encode("utf8").decode("latin1"), "QUERY_STRING": scope["query_string"].decode("ascii"), - "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"], + "SERVER_PROTOCOL": f'HTTP/{scope["http_version"]}', "wsgi.version": (1, 0), "wsgi.url_scheme": scope.get("scheme", "http"), "wsgi.input": body, @@ -87,11 +89,11 @@ def build_environ(self, scope, body): elif name == "content-type": corrected_name = "CONTENT_TYPE" else: - corrected_name = "HTTP_%s" % name.upper().replace("-", "_") + corrected_name = f'HTTP_{name.upper().replace("-", "_")}' # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case value = value.decode("latin1") if corrected_name in environ: - value = environ[corrected_name] + "," + value + value = f"{environ[corrected_name]},{value}" environ[corrected_name] = value return environ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/apps/config.py b/unicoding_venv/lib/python3.9/site-packages/django/apps/config.py index 53d38521..6422e814 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/apps/config.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/apps/config.py @@ -36,7 +36,7 @@ def __init__(self, app_name, app_module): self.label = app_name.rpartition(".")[2] if not self.label.isidentifier(): raise ImproperlyConfigured( - "The app label '%s' is not a valid Python identifier." % self.label + f"The app label '{self.label}' is not a valid Python identifier." ) # Human-readable name for the application e.g. "Admin". @@ -58,7 +58,7 @@ def __init__(self, app_name, app_module): self.models = None def __repr__(self): - return "<%s: %s>" % (self.__class__.__name__, self.label) + return f"<{self.__class__.__name__}: {self.label}>" @cached_property def default_auto_field(self): @@ -78,12 +78,7 @@ def _path_from_module(self, module): paths = list(getattr(module, "__path__", [])) if len(paths) != 1: filename = getattr(module, "__file__", None) - if filename is not None: - paths = [os.path.dirname(filename)] - else: - # For unknown reasons, sometimes the list returned by __path__ - # contains duplicates that must be removed (#25246). - paths = list(set(paths)) + paths = list(set(paths)) if filename is None else [os.path.dirname(filename)] if len(paths) > 1: raise ImproperlyConfigured( "The app module %r has multiple filesystem locations (%r); " @@ -269,9 +264,7 @@ def get_model(self, model_name, require_ready=True): try: return self.models[model_name.lower()] except KeyError: - raise LookupError( - "App '%s' doesn't have a '%s' model." % (self.label, model_name) - ) + raise LookupError(f"App '{self.label}' doesn't have a '{model_name}' model.") def get_models(self, include_auto_created=False, include_swapped=False): """ @@ -300,7 +293,7 @@ def import_models(self): self.models = self.apps.all_models[self.label] if module_has_submodule(self.module, MODELS_MODULE_NAME): - models_module_name = "%s.%s" % (self.name, MODELS_MODULE_NAME) + models_module_name = f"{self.name}.{MODELS_MODULE_NAME}" self.models_module = import_module(models_module_name) def ready(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/apps/registry.py b/unicoding_venv/lib/python3.9/site-packages/django/apps/registry.py index c5ba3a30..14385bc1 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/apps/registry.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/apps/registry.py @@ -85,14 +85,10 @@ def populate(self, installed_apps=None): # Phase 1: initialize app configs and import app modules. for entry in installed_apps: - if isinstance(entry, AppConfig): - app_config = entry - else: - app_config = AppConfig.create(entry) + app_config = entry if isinstance(entry, AppConfig) else AppConfig.create(entry) if app_config.label in self.app_configs: raise ImproperlyConfigured( - "Application labels aren't unique, " - "duplicates: %s" % app_config.label + f"Application labels aren't unique, duplicates: {app_config.label}" ) self.app_configs[app_config.label] = app_config @@ -102,11 +98,11 @@ def populate(self, installed_apps=None): counts = Counter( app_config.name for app_config in self.app_configs.values() ) - duplicates = [name for name, count in counts.most_common() if count > 1] - if duplicates: + if duplicates := [ + name for name, count in counts.most_common() if count > 1 + ]: raise ImproperlyConfigured( - "Application names aren't unique, " - "duplicates: %s" % ", ".join(duplicates) + f"""Application names aren't unique, duplicates: {", ".join(duplicates)}""" ) self.apps_ready = True @@ -157,10 +153,10 @@ def get_app_config(self, app_label): try: return self.app_configs[app_label] except KeyError: - message = "No installed app with label '%s'." % app_label + message = f"No installed app with label '{app_label}'." for app_config in self.get_app_configs(): if app_config.name == app_label: - message += " Did you mean '%s'?" % app_config.label + message += f" Did you mean '{app_config.label}'?" break raise LookupError(message) @@ -213,27 +209,21 @@ def get_model(self, app_label, model_name=None, require_ready=True): return app_config.get_model(model_name, require_ready=require_ready) def register_model(self, app_label, model): - # Since this method is called when models are imported, it cannot - # perform imports because of the risk of import loops. It mustn't - # call get_app_config(). - model_name = model._meta.model_name app_models = self.all_models[app_label] + model_name = model._meta.model_name if model_name in app_models: if ( model.__name__ == app_models[model_name].__name__ and model.__module__ == app_models[model_name].__module__ ): warnings.warn( - "Model '%s.%s' was already registered. Reloading models is not " - "advised as it can lead to inconsistencies, most notably with " - "related models." % (app_label, model_name), + f"Model '{app_label}.{model_name}' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.", RuntimeWarning, stacklevel=2, ) else: raise RuntimeError( - "Conflicting '%s' models in application '%s': %s and %s." - % (model_name, app_label, app_models[model_name], model) + f"Conflicting '{model_name}' models in application '{app_label}': {app_models[model_name]} and {model}." ) app_models[model_name] = model self.do_pending_operations(model) @@ -277,7 +267,7 @@ def get_registered_model(self, app_label, model_name): """ model = self.all_models[app_label].get(model_name.lower()) if model is None: - raise LookupError("Model '%s.%s' not registered." % (app_label, model_name)) + raise LookupError(f"Model '{app_label}.{model_name}' not registered.") return model @functools.lru_cache(maxsize=None) @@ -319,8 +309,7 @@ def set_available_apps(self, available): installed = {app_config.name for app_config in self.get_app_configs()} if not available.issubset(installed): raise ValueError( - "Available apps isn't a subset of installed apps, extra apps: %s" - % ", ".join(available - installed) + f"""Available apps isn't a subset of installed apps, extra apps: {", ".join(available - installed)}""" ) self.stored_app_configs.append(self.app_configs) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/conf/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/conf/__init__.py index 2fda24a2..047ede02 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/conf/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/conf/__init__.py @@ -41,8 +41,8 @@ class SettingsReference(str): the value in memory but serializes to a settings.NAME attribute reference. """ - def __new__(self, value, setting_name): - return str.__new__(self, value) + def __new__(cls, value, setting_name): + return str.__new__(cls, value) def __init__(self, value, setting_name): self.setting_name = setting_name @@ -63,7 +63,7 @@ def _setup(self, name=None): """ settings_module = os.environ.get(ENVIRONMENT_VARIABLE) if not settings_module: - desc = ("setting %s" % name) if name else "settings" + desc = f"setting {name}" if name else "settings" raise ImproperlyConfigured( "Requested %s, but settings are not configured. " "You must either define the environment variable %s " @@ -141,7 +141,7 @@ def _add_script_prefix(value): return value from django.urls import get_script_prefix - return "%s%s" % (get_script_prefix(), value) + return f"{get_script_prefix()}{value}" @property def configured(self): @@ -196,9 +196,7 @@ def __init__(self, settings_module): if setting in tuple_settings and not isinstance( setting_value, (list, tuple) ): - raise ImproperlyConfigured( - "The %s setting must be a list or a tuple." % setting - ) + raise ImproperlyConfigured(f"The {setting} setting must be a list or a tuple.") setattr(self, setting, setting_value) self._explicit_settings.add(setting) @@ -219,7 +217,7 @@ def __init__(self, settings_module): zoneinfo_root = Path("/usr/share/zoneinfo") zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split("/")) if zoneinfo_root.exists() and not zone_info_file.exists(): - raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) + raise ValueError(f"Incorrect timezone setting: {self.TIME_ZONE}") # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ["TZ"] = self.TIME_ZONE diff --git a/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/i18n.py b/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/i18n.py index ebe5d51b..75b8040f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/i18n.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/i18n.py @@ -10,14 +10,18 @@ def i18n_patterns(*urls, prefix_default_language=True): Add the language code prefix to every URL pattern within this function. This may only be used in the root URLconf, not in an included URLconf. """ - if not settings.USE_I18N: - return list(urls) - return [ - URLResolver( - LocalePrefixPattern(prefix_default_language=prefix_default_language), - list(urls), - ) - ] + return ( + [ + URLResolver( + LocalePrefixPattern( + prefix_default_language=prefix_default_language + ), + list(urls), + ) + ] + if settings.USE_I18N + else list(urls) + ) @functools.lru_cache(maxsize=None) @@ -28,10 +32,14 @@ def is_language_prefix_patterns_used(urlconf): `True` if the default language should be prefixed ) """ - for url_pattern in get_resolver(urlconf).url_patterns: - if isinstance(url_pattern.pattern, LocalePrefixPattern): - return True, url_pattern.pattern.prefix_default_language - return False, False + return next( + ( + (True, url_pattern.pattern.prefix_default_language) + for url_pattern in get_resolver(urlconf).url_patterns + if isinstance(url_pattern.pattern, LocalePrefixPattern) + ), + (False, False), + ) urlpatterns = [ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/static.py b/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/static.py index 8e7816e7..bfa72048 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/static.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/conf/urls/static.py @@ -25,6 +25,8 @@ def static(prefix, view=serve, **kwargs): return [] return [ re_path( - r"^%s(?P.*)$" % re.escape(prefix.lstrip("/")), view, kwargs=kwargs - ), + f'^{re.escape(prefix.lstrip("/"))}(?P.*)$', + view, + kwargs=kwargs, + ) ] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/actions.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/actions.py index 60dc848e..8b52c54e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/actions.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/actions.py @@ -43,8 +43,7 @@ def delete_selected(modeladmin, request, queryset): if request.POST.get("post") and not protected: if perms_needed: raise PermissionDenied - n = queryset.count() - if n: + if n := queryset.count(): for obj in queryset: obj_display = str(obj) modeladmin.log_deletion(request, obj, obj_display) @@ -86,9 +85,8 @@ def delete_selected(modeladmin, request, queryset): request, modeladmin.delete_selected_confirmation_template or [ - "admin/%s/%s/delete_selected_confirmation.html" - % (app_label, opts.model_name), - "admin/%s/delete_selected_confirmation.html" % app_label, + f"admin/{app_label}/{opts.model_name}/delete_selected_confirmation.html", + f"admin/{app_label}/delete_selected_confirmation.html", "admin/delete_selected_confirmation.html", ], context, diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/checks.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/checks.py index 10d33b06..362b8d26 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/checks.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/checks.py @@ -60,37 +60,27 @@ def check_dependencies(**kwargs): if not apps.is_installed("django.contrib.admin"): return [] - errors = [] app_dependencies = ( ("django.contrib.contenttypes", 401), ("django.contrib.auth", 405), ("django.contrib.messages", 406), ) - for app_name, error_code in app_dependencies: - if not apps.is_installed(app_name): - errors.append( - checks.Error( - "'%s' must be in INSTALLED_APPS in order to use the admin " - "application." % app_name, - id="admin.E%d" % error_code, - ) - ) - for engine in engines.all(): - if isinstance(engine, DjangoTemplates): - django_templates_instance = engine.engine - break - else: - django_templates_instance = None - if not django_templates_instance: - errors.append( - checks.Error( - "A 'django.template.backends.django.DjangoTemplates' instance " - "must be configured in TEMPLATES in order to use the admin " - "application.", - id="admin.E403", - ) + errors = [ + checks.Error( + f"'{app_name}' must be in INSTALLED_APPS in order to use the admin application.", + id="admin.E%d" % error_code, ) - else: + for app_name, error_code in app_dependencies + if not apps.is_installed(app_name) + ] + if django_templates_instance := next( + ( + engine.engine + for engine in engines.all() + if isinstance(engine, DjangoTemplates) + ), + None, + ): if ( "django.contrib.auth.context_processors.auth" not in django_templates_instance.context_processors @@ -134,6 +124,15 @@ def check_dependencies(**kwargs): ) ) + else: + errors.append( + checks.Error( + "A 'django.template.backends.django.DjangoTemplates' instance " + "must be configured in TEMPLATES in order to use the admin " + "application.", + id="admin.E403", + ) + ) if not _contains_subclass( "django.contrib.auth.middleware.AuthenticationMiddleware", settings.MIDDLEWARE ): @@ -195,15 +194,8 @@ def _check_autocomplete_fields(self, obj): """ Check that `autocomplete_fields` is a list or tuple of model fields. """ - if not isinstance(obj.autocomplete_fields, (list, tuple)): - return must_be( - "a list or tuple", - option="autocomplete_fields", - obj=obj, - id="admin.E036", - ) - else: - return list( + return ( + list( chain.from_iterable( [ self._check_autocomplete_fields_item( @@ -213,6 +205,14 @@ def _check_autocomplete_fields(self, obj): ] ) ) + if isinstance(obj.autocomplete_fields, (list, tuple)) + else must_be( + "a list or tuple", + option="autocomplete_fields", + obj=obj, + id="admin.E036", + ) + ) def _check_autocomplete_fields_item(self, obj, field_name, label): """ @@ -267,12 +267,8 @@ def _check_raw_id_fields(self, obj): """Check that `raw_id_fields` only contains field names that are listed on the model.""" - if not isinstance(obj.raw_id_fields, (list, tuple)): - return must_be( - "a list or tuple", option="raw_id_fields", obj=obj, id="admin.E001" - ) - else: - return list( + return ( + list( chain.from_iterable( self._check_raw_id_fields_item( obj, field_name, "raw_id_fields[%d]" % index @@ -280,6 +276,11 @@ def _check_raw_id_fields(self, obj): for index, field_name in enumerate(obj.raw_id_fields) ) ) + if isinstance(obj.raw_id_fields, (list, tuple)) + else must_be( + "a list or tuple", option="raw_id_fields", obj=obj, id="admin.E001" + ) + ) def _check_raw_id_fields_item(self, obj, field_name, label): """Check an item of `raw_id_fields`, i.e. check that field named @@ -375,13 +376,11 @@ def _check_fieldsets_item(self, obj, fieldset, label, seen_fields): elif len(fieldset) != 2: return must_be("of length 2", option=label, obj=obj, id="admin.E009") elif not isinstance(fieldset[1], dict): - return must_be( - "a dictionary", option="%s[1]" % label, obj=obj, id="admin.E010" - ) + return must_be("a dictionary", option=f"{label}[1]", obj=obj, id="admin.E010") elif "fields" not in fieldset[1]: return [ checks.Error( - "The value of '%s[1]' must contain the key 'fields'." % label, + f"The value of '{label}[1]' must contain the key 'fields'.", obj=obj.__class__, id="admin.E011", ) @@ -389,7 +388,7 @@ def _check_fieldsets_item(self, obj, fieldset, label, seen_fields): elif not isinstance(fieldset[1]["fields"], (list, tuple)): return must_be( "a list or tuple", - option="%s[1]['fields']" % label, + option=f"{label}[1]['fields']", obj=obj, id="admin.E008", ) @@ -398,14 +397,16 @@ def _check_fieldsets_item(self, obj, fieldset, label, seen_fields): if len(seen_fields) != len(set(seen_fields)): return [ checks.Error( - "There are duplicate field(s) in '%s[1]'." % label, + f"There are duplicate field(s) in '{label}[1]'.", obj=obj.__class__, id="admin.E012", ) ] return list( chain.from_iterable( - self._check_field_spec(obj, fieldset_fields, '%s[1]["fields"]' % label) + self._check_field_spec( + obj, fieldset_fields, f'{label}[1]["fields"]' + ) for fieldset_fields in fieldset[1]["fields"] ) ) @@ -433,29 +434,27 @@ def _check_field_spec_item(self, obj, field_name, label): # it's in readonly_fields, readonly_fields will handle the # validation of such things. return [] + try: + field = obj.model._meta.get_field(field_name) + except FieldDoesNotExist: + # If we can't find a field on the model that matches, it could + # be an extra field on the form. + return [] else: - try: - field = obj.model._meta.get_field(field_name) - except FieldDoesNotExist: - # If we can't find a field on the model that matches, it could - # be an extra field on the form. - return [] - else: + return ( + [ + checks.Error( + f"The value of '{label}' cannot include the ManyToManyField '{field_name}', because that field manually specifies a relationship model.", + obj=obj.__class__, + id="admin.E013", + ) + ] if ( isinstance(field, models.ManyToManyField) and not field.remote_field.through._meta.auto_created - ): - return [ - checks.Error( - "The value of '%s' cannot include the ManyToManyField " - "'%s', because that field manually specifies a " - "relationship model." % (label, field_name), - obj=obj.__class__, - id="admin.E013", - ) - ] - else: - return [] + ) + else [] + ) def _check_exclude(self, obj): """Check that exclude is a sequence without duplicates.""" @@ -479,21 +478,18 @@ def _check_exclude(self, obj): def _check_form(self, obj): """Check that form subclasses BaseModelForm.""" - if not _issubclass(obj.form, BaseModelForm): - return must_inherit_from( + return ( + [] + if _issubclass(obj.form, BaseModelForm) + else must_inherit_from( parent="BaseModelForm", option="form", obj=obj, id="admin.E016" ) - else: - return [] + ) def _check_filter_vertical(self, obj): """Check that filter_vertical is a sequence of field names.""" - if not isinstance(obj.filter_vertical, (list, tuple)): - return must_be( - "a list or tuple", option="filter_vertical", obj=obj, id="admin.E017" - ) - else: - return list( + return ( + list( chain.from_iterable( self._check_filter_item( obj, field_name, "filter_vertical[%d]" % index @@ -501,15 +497,19 @@ def _check_filter_vertical(self, obj): for index, field_name in enumerate(obj.filter_vertical) ) ) + if isinstance(obj.filter_vertical, (list, tuple)) + else must_be( + "a list or tuple", + option="filter_vertical", + obj=obj, + id="admin.E017", + ) + ) def _check_filter_horizontal(self, obj): """Check that filter_horizontal is a sequence of field names.""" - if not isinstance(obj.filter_horizontal, (list, tuple)): - return must_be( - "a list or tuple", option="filter_horizontal", obj=obj, id="admin.E018" - ) - else: - return list( + return ( + list( chain.from_iterable( self._check_filter_item( obj, field_name, "filter_horizontal[%d]" % index @@ -517,6 +517,14 @@ def _check_filter_horizontal(self, obj): for index, field_name in enumerate(obj.filter_horizontal) ) ) + if isinstance(obj.filter_horizontal, (list, tuple)) + else must_be( + "a list or tuple", + option="filter_horizontal", + obj=obj, + id="admin.E018", + ) + ) def _check_filter_item(self, obj, field_name, label): """Check one item of `filter_vertical` or `filter_horizontal`, i.e. @@ -529,29 +537,31 @@ def _check_filter_item(self, obj, field_name, label): field=field_name, option=label, obj=obj, id="admin.E019" ) else: - if not field.many_to_many: - return must_be( + return ( + [] + if field.many_to_many + else must_be( "a many-to-many field", option=label, obj=obj, id="admin.E020" ) - else: - return [] + ) def _check_radio_fields(self, obj): """Check that `radio_fields` is a dictionary.""" - if not isinstance(obj.radio_fields, dict): - return must_be( - "a dictionary", option="radio_fields", obj=obj, id="admin.E021" - ) - else: - return list( + return ( + list( chain.from_iterable( self._check_radio_fields_key(obj, field_name, "radio_fields") + self._check_radio_fields_value( - obj, val, 'radio_fields["%s"]' % field_name + obj, val, f'radio_fields["{field_name}"]' ) for field_name, val in obj.radio_fields.items() ) ) + if isinstance(obj.radio_fields, dict) + else must_be( + "a dictionary", option="radio_fields", obj=obj, id="admin.E021" + ) + ) def _check_radio_fields_key(self, obj, field_name, label): """Check that a key of `radio_fields` dictionary is name of existing @@ -564,35 +574,34 @@ def _check_radio_fields_key(self, obj, field_name, label): field=field_name, option=label, obj=obj, id="admin.E022" ) else: - if not (isinstance(field, models.ForeignKey) or field.choices): - return [ + return ( + [] + if (isinstance(field, models.ForeignKey) or field.choices) + else [ checks.Error( - "The value of '%s' refers to '%s', which is not an " - "instance of ForeignKey, and does not have a 'choices' " - "definition." % (label, field_name), + f"The value of '{label}' refers to '{field_name}', which is not an instance of ForeignKey, and does not have a 'choices' definition.", obj=obj.__class__, id="admin.E023", ) ] - else: - return [] + ) def _check_radio_fields_value(self, obj, val, label): """Check type of a value of `radio_fields` dictionary.""" from django.contrib.admin.options import HORIZONTAL, VERTICAL - if val not in (HORIZONTAL, VERTICAL): - return [ + return ( + [ checks.Error( - "The value of '%s' must be either admin.HORIZONTAL or " - "admin.VERTICAL." % label, + f"The value of '{label}' must be either admin.HORIZONTAL or admin.VERTICAL.", obj=obj.__class__, id="admin.E024", ) ] - else: - return [] + if val not in (HORIZONTAL, VERTICAL) + else [] + ) def _check_view_on_site_url(self, obj): if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): @@ -610,22 +619,26 @@ def _check_view_on_site_url(self, obj): def _check_prepopulated_fields(self, obj): """Check that `prepopulated_fields` is a dictionary containing allowed field types.""" - if not isinstance(obj.prepopulated_fields, dict): - return must_be( - "a dictionary", option="prepopulated_fields", obj=obj, id="admin.E026" - ) - else: - return list( + return ( + list( chain.from_iterable( self._check_prepopulated_fields_key( obj, field_name, "prepopulated_fields" ) + self._check_prepopulated_fields_value( - obj, val, 'prepopulated_fields["%s"]' % field_name + obj, val, f'prepopulated_fields["{field_name}"]' ) for field_name, val in obj.prepopulated_fields.items() ) ) + if isinstance(obj.prepopulated_fields, dict) + else must_be( + "a dictionary", + option="prepopulated_fields", + obj=obj, + id="admin.E026", + ) + ) def _check_prepopulated_fields_key(self, obj, field_name, label): """Check a key of `prepopulated_fields` dictionary, i.e. check that it @@ -639,29 +652,31 @@ def _check_prepopulated_fields_key(self, obj, field_name, label): field=field_name, option=label, obj=obj, id="admin.E027" ) else: - if isinstance( - field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField) - ): - return [ + return ( + [ checks.Error( - "The value of '%s' refers to '%s', which must not be a " - "DateTimeField, a ForeignKey, a OneToOneField, or a " - "ManyToManyField." % (label, field_name), + f"The value of '{label}' refers to '{field_name}', which must not be a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", obj=obj.__class__, id="admin.E028", ) ] - else: - return [] + if isinstance( + field, + ( + models.DateTimeField, + models.ForeignKey, + models.ManyToManyField, + ), + ) + else [] + ) def _check_prepopulated_fields_value(self, obj, val, label): """Check a value of `prepopulated_fields` dictionary, i.e. it's an iterable of existing fields.""" - if not isinstance(val, (list, tuple)): - return must_be("a list or tuple", option=label, obj=obj, id="admin.E029") - else: - return list( + return ( + list( chain.from_iterable( self._check_prepopulated_fields_value_item( obj, subfield_name, "%s[%r]" % (label, index) @@ -669,6 +684,9 @@ def _check_prepopulated_fields_value(self, obj, val, label): for index, subfield_name in enumerate(val) ) ) + if isinstance(val, (list, tuple)) + else must_be("a list or tuple", option=label, obj=obj, id="admin.E029") + ) def _check_prepopulated_fields_value_item(self, obj, field_name, label): """For `prepopulated_fields` equal to {"slug": ("title",)}, @@ -760,31 +778,24 @@ def _check_readonly_fields(self, obj): ) def _check_readonly_fields_item(self, obj, field_name, label): - if callable(field_name): - return [] - elif hasattr(obj, field_name): - return [] - elif hasattr(obj.model, field_name): + if ( + callable(field_name) + or hasattr(obj, field_name) + or hasattr(obj.model, field_name) + ): return [] + try: + obj.model._meta.get_field(field_name) + except FieldDoesNotExist: + return [ + checks.Error( + f"The value of '{label}' is not a callable, an attribute of '{obj.__class__.__name__}', or an attribute of '{obj.model._meta.label}'.", + obj=obj.__class__, + id="admin.E035", + ) + ] else: - try: - obj.model._meta.get_field(field_name) - except FieldDoesNotExist: - return [ - checks.Error( - "The value of '%s' is not a callable, an attribute of " - "'%s', or an attribute of '%s'." - % ( - label, - obj.__class__.__name__, - obj.model._meta.label, - ), - obj=obj.__class__, - id="admin.E035", - ) - ] - else: - return [] + return [] class ModelAdminChecks(BaseModelAdminChecks): @@ -810,42 +821,47 @@ def check(self, admin_obj, **kwargs): def _check_save_as(self, obj): """Check save_as is a boolean.""" - if not isinstance(obj.save_as, bool): - return must_be("a boolean", option="save_as", obj=obj, id="admin.E101") - else: - return [] + return ( + [] + if isinstance(obj.save_as, bool) + else must_be("a boolean", option="save_as", obj=obj, id="admin.E101") + ) def _check_save_on_top(self, obj): """Check save_on_top is a boolean.""" - if not isinstance(obj.save_on_top, bool): - return must_be("a boolean", option="save_on_top", obj=obj, id="admin.E102") - else: - return [] + return ( + [] + if isinstance(obj.save_on_top, bool) + else must_be( + "a boolean", option="save_on_top", obj=obj, id="admin.E102" + ) + ) def _check_inlines(self, obj): """Check all inline model admin classes.""" - if not isinstance(obj.inlines, (list, tuple)): - return must_be( - "a list or tuple", option="inlines", obj=obj, id="admin.E103" - ) - else: - return list( + return ( + list( chain.from_iterable( self._check_inlines_item(obj, item, "inlines[%d]" % index) for index, item in enumerate(obj.inlines) ) ) + if isinstance(obj.inlines, (list, tuple)) + else must_be( + "a list or tuple", option="inlines", obj=obj, id="admin.E103" + ) + ) def _check_inlines_item(self, obj, inline, label): """Check one inline model admin.""" try: - inline_label = inline.__module__ + "." + inline.__name__ + inline_label = f"{inline.__module__}.{inline.__name__}" except AttributeError: return [ checks.Error( - "'%s' must inherit from 'InlineModelAdmin'." % obj, + f"'{obj}' must inherit from 'InlineModelAdmin'.", obj=obj.__class__, id="admin.E104", ) @@ -856,7 +872,7 @@ def _check_inlines_item(self, obj, inline, label): if not _issubclass(inline, InlineModelAdmin): return [ checks.Error( - "'%s' must inherit from 'InlineModelAdmin'." % inline_label, + f"'{inline_label}' must inherit from 'InlineModelAdmin'.", obj=obj.__class__, id="admin.E104", ) @@ -864,14 +880,14 @@ def _check_inlines_item(self, obj, inline, label): elif not inline.model: return [ checks.Error( - "'%s' must have a 'model' attribute." % inline_label, + f"'{inline_label}' must have a 'model' attribute.", obj=obj.__class__, id="admin.E105", ) ] elif not _issubclass(inline.model, models.Model): return must_be( - "a Model", option="%s.model" % inline_label, obj=obj, id="admin.E106" + "a Model", option=f"{inline_label}.model", obj=obj, id="admin.E106" ) else: return inline(obj.model, obj.admin_site).check() @@ -879,22 +895,23 @@ def _check_inlines_item(self, obj, inline, label): def _check_list_display(self, obj): """Check that list_display only contains fields or usable attributes.""" - if not isinstance(obj.list_display, (list, tuple)): - return must_be( - "a list or tuple", option="list_display", obj=obj, id="admin.E107" - ) - else: - return list( + return ( + list( chain.from_iterable( - self._check_list_display_item(obj, item, "list_display[%d]" % index) + self._check_list_display_item( + obj, item, "list_display[%d]" % index + ) for index, item in enumerate(obj.list_display) ) ) + if isinstance(obj.list_display, (list, tuple)) + else must_be( + "a list or tuple", option="list_display", obj=obj, id="admin.E107" + ) + ) def _check_list_display_item(self, obj, item, label): - if callable(item): - return [] - elif hasattr(obj, item): + if callable(item) or hasattr(obj, item): return [] try: field = obj.model._meta.get_field(item) @@ -920,7 +937,7 @@ def _check_list_display_item(self, obj, item, label): if isinstance(field, models.ManyToManyField): return [ checks.Error( - "The value of '%s' must not be a ManyToManyField." % label, + f"The value of '{label}' must not be a ManyToManyField.", obj=obj.__class__, id="admin.E109", ) @@ -953,30 +970,33 @@ def _check_list_display_links(self, obj): return [] def _check_list_display_links_item(self, obj, field_name, label): - if field_name not in obj.list_display: - return [ + return ( + [ checks.Error( - "The value of '%s' refers to '%s', which is not defined in " - "'list_display'." % (label, field_name), + f"The value of '{label}' refers to '{field_name}', which is not defined in 'list_display'.", obj=obj.__class__, id="admin.E111", ) ] - else: - return [] + if field_name not in obj.list_display + else [] + ) def _check_list_filter(self, obj): - if not isinstance(obj.list_filter, (list, tuple)): - return must_be( - "a list or tuple", option="list_filter", obj=obj, id="admin.E112" - ) - else: - return list( + return ( + list( chain.from_iterable( - self._check_list_filter_item(obj, item, "list_filter[%d]" % index) + self._check_list_filter_item( + obj, item, "list_filter[%d]" % index + ) for index, item in enumerate(obj.list_filter) ) ) + if isinstance(obj.list_filter, (list, tuple)) + else must_be( + "a list or tuple", option="list_filter", obj=obj, id="admin.E112" + ) + ) def _check_list_filter_item(self, obj, item, label): """ @@ -994,12 +1014,10 @@ def _check_list_filter_item(self, obj, item, label): return must_inherit_from( parent="ListFilter", option=label, obj=obj, id="admin.E113" ) - # ... but not a FieldListFilter. elif issubclass(item, FieldListFilter): return [ checks.Error( - "The value of '%s' must not inherit from 'FieldListFilter'." - % label, + f"The value of '{label}' must not inherit from 'FieldListFilter'.", obj=obj.__class__, id="admin.E114", ) @@ -1009,15 +1027,16 @@ def _check_list_filter_item(self, obj, item, label): elif isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item - if not _issubclass(list_filter_class, FieldListFilter): - return must_inherit_from( + return ( + [] + if _issubclass(list_filter_class, FieldListFilter) + else must_inherit_from( parent="FieldListFilter", - option="%s[1]" % label, + option=f"{label}[1]", obj=obj, id="admin.E115", ) - else: - return [] + ) else: # item is option #1 field = item @@ -1040,46 +1059,45 @@ def _check_list_filter_item(self, obj, item, label): def _check_list_select_related(self, obj): """Check that list_select_related is a boolean, a list or a tuple.""" - if not isinstance(obj.list_select_related, (bool, list, tuple)): - return must_be( + return ( + [] + if isinstance(obj.list_select_related, (bool, list, tuple)) + else must_be( "a boolean, tuple or list", option="list_select_related", obj=obj, id="admin.E117", ) - else: - return [] + ) def _check_list_per_page(self, obj): """Check that list_per_page is an integer.""" - if not isinstance(obj.list_per_page, int): - return must_be( + return ( + [] + if isinstance(obj.list_per_page, int) + else must_be( "an integer", option="list_per_page", obj=obj, id="admin.E118" ) - else: - return [] + ) def _check_list_max_show_all(self, obj): """Check that list_max_show_all is an integer.""" - if not isinstance(obj.list_max_show_all, int): - return must_be( + return ( + [] + if isinstance(obj.list_max_show_all, int) + else must_be( "an integer", option="list_max_show_all", obj=obj, id="admin.E119" ) - else: - return [] + ) def _check_list_editable(self, obj): """Check that list_editable is a sequence of editable fields from list_display without first element.""" - if not isinstance(obj.list_editable, (list, tuple)): - return must_be( - "a list or tuple", option="list_editable", obj=obj, id="admin.E120" - ) - else: - return list( + return ( + list( chain.from_iterable( self._check_list_editable_item( obj, item, "list_editable[%d]" % index @@ -1087,6 +1105,11 @@ def _check_list_editable(self, obj): for index, item in enumerate(obj.list_editable) ) ) + if isinstance(obj.list_editable, (list, tuple)) + else must_be( + "a list or tuple", option="list_editable", obj=obj, id="admin.E120" + ) + ) def _check_list_editable_item(self, obj, field_name, label): try: @@ -1145,40 +1168,40 @@ def _check_list_editable_item(self, obj, field_name, label): def _check_search_fields(self, obj): """Check search_fields is a sequence.""" - if not isinstance(obj.search_fields, (list, tuple)): - return must_be( + return ( + [] + if isinstance(obj.search_fields, (list, tuple)) + else must_be( "a list or tuple", option="search_fields", obj=obj, id="admin.E126" ) - else: - return [] + ) def _check_date_hierarchy(self, obj): """Check that date_hierarchy refers to DateField or DateTimeField.""" if obj.date_hierarchy is None: return [] + try: + field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] + except (NotRelationField, FieldDoesNotExist): + return [ + checks.Error( + f"The value of 'date_hierarchy' refers to '{obj.date_hierarchy}', which does not refer to a Field.", + obj=obj.__class__, + id="admin.E127", + ) + ] else: - try: - field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] - except (NotRelationField, FieldDoesNotExist): - return [ - checks.Error( - "The value of 'date_hierarchy' refers to '%s', which " - "does not refer to a Field." % obj.date_hierarchy, - obj=obj.__class__, - id="admin.E127", - ) - ] - else: - if not isinstance(field, (models.DateField, models.DateTimeField)): - return must_be( - "a DateField or DateTimeField", - option="date_hierarchy", - obj=obj, - id="admin.E128", - ) - else: - return [] + return ( + [] + if isinstance(field, (models.DateField, models.DateTimeField)) + else must_be( + "a DateField or DateTimeField", + option="date_hierarchy", + obj=obj, + id="admin.E128", + ) + ) def _check_action_permission_methods(self, obj): """ @@ -1191,16 +1214,11 @@ def _check_action_permission_methods(self, obj): if not hasattr(func, "allowed_permissions"): continue for permission in func.allowed_permissions: - method_name = "has_%s_permission" % permission + method_name = f"has_{permission}_permission" if not hasattr(obj, method_name): errors.append( checks.Error( - "%s must define a %s() method for the %s action." - % ( - obj.__class__.__name__, - method_name, - func.__name__, - ), + f"{obj.__class__.__name__} must define a {method_name}() method for the {func.__name__} action.", obj=obj.__class__, id="admin.E129", ) @@ -1209,23 +1227,21 @@ def _check_action_permission_methods(self, obj): def _check_actions_uniqueness(self, obj): """Check that every action has a unique __name__.""" - errors = [] names = collections.Counter(name for _, name, _ in obj._get_base_actions()) - for name, count in names.items(): - if count > 1: - errors.append( - checks.Error( - "__name__ attributes of actions defined in %s must be " - "unique. Name %r is not unique." - % ( - obj.__class__.__name__, - name, - ), - obj=obj.__class__, - id="admin.E130", - ) - ) - return errors + return [ + checks.Error( + "__name__ attributes of actions defined in %s must be " + "unique. Name %r is not unique." + % ( + obj.__class__.__name__, + name, + ), + obj=obj.__class__, + id="admin.E130", + ) + for name, count in names.items() + if count > 1 + ] class InlineModelAdminChecks(BaseModelAdminChecks): @@ -1242,10 +1258,7 @@ def check(self, inline_obj, **kwargs): ] def _check_exclude_of_parent_model(self, obj, parent_model): - # Do not perform more specific checks if the base checks result in an - # error. - errors = super()._check_exclude(obj) - if errors: + if errors := super()._check_exclude(obj): return [] # Skip if `fk_name` is invalid. @@ -1259,12 +1272,7 @@ def _check_exclude_of_parent_model(self, obj, parent_model): if fk.name in obj.exclude: return [ checks.Error( - "Cannot exclude the field '%s', because it is the foreign key " - "to the parent model '%s'." - % ( - fk.name, - parent_model._meta.label, - ), + f"Cannot exclude the field '{fk.name}', because it is the foreign key to the parent model '{parent_model._meta.label}'.", obj=obj.__class__, id="admin.E201", ) @@ -1283,68 +1291,68 @@ def _check_relation(self, obj, parent_model): def _check_extra(self, obj): """Check that extra is an integer.""" - if not isinstance(obj.extra, int): - return must_be("an integer", option="extra", obj=obj, id="admin.E203") - else: - return [] + return ( + [] + if isinstance(obj.extra, int) + else must_be("an integer", option="extra", obj=obj, id="admin.E203") + ) def _check_max_num(self, obj): """Check that max_num is an integer.""" - if obj.max_num is None: + if obj.max_num is None or isinstance(obj.max_num, int): return [] - elif not isinstance(obj.max_num, int): - return must_be("an integer", option="max_num", obj=obj, id="admin.E204") else: - return [] + return must_be("an integer", option="max_num", obj=obj, id="admin.E204") def _check_min_num(self, obj): """Check that min_num is an integer.""" - if obj.min_num is None: + if obj.min_num is None or isinstance(obj.min_num, int): return [] - elif not isinstance(obj.min_num, int): - return must_be("an integer", option="min_num", obj=obj, id="admin.E205") else: - return [] + return must_be("an integer", option="min_num", obj=obj, id="admin.E205") def _check_formset(self, obj): """Check formset is a subclass of BaseModelFormSet.""" - if not _issubclass(obj.formset, BaseModelFormSet): - return must_inherit_from( - parent="BaseModelFormSet", option="formset", obj=obj, id="admin.E206" + return ( + [] + if _issubclass(obj.formset, BaseModelFormSet) + else must_inherit_from( + parent="BaseModelFormSet", + option="formset", + obj=obj, + id="admin.E206", ) - else: - return [] + ) def must_be(type, option, obj, id): return [ checks.Error( - "The value of '%s' must be %s." % (option, type), + f"The value of '{option}' must be {type}.", obj=obj.__class__, id=id, - ), + ) ] def must_inherit_from(parent, option, obj, id): return [ checks.Error( - "The value of '%s' must inherit from '%s'." % (option, parent), + f"The value of '{option}' must inherit from '{parent}'.", obj=obj.__class__, id=id, - ), + ) ] def refer_to_missing_field(field, option, obj, id): return [ checks.Error( - "The value of '%s' refers to '%s', which is not a field of '%s'." - % (option, field, obj.model._meta.label), + f"The value of '{option}' refers to '{field}', which is not a field of '{obj.model._meta.label}'.", obj=obj.__class__, id=id, - ), + ) ] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/decorators.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/decorators.py index d3ff56a5..2c5c894c 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/decorators.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/decorators.py @@ -25,10 +25,7 @@ def decorator(func): func.short_description = description return func - if function is None: - return decorator - else: - return decorator(function) + return decorator if function is None else decorator(function) def display( @@ -71,10 +68,7 @@ def decorator(func): func.empty_value_display = empty_value return func - if function is None: - return decorator - else: - return decorator(function) + return decorator if function is None else decorator(function) def register(*models, site=None): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/filters.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/filters.py index 01134646..89baeae5 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/filters.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/filters.py @@ -29,8 +29,7 @@ def __init__(self, request, params, model, model_admin): self.used_parameters = {} if self.title is None: raise ImproperlyConfigured( - "The list filter '%s' does not specify a 'title'." - % self.__class__.__name__ + f"The list filter '{self.__class__.__name__}' does not specify a 'title'." ) def has_output(self): @@ -77,8 +76,7 @@ def __init__(self, request, params, model, model_admin): super().__init__(request, params, model, model_admin) if self.parameter_name is None: raise ImproperlyConfigured( - "The list filter '%s' does not specify a 'parameter_name'." - % self.__class__.__name__ + f"The list filter '{self.__class__.__name__}' does not specify a 'parameter_name'." ) if self.parameter_name in params: value = params.pop(self.parameter_name) @@ -177,8 +175,8 @@ def create(cls, field, request, params, model, model_admin, field_path): class RelatedFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): other_model = get_model_from_relation(field) - self.lookup_kwarg = "%s__%s__exact" % (field_path, field.target_field.name) - self.lookup_kwarg_isnull = "%s__isnull" % field_path + self.lookup_kwarg = f"{field_path}__{field.target_field.name}__exact" + self.lookup_kwarg_isnull = f"{field_path}__isnull" self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = params.get(self.lookup_kwarg_isnull) super().__init__(field, request, params, model, model_admin, field_path) @@ -199,10 +197,7 @@ def include_empty_choice(self): return self.field.null or (self.field.is_relation and self.field.many_to_many) def has_output(self): - if self.include_empty_choice: - extra = 1 - else: - extra = 0 + extra = 1 if self.include_empty_choice else 0 return len(self.lookup_choices) + extra > 1 def expected_parameters(self): @@ -213,9 +208,7 @@ def field_admin_ordering(self, field, request, model_admin): Return the model admin's ordering for related field, if provided. """ related_admin = model_admin.admin_site._registry.get(field.remote_field.model) - if related_admin is not None: - return related_admin.get_ordering(request) - return () + return related_admin.get_ordering(request) if related_admin is not None else () def field_choices(self, field, request, model_admin): ordering = self.field_admin_ordering(field, request, model_admin) @@ -252,8 +245,8 @@ def choices(self, changelist): class BooleanFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): - self.lookup_kwarg = "%s__exact" % field_path - self.lookup_kwarg2 = "%s__isnull" % field_path + self.lookup_kwarg = f"{field_path}__exact" + self.lookup_kwarg2 = f"{field_path}__isnull" self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val2 = params.get(self.lookup_kwarg2) super().__init__(field, request, params, model, model_admin, field_path) @@ -300,8 +293,8 @@ def choices(self, changelist): class ChoicesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): - self.lookup_kwarg = "%s__exact" % field_path - self.lookup_kwarg_isnull = "%s__isnull" % field_path + self.lookup_kwarg = f"{field_path}__exact" + self.lookup_kwarg_isnull = f"{field_path}__isnull" self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = params.get(self.lookup_kwarg_isnull) super().__init__(field, request, params, model, model_admin, field_path) @@ -344,7 +337,7 @@ def choices(self, changelist): class DateFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): - self.field_generic = "%s__" % field_path + self.field_generic = f"{field_path}__" self.date_params = { k: v for k, v in params.items() if k.startswith(self.field_generic) } @@ -366,8 +359,8 @@ def __init__(self, field, request, params, model, model_admin, field_path): next_month = today.replace(month=today.month + 1, day=1) next_year = today.replace(year=today.year + 1, month=1, day=1) - self.lookup_kwarg_since = "%s__gte" % field_path - self.lookup_kwarg_until = "%s__lt" % field_path + self.lookup_kwarg_since = f"{field_path}__gte" + self.lookup_kwarg_until = f"{field_path}__lt" self.links = ( (_("Any date"), {}), ( @@ -400,10 +393,10 @@ def __init__(self, field, request, params, model, model_admin, field_path): ), ) if field.null: - self.lookup_kwarg_isnull = "%s__isnull" % field_path + self.lookup_kwarg_isnull = f"{field_path}__isnull" self.links += ( - (_("No date"), {self.field_generic + "isnull": "True"}), - (_("Has date"), {self.field_generic + "isnull": "False"}), + (_("No date"), {f"{self.field_generic}isnull": "True"}), + (_("Has date"), {f"{self.field_generic}isnull": "False"}), ) super().__init__(field, request, params, model, model_admin, field_path) @@ -433,7 +426,7 @@ def choices(self, changelist): class AllValuesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = field_path - self.lookup_kwarg_isnull = "%s__isnull" % field_path + self.lookup_kwarg_isnull = f"{field_path}__isnull" self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = params.get(self.lookup_kwarg_isnull) self.empty_value_display = model_admin.get_empty_value_display() @@ -490,7 +483,7 @@ def field_choices(self, field, request, model_admin): pk_qs = ( model_admin.get_queryset(request) .distinct() - .values_list("%s__pk" % self.field_path, flat=True) + .values_list(f"{self.field_path}__pk", flat=True) ) ordering = self.field_admin_ordering(field, request, model_admin) return field.get_choices( @@ -509,7 +502,7 @@ def __init__(self, field, request, params, model, model_admin, field_path): field.name, ) ) - self.lookup_kwarg = "%s__isempty" % field_path + self.lookup_kwarg = f"{field_path}__isempty" self.lookup_val = params.get(self.lookup_kwarg) super().__init__(field, request, params, model, model_admin, field_path) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/helpers.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/helpers.py index 2e7a20a4..5076c432 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/helpers.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/helpers.py @@ -239,10 +239,7 @@ def label_tag(self): ) def get_admin_url(self, remote_field, remote_obj): - url_name = "admin:%s_%s_change" % ( - remote_field.model._meta.app_label, - remote_field.model._meta.model_name, - ) + url_name = f"admin:{remote_field.model._meta.app_label}_{remote_field.model._meta.model_name}_change" try: url = reverse( url_name, @@ -276,10 +273,7 @@ def contents(self): if getattr(attr, "boolean", False): result_repr = _boolean_icon(value) else: - if hasattr(value, "__html__"): - result_repr = value - else: - result_repr = linebreaksbr(value) + result_repr = value if hasattr(value, "__html__") else linebreaksbr(value) else: if isinstance(f.remote_field, ManyToManyRel) and value is not None: result_repr = ", ".join(map(str, value.all())) @@ -417,7 +411,7 @@ def inline_formset_data(self): verbose_name = self.opts.verbose_name return json.dumps( { - "name": "#%s" % self.formset.prefix, + "name": f"#{self.formset.prefix}", "options": { "prefix": self.formset.prefix, "addText": gettext("Add another %(verbose_name)s") @@ -500,8 +494,7 @@ def pk_field(self): return AdminField(self.form, self.formset._pk_field.name, False) def fk_field(self): - fk = getattr(self.formset, "fk", None) - if fk: + if fk := getattr(self.formset, "fk", None): return AdminField(self.form, fk.name, False) else: return "" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/models.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/models.py index 7ff04102..07a2122b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/models.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/models.py @@ -111,64 +111,63 @@ def get_change_message(self): If self.change_message is a JSON structure, interpret it as a change string, properly translated. """ - if self.change_message and self.change_message[0] == "[": - try: - change_message = json.loads(self.change_message) - except json.JSONDecodeError: - return self.change_message - messages = [] - for sub_message in change_message: - if "added" in sub_message: - if sub_message["added"]: - sub_message["added"]["name"] = gettext( - sub_message["added"]["name"] - ) - messages.append( - gettext("Added {name} “{object}”.").format( - **sub_message["added"] - ) - ) - else: - messages.append(gettext("Added.")) - - elif "changed" in sub_message: - sub_message["changed"]["fields"] = get_text_list( - [ - gettext(field_name) - for field_name in sub_message["changed"]["fields"] - ], - gettext("and"), + if not self.change_message or self.change_message[0] != "[": + return self.change_message + try: + change_message = json.loads(self.change_message) + except json.JSONDecodeError: + return self.change_message + messages = [] + for sub_message in change_message: + if "added" in sub_message: + if sub_message["added"]: + sub_message["added"]["name"] = gettext( + sub_message["added"]["name"] ) - if "name" in sub_message["changed"]: - sub_message["changed"]["name"] = gettext( - sub_message["changed"]["name"] - ) - messages.append( - gettext("Changed {fields} for {name} “{object}”.").format( - **sub_message["changed"] - ) + messages.append( + gettext("Added {name} “{object}”.").format( + **sub_message["added"] ) - else: - messages.append( - gettext("Changed {fields}.").format( - **sub_message["changed"] - ) + ) + else: + messages.append(gettext("Added.")) + + elif "changed" in sub_message: + sub_message["changed"]["fields"] = get_text_list( + [ + gettext(field_name) + for field_name in sub_message["changed"]["fields"] + ], + gettext("and"), + ) + if "name" in sub_message["changed"]: + sub_message["changed"]["name"] = gettext( + sub_message["changed"]["name"] + ) + messages.append( + gettext("Changed {fields} for {name} “{object}”.").format( + **sub_message["changed"] ) - - elif "deleted" in sub_message: - sub_message["deleted"]["name"] = gettext( - sub_message["deleted"]["name"] ) + else: messages.append( - gettext("Deleted {name} “{object}”.").format( - **sub_message["deleted"] + gettext("Changed {fields}.").format( + **sub_message["changed"] ) ) - change_message = " ".join(msg[0].upper() + msg[1:] for msg in messages) - return change_message or gettext("No fields changed.") - else: - return self.change_message + elif "deleted" in sub_message: + sub_message["deleted"]["name"] = gettext( + sub_message["deleted"]["name"] + ) + messages.append( + gettext("Deleted {name} “{object}”.").format( + **sub_message["deleted"] + ) + ) + + change_message = " ".join(msg[0].upper() + msg[1:] for msg in messages) + return change_message or gettext("No fields changed.") def get_edited_object(self): """Return the edited object represented by this log entry.""" @@ -179,10 +178,7 @@ def get_admin_url(self): Return the admin URL to edit the object represented by this log entry. """ if self.content_type and self.object_id: - url_name = "admin:%s_%s_change" % ( - self.content_type.app_label, - self.content_type.model, - ) + url_name = f"admin:{self.content_type.app_label}_{self.content_type.model}_change" try: return reverse(url_name, args=(quote(self.object_id),)) except NoReverseMatch: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/options.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/options.py index 20e6b3a6..ec26bb6f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/options.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/options.py @@ -376,9 +376,7 @@ def get_fieldsets(self, request, obj=None): """ Hook for specifying fieldsets. """ - if self.fieldsets: - return self.fieldsets - return [(None, {"fields": self.get_fields(request, obj)})] + return self.fieldsets or [(None, {"fields": self.get_fields(request, obj)})] def get_inlines(self, request, obj): """Hook for specifying custom inlines.""" @@ -408,9 +406,7 @@ def get_queryset(self, request): admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() - # TODO: this should be handled by some parameter to the ChangeList. - ordering = self.get_ordering(request) - if ordering: + if ordering := self.get_ordering(request): qs = qs.order_by(*ordering) return qs @@ -537,7 +533,7 @@ def has_add_permission(self, request): """ opts = self.opts codename = get_permission_codename("add", opts) - return request.user.has_perm("%s.%s" % (opts.app_label, codename)) + return request.user.has_perm(f"{opts.app_label}.{codename}") def has_change_permission(self, request, obj=None): """ @@ -552,7 +548,7 @@ def has_change_permission(self, request, obj=None): """ opts = self.opts codename = get_permission_codename("change", opts) - return request.user.has_perm("%s.%s" % (opts.app_label, codename)) + return request.user.has_perm(f"{opts.app_label}.{codename}") def has_delete_permission(self, request, obj=None): """ @@ -567,7 +563,7 @@ def has_delete_permission(self, request, obj=None): """ opts = self.opts codename = get_permission_codename("delete", opts) - return request.user.has_perm("%s.%s" % (opts.app_label, codename)) + return request.user.has_perm(f"{opts.app_label}.{codename}") def has_view_permission(self, request, obj=None): """ @@ -584,8 +580,8 @@ def has_view_permission(self, request, obj=None): codename_view = get_permission_codename("view", opts) codename_change = get_permission_codename("change", opts) return request.user.has_perm( - "%s.%s" % (opts.app_label, codename_view) - ) or request.user.has_perm("%s.%s" % (opts.app_label, codename_change)) + f"{opts.app_label}.{codename_view}" + ) or request.user.has_perm(f"{opts.app_label}.{codename_change}") def has_view_or_change_permission(self, request, obj=None): return self.has_view_permission(request, obj) or self.has_change_permission( @@ -650,7 +646,7 @@ def __init__(self, model, admin_site): super().__init__() def __str__(self): - return "%s.%s" % (self.model._meta.app_label, self.__class__.__name__) + return f"{self.model._meta.app_label}.{self.__class__.__name__}" def __repr__(self): return ( @@ -725,16 +721,16 @@ def urls(self): def media(self): extra = "" if settings.DEBUG else ".min" js = [ - "vendor/jquery/jquery%s.js" % extra, + f"vendor/jquery/jquery{extra}.js", "jquery.init.js", "core.js", "admin/RelatedObjectLookups.js", "actions.js", "urlify.js", "prepopulate.js", - "vendor/xregexp/xregexp%s.js" % extra, + f"vendor/xregexp/xregexp{extra}.js", ] - return forms.Media(js=["admin/js/%s" % url for url in js]) + return forms.Media(js=[f"admin/js/{url}" for url in js]) def get_model_perms(self, request): """ @@ -804,8 +800,7 @@ def get_form(self, request, obj=None, change=False, **kwargs): return modelform_factory(self.model, **defaults) except FieldError as e: raise FieldError( - "%s. Check fields/fieldsets/exclude attributes of class %s." - % (e, self.__class__.__name__) + f"{e}. Check fields/fieldsets/exclude attributes of class {self.__class__.__name__}." ) def get_changelist(self, request, **kwargs): @@ -995,7 +990,7 @@ def _filter_actions_by_permissions(self, request, actions): filtered_actions.append(action) continue permission_checks = ( - getattr(self, "has_%s_permission" % permission) + getattr(self, f"has_{permission}_permission") for permission in callable.allowed_permissions ) if any(has_permission(request) for has_permission in permission_checks): @@ -1104,11 +1099,11 @@ def get_search_results(self, request, queryset, search_term): # Apply keyword searches. def construct_search(field_name): if field_name.startswith("^"): - return "%s__istartswith" % field_name[1:] + return f"{field_name[1:]}__istartswith" elif field_name.startswith("="): - return "%s__iexact" % field_name[1:] + return f"{field_name[1:]}__iexact" elif field_name.startswith("@"): - return "%s__search" % field_name[1:] + return f"{field_name[1:]}__search" # Use field_name if it includes a lookup. opts = queryset.model._meta lookup_fields = field_name.split(LOOKUP_SEP) @@ -1129,7 +1124,7 @@ def construct_search(field_name): # Update opts to follow the relation. opts = field.get_path_info()[-1].to_opts # Otherwise, use the field with icontains. - return "%s__icontains" % field_name + return f"{field_name}__icontains" may_have_duplicates = False search_fields = self.get_search_fields(request) @@ -1158,11 +1153,8 @@ def get_preserved_filters(self, request): match = request.resolver_match if self.preserve_filters and match: opts = self.model._meta - current_url = "%s:%s" % (match.app_name, match.url_name) - changelist_url = "admin:%s_%s_changelist" % ( - opts.app_label, - opts.model_name, - ) + current_url = f"{match.app_name}:{match.url_name}" + changelist_url = f"admin:{opts.app_label}_{opts.model_name}_changelist" if current_url == changelist_url: preserved_filters = request.GET.urlencode() else: @@ -1196,10 +1188,9 @@ def message_user( level = getattr(messages.constants, level.upper()) except AttributeError: levels = messages.constants.DEFAULT_TAGS.values() - levels_repr = ", ".join("`%s`" % level for level in levels) + levels_repr = ", ".join(f"`{level}`" for level in levels) raise ValueError( - "Bad message level string: `%s`. Possible values are: %s" - % (level, levels_repr) + f"Bad message level string: `{level}`. Possible values are: {levels_repr}" ) messages.add_message( @@ -1257,15 +1248,14 @@ def render_change_form( {"preserved_filters": preserved_filters, "opts": opts}, form_url ) view_on_site_url = self.get_view_on_site_url(obj) - has_editable_inline_admin_formsets = False - for inline in context["inline_admin_formsets"]: - if ( + has_editable_inline_admin_formsets = any( + ( inline.has_add_permission or inline.has_change_permission or inline.has_delete_permission - ): - has_editable_inline_admin_formsets = True - break + ) + for inline in context["inline_admin_formsets"] + ) context.update( { "add": add, @@ -1305,8 +1295,8 @@ def render_change_form( request, form_template or [ - "admin/%s/%s/change_form.html" % (app_label, opts.model_name), - "admin/%s/change_form.html" % app_label, + f"admin/{app_label}/{opts.model_name}/change_form.html", + f"admin/{app_label}/change_form.html", "admin/change_form.html", ], context, @@ -1319,7 +1309,7 @@ def response_add(self, request, obj, post_url_continue=None): opts = obj._meta preserved_filters = self.get_preserved_filters(request) obj_url = reverse( - "admin:%s_%s_change" % (opts.app_label, opts.model_name), + f"admin:{opts.app_label}_{opts.model_name}_change", args=(quote(obj.pk),), current_app=self.admin_site.name, ) @@ -1336,8 +1326,7 @@ def response_add(self, request, obj, post_url_continue=None): # the presence of keys in request.POST. if IS_POPUP_VAR in request.POST: - to_field = request.POST.get(TO_FIELD_VAR) - if to_field: + if to_field := request.POST.get(TO_FIELD_VAR): attr = str(to_field) else: attr = obj._meta.pk.attname @@ -1352,9 +1341,8 @@ def response_add(self, request, obj, post_url_continue=None): request, self.popup_response_template or [ - "admin/%s/%s/popup_response.html" - % (opts.app_label, opts.model_name), - "admin/%s/popup_response.html" % opts.app_label, + f"admin/{opts.app_label}/{opts.model_name}/popup_response.html", + f"admin/{opts.app_label}/popup_response.html", "admin/popup_response.html", ], { @@ -1425,9 +1413,8 @@ def response_change(self, request, obj): request, self.popup_response_template or [ - "admin/%s/%s/popup_response.html" - % (opts.app_label, opts.model_name), - "admin/%s/popup_response.html" % opts.app_label, + f"admin/{opts.app_label}/{opts.model_name}/popup_response.html", + f"admin/{opts.app_label}/popup_response.html", "admin/popup_response.html", ], { @@ -1467,7 +1454,7 @@ def response_change(self, request, obj): ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( - "admin:%s_%s_change" % (opts.app_label, opts.model_name), + f"admin:{opts.app_label}_{opts.model_name}_change", args=(obj.pk,), current_app=self.admin_site.name, ) @@ -1486,7 +1473,7 @@ def response_change(self, request, obj): ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( - "admin:%s_%s_add" % (opts.app_label, opts.model_name), + f"admin:{opts.app_label}_{opts.model_name}_add", current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( @@ -1505,7 +1492,7 @@ def _response_post_save(self, request, obj): opts = self.model._meta if self.has_view_or_change_permission(request): post_url = reverse( - "admin:%s_%s_changelist" % (opts.app_label, opts.model_name), + f"admin:{opts.app_label}_{opts.model_name}_changelist", current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) @@ -1616,9 +1603,8 @@ def response_delete(self, request, obj_display, obj_id): request, self.popup_response_template or [ - "admin/%s/%s/popup_response.html" - % (opts.app_label, opts.model_name), - "admin/%s/popup_response.html" % opts.app_label, + f"admin/{opts.app_label}/{opts.model_name}/popup_response.html", + f"admin/{opts.app_label}/popup_response.html", "admin/popup_response.html", ], { @@ -1638,7 +1624,7 @@ def response_delete(self, request, obj_display, obj_id): if self.has_change_permission(request, None): post_url = reverse( - "admin:%s_%s_changelist" % (opts.app_label, opts.model_name), + f"admin:{opts.app_label}_{opts.model_name}_changelist", current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) @@ -1664,10 +1650,8 @@ def render_delete_form(self, request, context): request, self.delete_confirmation_template or [ - "admin/{}/{}/delete_confirmation.html".format( - app_label, opts.model_name - ), - "admin/{}/delete_confirmation.html".format(app_label), + f"admin/{app_label}/{opts.model_name}/delete_confirmation.html", + f"admin/{app_label}/delete_confirmation.html", "admin/delete_confirmation.html", ], context, @@ -1748,7 +1732,7 @@ def _changeform_view(self, request, object_id, form_url, extra_context): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( - "The field %s cannot be referenced." % to_field + f"The field {to_field} cannot be referenced." ) model = self.model @@ -1767,13 +1751,13 @@ def _changeform_view(self, request, object_id, form_url, extra_context): else: obj = self.get_object(request, unquote(object_id), to_field) - if request.method == "POST": - if not self.has_change_permission(request, obj): - raise PermissionDenied - else: - if not self.has_view_or_change_permission(request, obj): - raise PermissionDenied - + if ( + request.method == "POST" + and not self.has_change_permission(request, obj) + or request.method != "POST" + and not self.has_view_or_change_permission(request, obj) + ): + raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(request, opts, object_id) @@ -1789,10 +1773,11 @@ def _changeform_view(self, request, object_id, form_url, extra_context): change=not add, ) form_validated = form.is_valid() - if form_validated: - new_object = self.save_form(request, form, change=not add) - else: - new_object = form.instance + new_object = ( + self.save_form(request, form, change=not add) + if form_validated + else form.instance + ) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, not add) self.save_related(request, form, formsets, not add) @@ -1807,18 +1792,17 @@ def _changeform_view(self, request, object_id, form_url, extra_context): return self.response_change(request, new_object) else: form_validated = False + elif add: + initial = self.get_changeform_initial_data(request) + form = ModelForm(initial=initial) + formsets, inline_instances = self._create_formsets( + request, form.instance, change=False + ) else: - if add: - initial = self.get_changeform_initial_data(request) - form = ModelForm(initial=initial) - formsets, inline_instances = self._create_formsets( - request, form.instance, change=False - ) - else: - form = ModelForm(instance=obj) - formsets, inline_instances = self._create_formsets( - request, obj, change=True - ) + form = ModelForm(instance=obj) + formsets, inline_instances = self._create_formsets( + request, obj, change=True + ) if not add and not self.has_change_permission(request, obj): readonly_fields = flatten_fieldsets(fieldsets) @@ -1875,7 +1859,7 @@ def _changeform_view(self, request, object_id, form_url, extra_context): # Use the change template instead of the add template. add = False - context.update(extra_context or {}) + context |= (extra_context or {}) return self.render_change_form( request, context, add=add, change=not add, obj=obj, form_url=form_url @@ -1889,9 +1873,7 @@ def change_view(self, request, object_id, form_url="", extra_context=None): def _get_edited_object_pks(self, request, prefix): """Return POST data values of list_editable primary keys.""" - pk_pattern = re.compile( - r"{}-\d+-{}$".format(re.escape(prefix), self.model._meta.pk.name) - ) + pk_pattern = re.compile(f"{re.escape(prefix)}-\d+-{self.model._meta.pk.name}$") return [value for key, value in request.POST.items() if pk_pattern.match(key)] def _get_list_editable_queryset(self, request, prefix): @@ -1938,7 +1920,7 @@ def changelist_view(self, request, extra_context=None): "title": _("Database error"), }, ) - return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1") + return HttpResponseRedirect(f"{request.path}?{ERROR_FLAG}=1") # If the request was POSTed, this might be a bulk action or a bulk # edit. Try to look up an action or confirmation first, but if this @@ -1956,10 +1938,9 @@ def changelist_view(self, request, extra_context=None): and "_save" not in request.POST ): if selected: - response = self.response_action( + if response := self.response_action( request, queryset=cl.get_queryset(request) - ) - if response: + ): return response else: action_failed = True @@ -1978,15 +1959,13 @@ def changelist_view(self, request, extra_context=None): and helpers.ACTION_CHECKBOX_NAME in request.POST and "index" not in request.POST and "_save" not in request.POST - ): - if selected: - response = self.response_action( - request, queryset=cl.get_queryset(request) - ) - if response: - return response - else: - action_failed = True + ) and selected: + if response := self.response_action( + request, queryset=cl.get_queryset(request) + ): + return response + else: + action_failed = True if action_failed: # Redirect back to the changelist page to avoid resubmitting the @@ -2040,11 +2019,7 @@ def changelist_view(self, request, extra_context=None): formset = cl.formset = FormSet(queryset=cl.result_list) # Build the list of media to be used by the formset. - if formset: - media = self.media + formset.media - else: - media = self.media - + media = self.media + formset.media if formset else self.media # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) @@ -2084,8 +2059,8 @@ def changelist_view(self, request, extra_context=None): request, self.change_list_template or [ - "admin/%s/%s/change_list.html" % (app_label, opts.model_name), - "admin/%s/change_list.html" % app_label, + f"admin/{app_label}/{opts.model_name}/change_list.html", + f"admin/{app_label}/change_list.html", "admin/change_list.html", ], context, @@ -2111,7 +2086,7 @@ def _delete_view(self, request, object_id, extra_context): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( - "The field %s cannot be referenced." % to_field + f"The field {to_field} cannot be referenced." ) obj = self.get_object(request, unquote(object_id), to_field) @@ -2214,8 +2189,8 @@ def history_view(self, request, object_id, extra_context=None): request, self.object_history_template or [ - "admin/%s/%s/object_history.html" % (app_label, opts.model_name), - "admin/%s/object_history.html" % app_label, + f"admin/{app_label}/{opts.model_name}/object_history.html", + f"admin/{app_label}/object_history.html", "admin/object_history.html", ], context, @@ -2228,13 +2203,11 @@ def get_formset_kwargs(self, request, obj, inline, prefix): "queryset": inline.get_queryset(request), } if request.method == "POST": - formset_params.update( - { - "data": request.POST.copy(), - "files": request.FILES, - "save_as_new": "_saveasnew" in request.POST, - } - ) + formset_params |= { + "data": request.POST.copy(), + "files": request.FILES, + "save_as_new": "_saveasnew" in request.POST, + } return formset_params def _create_formsets(self, request, obj, change): @@ -2249,7 +2222,7 @@ def _create_formsets(self, request, obj, change): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1 or not prefix: - prefix = "%s-%s" % (prefix, prefixes[prefix]) + prefix = f"{prefix}-{prefixes[prefix]}" formset_params = self.get_formset_kwargs(request, obj, inline, prefix) formset = FormSet(**formset_params) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/sites.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/sites.py index ae166cee..f6060642 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/sites.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/sites.py @@ -117,13 +117,12 @@ def register(self, model_or_iterable, admin_class=None, **options): for model in model_or_iterable: if model._meta.abstract: raise ImproperlyConfigured( - "The model %s is abstract, so it cannot be registered with admin." - % model.__name__ + f"The model {model.__name__} is abstract, so it cannot be registered with admin." ) if model in self._registry: registered_admin = str(self._registry[model]) - msg = "The model %s is already registered " % model.__name__ + msg = f"The model {model.__name__} is already registered " if registered_admin.endswith(".ModelAdmin"): # Most likely registered without a ModelAdmin subclass. msg += "in app %r." % re.sub(r"\.ModelAdmin$", "", registered_admin) @@ -141,9 +140,7 @@ def register(self, model_or_iterable, admin_class=None, **options): # the created class appears to "live" in the wrong place, # which causes issues later on. options["__module__"] = __name__ - admin_class = type( - "%sAdmin" % model.__name__, (admin_class,), options - ) + admin_class = type(f"{model.__name__}Admin", (admin_class,), options) # Instantiate the admin class to save in the registry self._registry[model] = admin_class(model, self) @@ -158,7 +155,7 @@ def unregister(self, model_or_iterable): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: - raise NotRegistered("The model %s is not registered" % model.__name__) + raise NotRegistered(f"The model {model.__name__} is not registered") del self._registry[model] def is_registered(self, model): @@ -293,9 +290,9 @@ def wrapper(*args, **kwargs): for model, model_admin in self._registry.items(): urlpatterns += [ path( - "%s/%s/" % (model._meta.app_label, model._meta.model_name), + f"{model._meta.app_label}/{model._meta.model_name}/", include(model_admin.urls), - ), + ) ] if model._meta.app_label not in valid_app_labels: valid_app_labels.append(model._meta.app_label) @@ -429,7 +426,7 @@ def login(self, request, extra_context=None): and REDIRECT_FIELD_NAME not in request.POST ): context[REDIRECT_FIELD_NAME] = reverse("admin:index", current_app=self.name) - context.update(extra_context or {}) + context |= (extra_context or {}) defaults = { "extra_context": context, @@ -447,12 +444,12 @@ def catch_all_view(self, request, url): if settings.APPEND_SLASH and not url.endswith("/"): urlconf = getattr(request, "urlconf", None) try: - match = resolve("%s/" % request.path_info, urlconf) + match = resolve(f"{request.path_info}/", urlconf) except Resolver404: pass else: if getattr(match.func, "should_append_slash", True): - return HttpResponsePermanentRedirect("%s/" % request.path) + return HttpResponsePermanentRedirect(f"{request.path}/") raise Http404 def _build_app_dict(self, request, label=None): @@ -525,9 +522,7 @@ def _build_app_dict(self, request, label=None): "models": [model_dict], } - if label: - return app_dict.get(label) - return app_dict + return app_dict.get(label) if label else app_dict def get_app_list(self, request): """ @@ -586,7 +581,7 @@ def app_index(self, request, app_label, extra_context=None): return TemplateResponse( request, self.app_index_template - or ["admin/%s/app_index.html" % app_label, "admin/app_index.html"], + or [f"admin/{app_label}/app_index.html", "admin/app_index.html"], context, ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_list.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_list.py index 5865843d..95e4c97d 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_list.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_list.py @@ -130,7 +130,7 @@ def result_headers(cl): if is_sorted: order_type = ordering_field_columns.get(i).lower() sort_priority = list(ordering_field_columns).index(i) + 1 - th_classes.append("sorted %sending" % order_type) + th_classes.append(f"sorted {order_type}ending") new_order_type = {"asc": "desc", "desc": "asc"}[order_type] # build new ordering param @@ -186,7 +186,7 @@ def _coerce_field_name(field_name, field_index): """ if callable(field_name): if field_name.__name__ == "": - return "lambda" + str(field_index) + return f"lambda{str(field_index)}" else: return field_name.__name__ return field_name @@ -208,7 +208,7 @@ def link_in_col(is_first, field_name, cl): pk = cl.lookup_opts.pk.attname for field_index, field_name in enumerate(cl.list_display): empty_value_display = cl.model_admin.get_empty_value_display() - row_classes = ["field-%s" % _coerce_field_name(field_name, field_index)] + row_classes = [f"field-{_coerce_field_name(field_name, field_index)}"] try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except ObjectDoesNotExist: @@ -227,17 +227,14 @@ def link_in_col(is_first, field_name, cl): else: if isinstance(f.remote_field, models.ManyToOneRel): field_val = getattr(result, f.name) - if field_val is None: - result_repr = empty_value_display - else: - result_repr = field_val + result_repr = empty_value_display if field_val is None else field_val else: result_repr = display_for_field(value, f, empty_value_display) if isinstance( f, (models.DateField, models.TimeField, models.ForeignKey) ): row_classes.append("nowrap") - row_class = mark_safe(' class="%s"' % " ".join(row_classes)) + row_class = mark_safe(f' class="{" ".join(row_classes)}"') # If list_display_links not defined, add the link tag to the first field if link_in_col(first, field_name, cl): table_tag = "th" if first else "td" @@ -255,10 +252,7 @@ def link_in_col(is_first, field_name, cl): ) # Convert the pk to something that can be used in JavaScript. # Problem cases are non-ASCII strings. - if cl.to_field: - attr = str(cl.to_field) - else: - attr = pk + attr = str(cl.to_field) if cl.to_field else pk value = result.serializable_value(attr) link_or_text = format_html( '{}', @@ -324,10 +318,7 @@ def result_list(cl): Display the headers and data list together. """ headers = list(result_headers(cl)) - num_sorted_fields = 0 - for h in headers: - if h["sortable"] and h["sorted"]: - num_sorted_fields += 1 + num_sorted_fields = sum(1 for h in headers if h["sortable"] and h["sorted"]) return { "cl": cl, "result_hidden_fields": list(result_hidden_fields(cl)), @@ -352,112 +343,113 @@ def date_hierarchy(cl): """ Display the date hierarchy for date drill-down functionality. """ - if cl.date_hierarchy: - field_name = cl.date_hierarchy - field = get_fields_from_path(cl.model, field_name)[-1] - if isinstance(field, models.DateTimeField): - dates_or_datetimes = "datetimes" - qs_kwargs = {"is_dst": True} if settings.USE_DEPRECATED_PYTZ else {} - else: - dates_or_datetimes = "dates" - qs_kwargs = {} - year_field = "%s__year" % field_name - month_field = "%s__month" % field_name - day_field = "%s__day" % field_name - field_generic = "%s__" % field_name - year_lookup = cl.params.get(year_field) - month_lookup = cl.params.get(month_field) - day_lookup = cl.params.get(day_field) - - def link(filters): - return cl.get_query_string(filters, [field_generic]) - - if not (year_lookup or month_lookup or day_lookup): - # select appropriate start level - date_range = cl.queryset.aggregate( - first=models.Min(field_name), last=models.Max(field_name) - ) - if date_range["first"] and date_range["last"]: - if dates_or_datetimes == "datetimes": - date_range = { - k: timezone.localtime(v) if timezone.is_aware(v) else v - for k, v in date_range.items() - } - if date_range["first"].year == date_range["last"].year: - year_lookup = date_range["first"].year - if date_range["first"].month == date_range["last"].month: - month_lookup = date_range["first"].month - - if year_lookup and month_lookup and day_lookup: - day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup)) - return { - "show": True, - "back": { - "link": link({year_field: year_lookup, month_field: month_lookup}), - "title": capfirst(formats.date_format(day, "YEAR_MONTH_FORMAT")), - }, - "choices": [ - {"title": capfirst(formats.date_format(day, "MONTH_DAY_FORMAT"))} - ], - } - elif year_lookup and month_lookup: - days = getattr(cl.queryset, dates_or_datetimes)( - field_name, "day", **qs_kwargs - ) - return { - "show": True, - "back": { - "link": link({year_field: year_lookup}), - "title": str(year_lookup), - }, - "choices": [ - { - "link": link( - { - year_field: year_lookup, - month_field: month_lookup, - day_field: day.day, - } - ), - "title": capfirst(formats.date_format(day, "MONTH_DAY_FORMAT")), - } - for day in days - ], - } - elif year_lookup: - months = getattr(cl.queryset, dates_or_datetimes)( - field_name, "month", **qs_kwargs - ) - return { - "show": True, - "back": {"link": link({}), "title": _("All dates")}, - "choices": [ - { - "link": link( - {year_field: year_lookup, month_field: month.month} - ), - "title": capfirst( - formats.date_format(month, "YEAR_MONTH_FORMAT") - ), - } - for month in months - ], - } - else: - years = getattr(cl.queryset, dates_or_datetimes)( - field_name, "year", **qs_kwargs - ) - return { - "show": True, - "back": None, - "choices": [ - { - "link": link({year_field: str(year.year)}), - "title": str(year.year), - } - for year in years - ], - } + if not cl.date_hierarchy: + return + field_name = cl.date_hierarchy + field = get_fields_from_path(cl.model, field_name)[-1] + if isinstance(field, models.DateTimeField): + dates_or_datetimes = "datetimes" + qs_kwargs = {"is_dst": True} if settings.USE_DEPRECATED_PYTZ else {} + else: + dates_or_datetimes = "dates" + qs_kwargs = {} + year_field = f"{field_name}__year" + month_field = f"{field_name}__month" + day_field = f"{field_name}__day" + field_generic = f"{field_name}__" + year_lookup = cl.params.get(year_field) + month_lookup = cl.params.get(month_field) + day_lookup = cl.params.get(day_field) + + def link(filters): + return cl.get_query_string(filters, [field_generic]) + + if not (year_lookup or month_lookup or day_lookup): + # select appropriate start level + date_range = cl.queryset.aggregate( + first=models.Min(field_name), last=models.Max(field_name) + ) + if date_range["first"] and date_range["last"]: + if dates_or_datetimes == "datetimes": + date_range = { + k: timezone.localtime(v) if timezone.is_aware(v) else v + for k, v in date_range.items() + } + if date_range["first"].year == date_range["last"].year: + year_lookup = date_range["first"].year + if date_range["first"].month == date_range["last"].month: + month_lookup = date_range["first"].month + + if year_lookup and month_lookup and day_lookup: + day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup)) + return { + "show": True, + "back": { + "link": link({year_field: year_lookup, month_field: month_lookup}), + "title": capfirst(formats.date_format(day, "YEAR_MONTH_FORMAT")), + }, + "choices": [ + {"title": capfirst(formats.date_format(day, "MONTH_DAY_FORMAT"))} + ], + } + elif year_lookup and month_lookup: + days = getattr(cl.queryset, dates_or_datetimes)( + field_name, "day", **qs_kwargs + ) + return { + "show": True, + "back": { + "link": link({year_field: year_lookup}), + "title": str(year_lookup), + }, + "choices": [ + { + "link": link( + { + year_field: year_lookup, + month_field: month_lookup, + day_field: day.day, + } + ), + "title": capfirst(formats.date_format(day, "MONTH_DAY_FORMAT")), + } + for day in days + ], + } + elif year_lookup: + months = getattr(cl.queryset, dates_or_datetimes)( + field_name, "month", **qs_kwargs + ) + return { + "show": True, + "back": {"link": link({}), "title": _("All dates")}, + "choices": [ + { + "link": link( + {year_field: year_lookup, month_field: month.month} + ), + "title": capfirst( + formats.date_format(month, "YEAR_MONTH_FORMAT") + ), + } + for month in months + ], + } + else: + years = getattr(cl.queryset, dates_or_datetimes)( + field_name, "year", **qs_kwargs + ) + return { + "show": True, + "back": None, + "choices": [ + { + "link": link({year_field: str(year.year)}), + "title": str(year.year), + } + for year in years + ], + } @register.tag(name="date_hierarchy") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_modify.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_modify.py index 9df4b7aa..bf8cd747 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_modify.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_modify.py @@ -22,23 +22,24 @@ def prepopulated_fields_js(context): if inline_admin_form.original is None: prepopulated_fields.extend(inline_admin_form.prepopulated_fields) - prepopulated_fields_json = [] - for field in prepopulated_fields: - prepopulated_fields_json.append( - { - "id": "#%s" % field["field"].auto_id, - "name": field["field"].name, - "dependency_ids": [ - "#%s" % dependency.auto_id for dependency in field["dependencies"] - ], - "dependency_list": [ - dependency.name for dependency in field["dependencies"] - ], - "maxLength": field["field"].field.max_length or 50, - "allowUnicode": getattr(field["field"].field, "allow_unicode", False), - } - ) - + prepopulated_fields_json = [ + { + "id": f'#{field["field"].auto_id}', + "name": field["field"].name, + "dependency_ids": [ + f"#{dependency.auto_id}" + for dependency in field["dependencies"] + ], + "dependency_list": [ + dependency.name for dependency in field["dependencies"] + ], + "maxLength": field["field"].field.max_length or 50, + "allowUnicode": getattr( + field["field"].field, "allow_unicode", False + ), + } + for field in prepopulated_fields + ] context.update( { "prepopulated_fields": prepopulated_fields, diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_urls.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_urls.py index 13ded033..a8ecf996 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_urls.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/admin_urls.py @@ -10,7 +10,7 @@ @register.filter def admin_urlname(value, arg): - return "admin:%s_%s_%s" % (value.app_label, value.model_name, arg) + return f"admin:{value.app_label}_{value.model_name}_{arg}" @register.filter @@ -30,17 +30,14 @@ def add_preserved_filters(context, url, popup=False, to_field=None): if opts and preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters)) - match_url = "/%s" % unquote(url).partition(get_script_prefix())[2] + match_url = f"/{unquote(url).partition(get_script_prefix())[2]}" try: match = resolve(match_url) except Resolver404: pass else: - current_url = "%s:%s" % (match.app_name, match.url_name) - changelist_url = "admin:%s_%s_changelist" % ( - opts.app_label, - opts.model_name, - ) + current_url = f"{match.app_name}:{match.url_name}" + changelist_url = f"admin:{opts.app_label}_{opts.model_name}_changelist" if ( changelist_url == current_url and "_changelist_filters" in preserved_filters @@ -49,7 +46,7 @@ def add_preserved_filters(context, url, popup=False, to_field=None): parse_qsl(preserved_filters["_changelist_filters"]) ) - merged_qs.update(preserved_filters) + merged_qs |= preserved_filters if popup: from django.contrib.admin.options import IS_POPUP_VAR @@ -60,7 +57,7 @@ def add_preserved_filters(context, url, popup=False, to_field=None): merged_qs[TO_FIELD_VAR] = to_field - merged_qs.update(parsed_qs) + merged_qs |= parsed_qs parsed_url[4] = urlencode(merged_qs) return urlunparse(parsed_url) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/base.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/base.py index 23e4cfbe..4832518e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/base.py @@ -37,9 +37,9 @@ def render(self, context): # thread-safe.) context.render_context[self] = context.template.engine.select_template( [ - "admin/%s/%s/%s" % (app_label, object_name, self.template_name), - "admin/%s/%s" % (app_label, self.template_name), - "admin/%s" % self.template_name, + f"admin/{app_label}/{object_name}/{self.template_name}", + f"admin/{app_label}/{self.template_name}", + f"admin/{self.template_name}", ] ) return super().render(context) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/log.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/log.py index 098aa640..b60809fd 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/log.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/templatetags/log.py @@ -57,11 +57,10 @@ def get_admin_log(parser, token): raise template.TemplateSyntaxError( "Second argument to 'get_admin_log' must be 'as'" ) - if len(tokens) > 4: - if tokens[4] != "for_user": - raise template.TemplateSyntaxError( - "Fourth argument to 'get_admin_log' must be 'for_user'" - ) + if len(tokens) > 4 and tokens[4] != "for_user": + raise template.TemplateSyntaxError( + "Fourth argument to 'get_admin_log' must be 'for_user'" + ) return AdminLogNode( limit=tokens[1], varname=tokens[3], diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/tests.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/tests.py index e3def6ec..a370472f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/tests.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/tests.py @@ -133,16 +133,14 @@ def admin_login(self, username, password, login_url="/admin/"): """ Log in to the admin. """ - self.selenium.get("%s%s" % (self.live_server_url, login_url)) + self.selenium.get(f"{self.live_server_url}{login_url}") username_input = self.selenium.find_element_by_name("username") username_input.send_keys(username) password_input = self.selenium.find_element_by_name("password") password_input.send_keys(password) login_text = _("Log in") with self.wait_page_loaded(): - self.selenium.find_element_by_xpath( - '//input[@value="%s"]' % login_text - ).click() + self.selenium.find_element_by_xpath(f'//input[@value="{login_text}"]').click() def select_option(self, selector, value): """ @@ -167,9 +165,7 @@ def deselect_option(self, selector, value): def _assertOptionsValues(self, options_selector, values): if values: options = self.selenium.find_elements_by_css_selector(options_selector) - actual_values = [] - for option in options: - actual_values.append(option.get_attribute("value")) + actual_values = [option.get_attribute("value") for option in options] self.assertEqual(values, actual_values) else: # Prevent the `find_elements_by_css_selector` call from blocking @@ -187,14 +183,14 @@ def assertSelectOptions(self, selector, values): Assert that the widget identified by `selector` has the selected options with the given `values`. """ - self._assertOptionsValues("%s > option:checked" % selector, values) + self._assertOptionsValues(f"{selector} > option:checked", values) def has_css_class(self, selector, klass): """ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/utils.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/utils.py index 5b875ae5..2b1eb37d 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/utils.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/utils.py @@ -18,7 +18,7 @@ QUOTE_MAP = {i: "_%02X" % i for i in b'":/_#?;@&=+$,"[]<>%\n\\'} UNQUOTE_MAP = {v: chr(k) for k, v in QUOTE_MAP.items()} -UNQUOTE_RE = _lazy_re_compile("_(?:%s)" % "|".join([x[1:] for x in UNQUOTE_MAP])) +UNQUOTE_RE = _lazy_re_compile(f'_(?:{"|".join([x[1:] for x in UNQUOTE_MAP])})') class FieldIsAForeignKeyColumnName(Exception): @@ -125,15 +125,14 @@ def format_callback(obj): has_admin = model in admin_site._registry opts = obj._meta - no_edit_link = "%s: %s" % (capfirst(opts.verbose_name), obj) + no_edit_link = f"{capfirst(opts.verbose_name)}: {obj}" if has_admin: if not admin_site._registry[model].has_delete_permission(request, obj): perms_needed.add(opts.verbose_name) try: admin_url = reverse( - "%s:%s_%s_change" - % (admin_site.name, opts.app_label, opts.model_name), + f"{admin_site.name}:{opts.app_label}_{opts.model_name}_change", None, (quote(obj.pk),), ) @@ -202,10 +201,7 @@ def _nested(self, obj, seen, format_callback): children = [] for child in self.edges.get(obj, ()): children.extend(self._nested(child, seen, format_callback)) - if format_callback: - ret = [format_callback(obj)] - else: - ret = [obj] + ret = [format_callback(obj)] if format_callback else [obj] if children: ret.append(children) return ret @@ -280,10 +276,7 @@ def lookup_field(name, obj, model_admin=None): value = attr(obj) else: attr = getattr(obj, name) - if callable(attr): - value = attr() - else: - value = attr + value = attr() if callable(attr) else attr f = None else: attr = None @@ -350,14 +343,11 @@ def label_for_field(name, model, model_admin=None, return_attr=False, form=None) elif form and name in form.fields: attr = form.fields[name] else: - message = "Unable to lookup '%s' on %s" % ( - name, - model._meta.object_name, - ) + message = f"Unable to lookup '{name}' on {model._meta.object_name}" if model_admin: - message += " or %s" % model_admin.__class__.__name__ + message += f" or {model_admin.__class__.__name__}" if form: - message += " or %s" % form.__class__.__name__ + message += f" or {form.__class__.__name__}" raise AttributeError(message) if hasattr(attr, "short_description"): @@ -369,20 +359,14 @@ def label_for_field(name, model, model_admin=None, return_attr=False, form=None) ): label = attr.fget.short_description elif callable(attr): - if attr.__name__ == "": - label = "--" - else: - label = pretty_name(attr.__name__) + label = "--" if attr.__name__ == "" else pretty_name(attr.__name__) else: label = pretty_name(name) except FieldIsAForeignKeyColumnName: label = pretty_name(name) attr = name - if return_attr: - return (label, attr) - else: - return label + return (label, attr) if return_attr else label def help_text_for_field(name, model): @@ -480,7 +464,7 @@ def reverse_field_path(model, path): break # Field should point to another model - if field.is_relation and not (field.auto_created and not field.concrete): + if field.is_relation and (not field.auto_created or field.concrete): related_name = field.related_query_name() parent = field.remote_field.model else: @@ -502,10 +486,7 @@ def get_fields_from_path(model, path): pieces = path.split(LOOKUP_SEP) fields = [] for piece in pieces: - if fields: - parent = get_model_from_relation(fields[-1]) - else: - parent = model + parent = get_model_from_relation(fields[-1]) if fields else model fields.append(parent._meta.get_field(piece)) return fields @@ -534,36 +515,36 @@ def construct_change_message(form, formsets, add): if formsets: with translation_override(None): for formset in formsets: - for added_object in formset.new_objects: - change_message.append( - { - "added": { - "name": str(added_object._meta.verbose_name), - "object": str(added_object), - } + change_message.extend( + { + "added": { + "name": str(added_object._meta.verbose_name), + "object": str(added_object), } - ) - for changed_object, changed_fields in formset.changed_objects: - change_message.append( - { - "changed": { - "name": str(changed_object._meta.verbose_name), - "object": str(changed_object), - "fields": _get_changed_field_labels_from_form( - formset.forms[0], changed_fields - ), - } + } + for added_object in formset.new_objects + ) + change_message.extend( + { + "changed": { + "name": str(changed_object._meta.verbose_name), + "object": str(changed_object), + "fields": _get_changed_field_labels_from_form( + formset.forms[0], changed_fields + ), } - ) - for deleted_object in formset.deleted_objects: - change_message.append( - { - "deleted": { - "name": str(deleted_object._meta.verbose_name), - "object": str(deleted_object), - } + } + for changed_object, changed_fields in formset.changed_objects + ) + change_message.extend( + { + "deleted": { + "name": str(deleted_object._meta.verbose_name), + "object": str(deleted_object), } - ) + } + for deleted_object in formset.deleted_objects + ) return change_message diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/autocomplete.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/autocomplete.py index 130848b5..7bd99bec 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/autocomplete.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/autocomplete.py @@ -104,8 +104,7 @@ def process_request(self, request): # Validate suitability of objects. if not model_admin.get_search_fields(request): raise Http404( - "%s must have search_fields for the autocomplete_view." - % type(model_admin).__qualname__ + f"{type(model_admin).__qualname__} must have search_fields for the autocomplete_view." ) to_field_name = getattr( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/decorators.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/decorators.py index c1b63ba6..1b4f0b6b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/decorators.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/decorators.py @@ -14,6 +14,4 @@ def staff_member_required( login_url=login_url, redirect_field_name=redirect_field_name, ) - if view_func: - return actual_decorator(view_func) - return actual_decorator + return actual_decorator(view_func) if view_func else actual_decorator diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/main.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/main.py index ace4b34c..b4bcc102 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/main.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/views/main.py @@ -106,7 +106,7 @@ def __init__( to_field = request.GET.get(TO_FIELD_VAR) if to_field and not model_admin.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( - "The field %s cannot be referenced." % to_field + f"The field {to_field} cannot be referenced." ) self.to_field = to_field self.params = dict(request.GET.items()) @@ -115,10 +115,7 @@ def __init__( if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] - if self.is_popup: - self.list_editable = () - else: - self.list_editable = list_editable + self.list_editable = () if self.is_popup else list_editable self.queryset = self.get_queryset(request) self.get_results(request) if self.is_popup: @@ -131,11 +128,7 @@ def __init__( self.pk_attname = self.lookup_opts.pk.attname def __repr__(self): - return "<%s: model=%s model_admin=%s>" % ( - self.__class__.__qualname__, - self.model.__qualname__, - self.model_admin.__class__.__qualname__, - ) + return f"<{self.__class__.__qualname__}: model={self.model.__qualname__} model_admin={self.model_admin.__class__.__qualname__}>" def get_filters_params(self, params=None): """ @@ -157,7 +150,7 @@ def get_filters(self, request): for key, value in lookup_params.items(): if not self.model_admin.lookup_allowed(key, value): - raise DisallowedModelAdminLookup("Filtering by %s not allowed" % key) + raise DisallowedModelAdminLookup(f"Filtering by {key} not allowed") filter_specs = [] for list_filter in self.list_filter: @@ -203,10 +196,10 @@ def get_filters(self, request): if self.date_hierarchy: # Create bounded lookup parameters so that the query is more # efficient. - year = lookup_params.pop("%s__year" % self.date_hierarchy, None) + year = lookup_params.pop(f"{self.date_hierarchy}__year", None) if year is not None: - month = lookup_params.pop("%s__month" % self.date_hierarchy, None) - day = lookup_params.pop("%s__day" % self.date_hierarchy, None) + month = lookup_params.pop(f"{self.date_hierarchy}__month", None) + day = lookup_params.pop(f"{self.date_hierarchy}__day", None) try: from_date = datetime( int(year), @@ -228,8 +221,8 @@ def get_filters(self, request): to_date = make_aware(to_date) lookup_params.update( { - "%s__gte" % self.date_hierarchy: from_date, - "%s__lt" % self.date_hierarchy: to_date, + f"{self.date_hierarchy}__gte": from_date, + f"{self.date_hierarchy}__lt": to_date, } ) @@ -269,7 +262,7 @@ def get_query_string(self, new_params=None, remove=None): del p[k] else: p[k] = v - return "?%s" % urlencode(sorted(p.items())) + return f"?{urlencode(sorted(p.items()))}" def get_results(self, request): paginator = self.model_admin.get_paginator( @@ -468,11 +461,10 @@ def get_ordering_field_columns(self): if isinstance(field, (Combinable, OrderBy)): if not isinstance(field, OrderBy): field = field.asc() - if isinstance(field.expression, F): - order_type = "desc" if field.descending else "asc" - field = field.expression.name - else: + if not isinstance(field.expression, F): continue + order_type = "desc" if field.descending else "asc" + field = field.expression.name elif field.startswith("-"): field = field[1:] order_type = "desc" @@ -555,9 +547,11 @@ def apply_select_related(self, qs): if self.list_select_related is True: return qs.select_related() - if self.list_select_related is False: - if self.has_related_field_in_list_display(): - return qs.select_related() + if ( + self.list_select_related is False + and self.has_related_field_in_list_display() + ): + return qs.select_related() if self.list_select_related: return qs.select_related(*self.list_select_related) @@ -570,16 +564,17 @@ def has_related_field_in_list_display(self): except FieldDoesNotExist: pass else: - if isinstance(field.remote_field, ManyToOneRel): - # _id field names don't require a join. - if field_name != field.get_attname(): - return True + if ( + isinstance(field.remote_field, ManyToOneRel) + and field_name != field.get_attname() + ): + return True return False def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse( - "admin:%s_%s_change" % (self.opts.app_label, self.opts.model_name), + f"admin:{self.opts.app_label}_{self.opts.model_name}_change", args=(quote(pk),), current_app=self.model_admin.admin_site.name, ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/widgets.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/widgets.py index 8ee72fb3..6d9bc399 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/widgets.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admin/widgets.py @@ -140,17 +140,12 @@ def get_context(self, name, value, attrs): if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse( - "admin:%s_%s_changelist" - % ( - rel_to._meta.app_label, - rel_to._meta.model_name, - ), + f"admin:{rel_to._meta.app_label}_{rel_to._meta.model_name}_changelist", current_app=self.admin_site.name, ) - params = self.url_parameters() - if params: - related_url += "?" + urlencode(params) + if params := self.url_parameters(): + related_url += f"?{urlencode(params)}" context["related_url"] = related_url context["link_title"] = _("Lookup") # The JavaScript code looks for this class. @@ -187,12 +182,7 @@ def label_and_url_for_value(self, value): try: url = reverse( - "%s:%s_%s_change" - % ( - self.admin_site.name, - obj._meta.app_label, - obj._meta.object_name.lower(), - ), + f"{self.admin_site.name}:{obj._meta.app_label}_{obj._meta.object_name.lower()}_change", args=(obj.pk,), ) except NoReverseMatch: @@ -223,8 +213,7 @@ def label_and_url_for_value(self, value): return "", "" def value_from_datadict(self, data, files, name): - value = data.get(name) - if value: + if value := data.get(name): return value.split(",") def format_value(self, value): @@ -361,7 +350,7 @@ def __init__(self, attrs=None, validator_class=URLValidator): def get_context(self, name, value, attrs): try: - self.validator(value if value else "") + self.validator(value or "") url_valid = True except ValidationError: url_valid = False @@ -443,8 +432,7 @@ def __init__(self, attrs=None): "uk", "vi", ] -} -SELECT2_TRANSLATIONS.update({"zh-hans": "zh-CN", "zh-hant": "zh-TW"}) +} | {"zh-hans": "zh-CN", "zh-hant": "zh-TW"} class AutocompleteMixin: @@ -514,9 +502,12 @@ def optgroups(self, name, value, attr=None): ) to_field_name = remote_model_opts.get_field(to_field_name).attname choices = ( - (getattr(obj, to_field_name), self.choices.field.label_from_instance(obj)) + ( + getattr(obj, to_field_name), + self.choices.field.label_from_instance(obj), + ) for obj in self.choices.queryset.using(self.db).filter( - **{"%s__in" % to_field_name: selected_choices} + **{f"{to_field_name}__in": selected_choices} ) ) for option_value, option_label in choices: @@ -537,25 +528,27 @@ def optgroups(self, name, value, attr=None): def media(self): extra = "" if settings.DEBUG else ".min" i18n_file = ( - ("admin/js/vendor/select2/i18n/%s.js" % self.i18n_name,) + (f"admin/js/vendor/select2/i18n/{self.i18n_name}.js",) if self.i18n_name else () ) return forms.Media( js=( - "admin/js/vendor/jquery/jquery%s.js" % extra, - "admin/js/vendor/select2/select2.full%s.js" % extra, + ( + f"admin/js/vendor/jquery/jquery{extra}.js", + f"admin/js/vendor/select2/select2.full{extra}.js", + ) + + i18n_file ) - + i18n_file + ( "admin/js/jquery.init.js", "admin/js/autocomplete.js", ), css={ "screen": ( - "admin/css/vendor/select2/select2%s.css" % extra, + f"admin/css/vendor/select2/select2{extra}.css", "admin/css/autocomplete.css", - ), + ) }, ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/utils.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/utils.py index 52bedea4..482a1e24 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/utils.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/utils.py @@ -25,7 +25,7 @@ def get_view_name(view_func): return f"{klass.__module__}.{klass.__qualname__}" mod_name = view_func.__module__ view_name = getattr(view_func, "__qualname__", view_func.__class__.__name__) - return mod_name + "." + view_name + return f"{mod_name}.{view_name}" def parse_docstring(docstring): @@ -48,11 +48,8 @@ def parse_docstring(docstring): metadata = {} body = "\n\n".join(parts[1:]) else: - metadata = dict(metadata.items()) - if metadata: - body = "\n\n".join(parts[1:-1]) - else: - body = "\n\n".join(parts[1:]) + metadata = dict(metadata) + body = "\n\n".join(parts[1:-1]) if metadata else "\n\n".join(parts[1:]) return title, body, metadata @@ -68,7 +65,7 @@ def parse_rst(text, default_reference_context, thing_being_parsed=None): "raw_enabled": False, "file_insertion_enabled": False, } - thing_being_parsed = thing_being_parsed and "<%s>" % thing_being_parsed + thing_being_parsed = thing_being_parsed and f"<{thing_being_parsed}>" # Wrap ``text`` in some reST that sets the default role to ``cmsreference``, # then restores it. source = """ @@ -231,17 +228,16 @@ def replace_unnamed_groups(pattern): group_start_end_indices.append((start, end)) prev_end = end - if group_start_end_indices: - # Replace unnamed groups with . Handle the fact that replacing the - # string between indices will change string length and thus indices - # will point to the wrong substring if not corrected. - final_pattern, prev_end = [], None - for start, end in group_start_end_indices: - if prev_end: - final_pattern.append(pattern[prev_end:start]) - final_pattern.append(pattern[:start] + "") - prev_end = end - final_pattern.append(pattern[prev_end:]) - return "".join(final_pattern) - else: + if not group_start_end_indices: return pattern + # Replace unnamed groups with . Handle the fact that replacing the + # string between indices will change string length and thus indices + # will point to the wrong substring if not corrected. + final_pattern, prev_end = [], None + for start, end in group_start_end_indices: + if prev_end: + final_pattern.append(pattern[prev_end:start]) + final_pattern.append(f"{pattern[:start]}") + prev_end = end + final_pattern.append(pattern[prev_end:]) + return "".join(final_pattern) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/views.py index e3c53fc7..f9ca556f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/admindocs/views.py @@ -137,22 +137,21 @@ class ViewIndexView(BaseAdminDocsView): template_name = "admin_doc/view_index.html" def get_context_data(self, **kwargs): - views = [] url_resolver = get_resolver(get_urlconf()) try: view_functions = extract_views_from_urlpatterns(url_resolver.url_patterns) except ImproperlyConfigured: view_functions = [] - for (func, regex, namespace, name) in view_functions: - views.append( - { - "full_name": get_view_name(func), - "url": simplify_regex(regex), - "url_name": ":".join((namespace or []) + (name and [name] or [])), - "namespace": ":".join(namespace or []), - "name": name, - } - ) + views = [ + { + "full_name": get_view_name(func), + "url": simplify_regex(regex), + "url_name": ":".join((namespace or []) + (name and [name] or [])), + "namespace": ":".join(namespace or []), + "name": name, + } + for func, regex, namespace, name in view_functions + ] return super().get_context_data(**{**kwargs, "views": views}) @@ -267,27 +266,28 @@ def get_context_data(self, **kwargs): "app_label": app_label, "object_name": data_type, } - fields.append( - { - "name": "%s.all" % field.name, - "data_type": "List", - "verbose": utils.parse_rst( - _("all %s") % verbose, "model", _("model:") + opts.model_name - ), - } - ) - fields.append( - { - "name": "%s.count" % field.name, - "data_type": "Integer", - "verbose": utils.parse_rst( - _("number of %s") % verbose, - "model", - _("model:") + opts.model_name, - ), - } + fields.extend( + ( + { + "name": f"{field.name}.all", + "data_type": "List", + "verbose": utils.parse_rst( + _("all %s") % verbose, + "model", + _("model:") + opts.model_name, + ), + }, + { + "name": f"{field.name}.count", + "data_type": "Integer", + "verbose": utils.parse_rst( + _("number of %s") % verbose, + "model", + _("model:") + opts.model_name, + ), + }, + ) ) - methods = [] # Gather model methods. for func_name, func in model.__dict__.items(): @@ -355,25 +355,27 @@ def get_context_data(self, **kwargs): "object_name": rel.related_model._meta.object_name, } accessor = rel.get_accessor_name() - fields.append( - { - "name": "%s.all" % accessor, - "data_type": "List", - "verbose": utils.parse_rst( - _("all %s") % verbose, "model", _("model:") + opts.model_name - ), - } - ) - fields.append( - { - "name": "%s.count" % accessor, - "data_type": "Integer", - "verbose": utils.parse_rst( - _("number of %s") % verbose, - "model", - _("model:") + opts.model_name, - ), - } + fields.extend( + ( + { + "name": f"{accessor}.all", + "data_type": "List", + "verbose": utils.parse_rst( + _("all %s") % verbose, + "model", + _("model:") + opts.model_name, + ), + }, + { + "name": f"{accessor}.count", + "data_type": "Integer", + "verbose": utils.parse_rst( + _("number of %s") % verbose, + "model", + _("model:") + opts.model_name, + ), + }, + ) ) return super().get_context_data( **{ @@ -402,10 +404,7 @@ def get_context_data(self, **kwargs): # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) - if template_file.exists(): - template_contents = template_file.read_text() - else: - template_contents = "" + template_contents = template_file.read_text() if template_file.exists() else "" templates.append( { "file": template_file, @@ -488,5 +487,5 @@ def simplify_regex(pattern): # clean up any outstanding regex-y characters. pattern = pattern.replace("^", "").replace("$", "").replace("?", "") if not pattern.startswith("/"): - pattern = "/" + pattern + pattern = f"/{pattern}" return pattern diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/__init__.py index 155330c5..f8e0b0b1 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/__init__.py @@ -174,8 +174,7 @@ def get_user_model(): ) except LookupError: raise ImproperlyConfigured( - "AUTH_USER_MODEL refers to model '%s' that has not been installed" - % settings.AUTH_USER_MODEL + f"AUTH_USER_MODEL refers to model '{settings.AUTH_USER_MODEL}' that has not been installed" ) @@ -213,7 +212,7 @@ def get_permission_codename(action, opts): """ Return the codename of the permission for the specified action. """ - return "%s_%s" % (action, opts.model_name) + return f"{action}_{opts.model_name}" def update_session_auth_hash(request, user): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/admin.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/admin.py index 636e620e..a6644331 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/admin.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/admin.py @@ -83,9 +83,7 @@ class UserAdmin(admin.ModelAdmin): ) def get_fieldsets(self, request, obj=None): - if not obj: - return self.add_fieldsets - return super().get_fieldsets(request, obj) + return super().get_fieldsets(request, obj) if obj else self.add_fieldsets def get_form(self, request, obj=None, **kwargs): """ @@ -94,7 +92,7 @@ def get_form(self, request, obj=None, **kwargs): defaults = {} if obj is None: defaults["form"] = self.add_form - defaults.update(kwargs) + defaults |= kwargs return super().get_form(request, obj, **defaults) def get_urls(self): @@ -170,12 +168,7 @@ def user_change_password(self, request, id, form_url=""): update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( - "%s:%s_%s_change" - % ( - self.admin_site.name, - user._meta.app_label, - user._meta.model_name, - ), + f"{self.admin_site.name}:{user._meta.app_label}_{user._meta.model_name}_change", args=(user.pk,), ) ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/backends.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/backends.py index 7cf40571..bbb798b9 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/backends.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/backends.py @@ -61,7 +61,7 @@ def _get_user_permissions(self, user_obj): def _get_group_permissions(self, user_obj): user_groups_field = get_user_model()._meta.get_field("groups") - user_groups_query = "group__%s" % user_groups_field.related_query_name() + user_groups_query = f"group__{user_groups_field.related_query_name()}" return Permission.objects.filter(**{user_groups_query: user_obj}) def _get_permissions(self, user_obj, obj, from_name): @@ -73,16 +73,14 @@ def _get_permissions(self, user_obj, obj, from_name): if not user_obj.is_active or user_obj.is_anonymous or obj is not None: return set() - perm_cache_name = "_%s_perm_cache" % from_name + perm_cache_name = f"_{from_name}_perm_cache" if not hasattr(user_obj, perm_cache_name): if user_obj.is_superuser: perms = Permission.objects.all() else: - perms = getattr(self, "_get_%s_permissions" % from_name)(user_obj) + perms = getattr(self, f"_get_{from_name}_permissions")(user_obj) perms = perms.values_list("content_type__app_label", "codename").order_by() - setattr( - user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms} - ) + setattr(user_obj, perm_cache_name, {f"{ct}.{name}" for ct, name in perms}) return getattr(user_obj, perm_cache_name) def get_user_permissions(self, user_obj, obj=None): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py index f6de3b93..fdef4c74 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py @@ -27,7 +27,7 @@ def normalize_email(cls, email): except ValueError: pass else: - email = email_name + "@" + domain_part.lower() + email = f"{email_name}@{domain_part.lower()}" return email def make_random_password( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/checks.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/checks.py index ee808252..7a3d6743 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/checks.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/checks.py @@ -52,8 +52,8 @@ def check_user_model(app_configs=None, **kwargs): ) # Check that the username field is unique - if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any( - constraint.fields == (cls.USERNAME_FIELD,) + if not cls._meta.get_field(cls.USERNAME_FIELD).unique and all( + constraint.fields != (cls.USERNAME_FIELD,) for constraint in cls._meta.total_unique_constraints ): if settings.AUTHENTICATION_BACKENDS == [ @@ -70,8 +70,7 @@ def check_user_model(app_configs=None, **kwargs): else: errors.append( checks.Warning( - "'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique." - % (cls._meta.object_name, cls.USERNAME_FIELD), + f"'{cls._meta.object_name}.{cls.USERNAME_FIELD}' is named as the 'USERNAME_FIELD', but it is not unique.", hint=( "Ensure that your authentication backend(s) can handle " "non-unique usernames." @@ -141,10 +140,8 @@ def check_models_permissions(app_configs=None, **kwargs): ) ) # Check builtin permission codename length. - max_builtin_permission_codename_length = ( - max(len(codename) for codename in builtin_permissions.keys()) - if builtin_permissions - else 0 + max_builtin_permission_codename_length = max( + (len(codename) for codename in builtin_permissions), default=0 ) if max_builtin_permission_codename_length > permission_codename_max_length: model_name_max_length = permission_codename_max_length - ( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/context_processors.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/context_processors.py index 0a881992..1a13ab85 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/context_processors.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/context_processors.py @@ -10,7 +10,7 @@ def __repr__(self): return str(self.user.get_all_permissions()) def __getitem__(self, perm_name): - return self.user.has_perm("%s.%s" % (self.app_label, perm_name)) + return self.user.has_perm(f"{self.app_label}.{perm_name}") def __iter__(self): # To fix 'item in perms.someapp' and __getitem__ interaction we need to diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py index a419068d..91239c38 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py @@ -52,9 +52,7 @@ def login_required( login_url=login_url, redirect_field_name=redirect_field_name, ) - if function: - return actual_decorator(function) - return actual_decorator + return actual_decorator(function) if function else actual_decorator def permission_required(perm, login_url=None, raise_exception=False): @@ -66,10 +64,7 @@ def permission_required(perm, login_url=None, raise_exception=False): """ def check_perms(user): - if isinstance(perm, str): - perms = (perm,) - else: - perms = perm + perms = (perm, ) if isinstance(perm, str) else perm # First check if the user has the permission (even anon users) if user.has_perms(perms): return True diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/forms.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/forms.py index 9d6a9918..2396b91e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/forms.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/forms.py @@ -51,8 +51,10 @@ def get_context(self, name, value, attrs): } ) else: - for key, value_ in hasher.safe_summary(value).items(): - summary.append({"label": gettext(key), "value": value_}) + summary.extend( + {"label": gettext(key), "value": value_} + for key, value_ in hasher.safe_summary(value).items() + ) context["summary"] = summary return context @@ -127,10 +129,7 @@ def clean_password2(self): def _post_clean(self): super()._post_clean() - # Validate the password after self.instance is updated with form data - # by super(). - password = self.cleaned_data.get("password2") - if password: + if password := self.cleaned_data.get("password2"): try: password_validation.validate_password(password, self.instance) except ValidationError as error: @@ -161,11 +160,9 @@ class Meta: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - password = self.fields.get("password") - if password: + if password := self.fields.get("password"): password.help_text = password.help_text.format("../password/") - user_permissions = self.fields.get("user_permissions") - if user_permissions: + if user_permissions := self.fields.get("user_permissions"): user_permissions.queryset = user_permissions.queryset.select_related( "content_type" ) @@ -292,10 +289,7 @@ def get_users(self, email): """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter( - **{ - "%s__iexact" % email_field_name: email, - "is_active": True, - } + **{f"{email_field_name}__iexact": email, "is_active": True} ) return ( u @@ -378,12 +372,11 @@ def __init__(self, user, *args, **kwargs): def clean_new_password2(self): password1 = self.cleaned_data.get("new_password1") password2 = self.cleaned_data.get("new_password2") - if password1 and password2: - if password1 != password2: - raise ValidationError( - self.error_messages["password_mismatch"], - code="password_mismatch", - ) + if password1 and password2 and password1 != password2: + raise ValidationError( + self.error_messages["password_mismatch"], + code="password_mismatch", + ) password_validation.validate_password(password2, self.user) return password2 @@ -480,7 +473,4 @@ def save(self, commit=True): @property def changed_data(self): data = super().changed_data - for name in self.fields: - if name not in data: - return [] - return ["password"] + return next(([] for name in self.fields if name not in data), ["password"]) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/handlers/modwsgi.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/handlers/modwsgi.py index 591ec72c..dcf7915a 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/handlers/modwsgi.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/handlers/modwsgi.py @@ -19,9 +19,7 @@ def check_password(environ, username, password): user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return None - if not user.is_active: - return None - return user.check_password(password) + return user.check_password(password) if user.is_active else None finally: db.close_old_connections() @@ -36,8 +34,10 @@ def groups_for_user(environ, username): user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return [] - if not user.is_active: - return [] - return [group.name.encode() for group in user.groups.all()] + return ( + [group.name.encode() for group in user.groups.all()] + if user.is_active + else [] + ) finally: db.close_old_connections() diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/hashers.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/hashers.py index 832531e5..44f4cfbd 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/hashers.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/hashers.py @@ -82,7 +82,7 @@ def make_password(password, salt=None, hasher="default"): ) if not isinstance(password, (bytes, str)): raise TypeError( - "Password must be a string or bytes, got %s." % type(password).__qualname__ + f"Password must be a string or bytes, got {type(password).__qualname__}." ) hasher = get_hasher(hasher) salt = salt or hasher.salt() @@ -97,7 +97,7 @@ def get_hashers(): hasher = hasher_cls() if not getattr(hasher, "algorithm"): raise ImproperlyConfigured( - "hasher doesn't specify an algorithm name: %s" % hasher_path + f"hasher doesn't specify an algorithm name: {hasher_path}" ) hashers.append(hasher) return hashers @@ -386,7 +386,7 @@ def decode(self, encoded): argon2 = self._load_library() algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm - params = argon2.extract_parameters("$" + rest) + params = argon2.extract_parameters(f"${rest}") variety, *_, b64salt, hash = rest.split("$") # Add padding. b64salt += "=" * (-len(b64salt) % 4) @@ -408,7 +408,7 @@ def verify(self, password, encoded): algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm try: - return argon2.PasswordHasher().verify("$" + rest, password) + return argon2.PasswordHasher().verify(f"${rest}", password) except argon2.exceptions.VerificationError: return False @@ -483,7 +483,7 @@ def encode(self, password, salt): password = binascii.hexlify(self.digest(password).digest()) data = bcrypt.hashpw(password, salt) - return "%s$%s" % (self.algorithm, data.decode("ascii")) + return f'{self.algorithm}${data.decode("ascii")}' def decode(self, encoded): algorithm, empty, algostr, work_factor, data = encoded.split("$", 4) @@ -632,7 +632,7 @@ class SHA1PasswordHasher(BasePasswordHasher): def encode(self, password, salt): self._check_encode_args(password, salt) hash = hashlib.sha1((salt + password).encode()).hexdigest() - return "%s$%s$%s" % (self.algorithm, salt, hash) + return f"{self.algorithm}${salt}${hash}" def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) @@ -674,7 +674,7 @@ class MD5PasswordHasher(BasePasswordHasher): def encode(self, password, salt): self._check_encode_args(password, salt) hash = hashlib.md5((salt + password).encode()).hexdigest() - return "%s$%s$%s" % (self.algorithm, salt, hash) + return f"{self.algorithm}${salt}${hash}" def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) @@ -725,7 +725,7 @@ def encode(self, password, salt): if salt != "": raise ValueError("salt must be empty.") hash = hashlib.sha1(password.encode()).hexdigest() - return "sha1$$%s" % hash + return f"sha1$${hash}" def decode(self, encoded): assert encoded.startswith("sha1$$") @@ -817,7 +817,7 @@ def encode(self, password, salt): if hash is None: # A platform like OpenBSD with a dummy crypt module. raise TypeError("hash must be provided.") # we don't need to store the salt, but Django used to do this - return "%s$%s$%s" % (self.algorithm, "", hash) + return f"{self.algorithm}$${hash}" def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/__init__.py index 0b5a9826..4e355f62 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/__init__.py @@ -23,15 +23,13 @@ def _get_builtin_permissions(opts): Return (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete', 'view') """ - perms = [] - for action in opts.default_permissions: - perms.append( - ( - get_permission_codename(action, opts), - "Can %s %s" % (action, opts.verbose_name_raw), - ) + return [ + ( + get_permission_codename(action, opts), + f"Can {action} {opts.verbose_name_raw}", ) - return perms + for action in opts.default_permissions + ] def create_permissions( @@ -81,9 +79,9 @@ def create_permissions( ) ctypes.add(ctype) - for perm in _get_all_permissions(klass._meta): - searched_perms.append((ctype, perm)) - + searched_perms.extend( + (ctype, perm) for perm in _get_all_permissions(klass._meta) + ) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. @@ -103,7 +101,7 @@ def create_permissions( Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: - print("Adding permission '%s'" % perm) + print(f"Adding permission '{perm}'") def get_system_username(): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/changepassword.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/changepassword.py index 669d8cf5..5dee2b6c 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/changepassword.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/changepassword.py @@ -15,10 +15,10 @@ class Command(BaseCommand): requires_system_checks = [] def _get_pass(self, prompt="Password: "): - p = getpass.getpass(prompt=prompt) - if not p: + if p := getpass.getpass(prompt=prompt): + return p + else: raise CommandError("aborted") - return p def add_arguments(self, parser): parser.add_argument( @@ -36,19 +36,15 @@ def add_arguments(self, parser): ) def handle(self, *args, **options): - if options["username"]: - username = options["username"] - else: - username = getpass.getuser() - + username = options["username"] or getpass.getuser() try: u = UserModel._default_manager.using(options["database"]).get( **{UserModel.USERNAME_FIELD: username} ) except UserModel.DoesNotExist: - raise CommandError("user '%s' does not exist" % username) + raise CommandError(f"user '{username}' does not exist") - self.stdout.write("Changing password for user '%s'" % u) + self.stdout.write(f"Changing password for user '{u}'") MAX_TRIES = 3 count = 0 @@ -72,10 +68,10 @@ def handle(self, *args, **options): if count == MAX_TRIES: raise CommandError( - "Aborting password change for user '%s' after %s attempts" % (u, count) + f"Aborting password change for user '{u}' after {count} attempts" ) u.set_password(p1) u.save() - return "Password changed successfully for user '%s'" % u + return f"Password changed successfully for user '{u}'" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py index 5fffa55a..64d05b56 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py @@ -35,7 +35,7 @@ def __init__(self, *args, **kwargs): def add_arguments(self, parser): parser.add_argument( - "--%s" % self.UserModel.USERNAME_FIELD, + f"--{self.UserModel.USERNAME_FIELD}", help="Specifies the login for the superuser.", ) parser.add_argument( @@ -69,7 +69,7 @@ def add_arguments(self, parser): ) else: parser.add_argument( - "--%s" % field_name, + f"--{field_name}", action="append", help=( "Specifies the %s for the superuser. Can be used " @@ -78,8 +78,8 @@ def add_arguments(self, parser): ) else: parser.add_argument( - "--%s" % field_name, - help="Specifies the %s for the superuser." % field_name, + f"--{field_name}", + help=f"Specifies the {field_name} for the superuser.", ) def execute(self, *args, **options): @@ -100,23 +100,17 @@ def handle(self, *args, **options): user_data[PASSWORD_FIELD] = None try: if options["interactive"]: - # Same as user_data but without many to many fields and with - # foreign keys as fake model instances instead of raw IDs. - fake_user_data = {} if hasattr(self.stdin, "isatty") and not self.stdin.isatty(): raise NotRunningInTTYException default_username = get_default_username(database=database) if username: - error_msg = self._validate_username( + if error_msg := self._validate_username( username, verbose_field_name, database - ) - if error_msg: + ): self.stderr.write(error_msg) username = None elif username == "": - raise CommandError( - "%s cannot be blank." % capfirst(verbose_field_name) - ) + raise CommandError(f"{capfirst(verbose_field_name)} cannot be blank.") # Prompt for username. while username is None: message = self._get_input_message( @@ -126,19 +120,20 @@ def handle(self, *args, **options): self.username_field, message, default_username ) if username: - error_msg = self._validate_username( + if error_msg := self._validate_username( username, verbose_field_name, database - ) - if error_msg: + ): self.stderr.write(error_msg) username = None continue user_data[self.UserModel.USERNAME_FIELD] = username - fake_user_data[self.UserModel.USERNAME_FIELD] = ( - self.username_field.remote_field.model(username) + fake_user_data = { + self.UserModel.USERNAME_FIELD: self.username_field.remote_field.model( + username + ) if self.username_field.remote_field else username - ) + } # Prompt for required fields. for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) @@ -200,28 +195,23 @@ def handle(self, *args, **options): # options. if username is None: username = os.environ.get( - "DJANGO_SUPERUSER_" + self.UserModel.USERNAME_FIELD.upper() + f"DJANGO_SUPERUSER_{self.UserModel.USERNAME_FIELD.upper()}" ) if username is None: raise CommandError( - "You must use --%s with --noinput." - % self.UserModel.USERNAME_FIELD + f"You must use --{self.UserModel.USERNAME_FIELD} with --noinput." ) - else: - error_msg = self._validate_username( - username, verbose_field_name, database - ) - if error_msg: - raise CommandError(error_msg) + if error_msg := self._validate_username( + username, verbose_field_name, database + ): + raise CommandError(error_msg) user_data[self.UserModel.USERNAME_FIELD] = username for field_name in self.UserModel.REQUIRED_FIELDS: - env_var = "DJANGO_SUPERUSER_" + field_name.upper() + env_var = f"DJANGO_SUPERUSER_{field_name.upper()}" value = options[field_name] or os.environ.get(env_var) if not value: - raise CommandError( - "You must use --%s with --noinput." % field_name - ) + raise CommandError(f"You must use --{field_name} with --noinput.") field = self.UserModel._meta.get_field(field_name) user_data[field_name] = field.clean(value, None) if field.many_to_many and isinstance(user_data[field_name], str): @@ -257,7 +247,7 @@ def get_input_data(self, field, message, default=None): try: val = field.clean(raw_value, None) except exceptions.ValidationError as e: - self.stderr.write("Error: %s" % "; ".join(e.messages)) + self.stderr.write(f'Error: {"; ".join(e.messages)}') val = None return val @@ -265,7 +255,7 @@ def get_input_data(self, field, message, default=None): def _get_input_message(self, field, default=None): return "%s%s%s: " % ( capfirst(field.verbose_name), - " (leave blank to use '%s')" % default if default else "", + f" (leave blank to use '{default}')" if default else "", " (%s.%s)" % ( field.remote_field.model._meta.object_name, @@ -287,9 +277,9 @@ def _validate_username(self, username, verbose_field_name, database): except self.UserModel.DoesNotExist: pass else: - return "Error: That %s is already taken." % verbose_field_name + return f"Error: That {verbose_field_name} is already taken." if not username: - return "%s cannot be blank." % capfirst(verbose_field_name) + return f"{capfirst(verbose_field_name)} cannot be blank." try: self.username_field.clean(username, None) except exceptions.ValidationError as e: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/middleware.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/middleware.py index dcc48215..c26ec563 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/middleware.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/middleware.py @@ -75,10 +75,7 @@ def process_request(self, request): # it does not match the authorized user in the header. self._remove_invalid_user(request) - # We are seeing this user for the first time in this session, attempt - # to authenticate the user. - user = auth.authenticate(request, remote_user=username) - if user: + if user := auth.authenticate(request, remote_user=username): # User is valid. Set request.user and persist user in the session # by logging the user in. request.user = user diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/migrations/0011_update_proxy_permissions.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/migrations/0011_update_proxy_permissions.py index b792141d..434fe572 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/migrations/0011_update_proxy_permissions.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/migrations/0011_update_proxy_permissions.py @@ -28,7 +28,8 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): if not opts.proxy: continue proxy_default_permissions_codenames = [ - "%s_%s" % (action, opts.model_name) for action in opts.default_permissions + f"{action}_{opts.model_name}" + for action in opts.default_permissions ] permissions_query = Q(codename__in=proxy_default_permissions_codenames) for codename, name in opts.permissions: @@ -49,8 +50,8 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): content_type=old_content_type, ).update(content_type=new_content_type) except IntegrityError: - old = "{}_{}".format(old_content_type.app_label, old_content_type.model) - new = "{}_{}".format(new_content_type.app_label, new_content_type.model) + old = f"{old_content_type.app_label}_{old_content_type.model}" + new = f"{new_content_type.app_label}_{new_content_type.model}" sys.stdout.write( style.WARNING(WARNING.format(old=old, new=new, query=permissions_query)) ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/mixins.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/mixins.py index 0e46000d..c9de840b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/mixins.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/mixins.py @@ -22,14 +22,14 @@ def get_login_url(self): """ Override this method to override the login_url attribute. """ - login_url = self.login_url or settings.LOGIN_URL - if not login_url: + if login_url := self.login_url or settings.LOGIN_URL: + return str(login_url) + else: raise ImproperlyConfigured( f"{self.__class__.__name__} is missing the login_url attribute. Define " f"{self.__class__.__name__}.login_url, settings.LOGIN_URL, or override " f"{self.__class__.__name__}.get_login_url()." ) - return str(login_url) def get_permission_denied_message(self): """ @@ -68,9 +68,11 @@ class LoginRequiredMixin(AccessMixin): """Verify that the current user is authenticated.""" def dispatch(self, request, *args, **kwargs): - if not request.user.is_authenticated: - return self.handle_no_permission() - return super().dispatch(request, *args, **kwargs) + return ( + super().dispatch(request, *args, **kwargs) + if request.user.is_authenticated + else self.handle_no_permission() + ) class PermissionRequiredMixin(AccessMixin): @@ -90,11 +92,11 @@ def get_permission_required(self): f"{self.__class__.__name__}.permission_required, or override " f"{self.__class__.__name__}.get_permission_required()." ) - if isinstance(self.permission_required, str): - perms = (self.permission_required,) - else: - perms = self.permission_required - return perms + return ( + (self.permission_required,) + if isinstance(self.permission_required, str) + else self.permission_required + ) def has_permission(self): """ @@ -104,9 +106,11 @@ def has_permission(self): return self.request.user.has_perms(perms) def dispatch(self, request, *args, **kwargs): - if not self.has_permission(): - return self.handle_no_permission() - return super().dispatch(request, *args, **kwargs) + return ( + super().dispatch(request, *args, **kwargs) + if self.has_permission() + else self.handle_no_permission() + ) class UserPassesTestMixin(AccessMixin): @@ -117,9 +121,7 @@ class UserPassesTestMixin(AccessMixin): def test_func(self): raise NotImplementedError( - "{} is missing the implementation of the test_func() method.".format( - self.__class__.__name__ - ) + f"{self.__class__.__name__} is missing the implementation of the test_func() method." ) def get_test_func(self): @@ -130,6 +132,8 @@ def get_test_func(self): def dispatch(self, request, *args, **kwargs): user_test_result = self.get_test_func()() - if not user_test_result: - return self.handle_no_permission() - return super().dispatch(request, *args, **kwargs) + return ( + super().dispatch(request, *args, **kwargs) + if user_test_result + else self.handle_no_permission() + ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/models.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/models.py index 53bb681e..08e5ba64 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/models.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/models.py @@ -75,7 +75,7 @@ class Meta: ordering = ["content_type__app_label", "content_type__model", "codename"] def __str__(self): - return "%s | %s" % (self.content_type, self.name) + return f"{self.content_type} | {self.name}" def natural_key(self): return (self.codename,) + self.content_type.natural_key() @@ -201,7 +201,7 @@ def with_perm( # A few helper functions for common logic between User and AnonymousUser. def _user_get_permissions(user, obj, from_name): permissions = set() - name = "get_%s_permissions" % from_name + name = f"get_{from_name}_permissions" for backend in auth.get_backends(): if hasattr(backend, name): permissions.update(getattr(backend, name)(user, obj)) @@ -387,7 +387,7 @@ def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ - full_name = "%s %s" % (self.first_name, self.last_name) + full_name = f"{self.first_name} {self.last_name}" return full_name.strip() def get_short_name(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/password_validation.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/password_validation.py index e5c97108..3ac835c4 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/password_validation.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/password_validation.py @@ -73,12 +73,9 @@ def password_validators_help_texts(password_validators=None): """ Return a list of all help texts of all configured validators. """ - help_texts = [] if password_validators is None: password_validators = get_default_password_validators() - for validator in password_validators: - help_texts.append(validator.get_help_text()) - return help_texts + return [validator.get_help_text() for validator in password_validators] def _password_validators_help_text_html(password_validators=None): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/tokens.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/tokens.py index de8e17a2..2abf0fb5 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/tokens.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/tokens.py @@ -37,7 +37,7 @@ def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ - if not (user and token): + if not user or not token: return False # Parse the token try: @@ -51,14 +51,13 @@ def check_token(self, user, token): return False # Check that the timestamp/uid has not been tampered with - if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): - return False - - # Check the timestamp is within limit. - if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: - return False - - return True + return ( + self._num_seconds(self._now()) - ts <= settings.PASSWORD_RESET_TIMEOUT + if constant_time_compare( + self._make_token_with_timestamp(user, ts), token + ) + else False + ) def _make_token_with_timestamp(self, user, timestamp): # timestamp is number of seconds since 2001-1-1. Converted to base 36, @@ -72,7 +71,7 @@ def _make_token_with_timestamp(self, user, timestamp): ).hexdigest()[ ::2 ] # Limit to shorten the URL. - return "%s-%s" % (ts_b36, hash_string) + return f"{ts_b36}-{hash_string}" def _make_hash_value(self, user, timestamp): """ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/views.py index 7749e9f1..677f0502 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/auth/views.py @@ -125,8 +125,7 @@ class LogoutView(SuccessURLAllowedHostsMixin, TemplateView): @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): auth_logout(request) - next_page = self.get_next_page() - if next_page: + if next_page := self.get_next_page(): # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) return super().dispatch(request, *args, **kwargs) @@ -283,17 +282,16 @@ def dispatch(self, *args, **kwargs): # If the token is valid, display the password reset form. self.validlink = True return super().dispatch(*args, **kwargs) - else: - if self.token_generator.check_token(self.user, token): - # Store the token in the session and redirect to the - # password reset form at a URL without the token. That - # avoids the possibility of leaking the token in the - # HTTP Referer header. - self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token - redirect_url = self.request.path.replace( - token, self.reset_url_token - ) - return HttpResponseRedirect(redirect_url) + elif self.token_generator.check_token(self.user, token): + # Store the token in the session and redirect to the + # password reset form at a URL without the token. That + # avoids the possibility of leaking the token in the + # HTTP Referer header. + self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token + redirect_url = self.request.path.replace( + token, self.reset_url_token + ) + return HttpResponseRedirect(redirect_url) # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/admin.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/admin.py index 617d6d2e..046d8633 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/admin.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/admin.py @@ -19,74 +19,57 @@ def _check_exclude_of_parent_model(self, obj, parent_model): return [] def _check_relation(self, obj, parent_model): - # There's no FK, but we do need to confirm that the ct_field and - # ct_fk_field are valid, and that they are part of a GenericForeignKey. - - gfks = [ - f - for f in obj.model._meta.private_fields - if isinstance(f, GenericForeignKey) - ] - if not gfks: + if not ( + gfks := [ + f + for f in obj.model._meta.private_fields + if isinstance(f, GenericForeignKey) + ] + ): return [ checks.Error( - "'%s' has no GenericForeignKey." % obj.model._meta.label, + f"'{obj.model._meta.label}' has no GenericForeignKey.", obj=obj.__class__, id="admin.E301", ) ] - else: # Check that the ct_field and ct_fk_fields exist - try: - obj.model._meta.get_field(obj.ct_field) - except FieldDoesNotExist: - return [ - checks.Error( - "'ct_field' references '%s', which is not a field on '%s'." - % ( - obj.ct_field, - obj.model._meta.label, - ), - obj=obj.__class__, - id="admin.E302", - ) - ] - - try: - obj.model._meta.get_field(obj.ct_fk_field) - except FieldDoesNotExist: - return [ - checks.Error( - "'ct_fk_field' references '%s', which is not a field on '%s'." - % ( - obj.ct_fk_field, - obj.model._meta.label, - ), - obj=obj.__class__, - id="admin.E303", - ) - ] - - # There's one or more GenericForeignKeys; make sure that one of them - # uses the right ct_field and ct_fk_field. - for gfk in gfks: - if gfk.ct_field == obj.ct_field and gfk.fk_field == obj.ct_fk_field: - return [] + try: + obj.model._meta.get_field(obj.ct_field) + except FieldDoesNotExist: + return [ + checks.Error( + f"'ct_field' references '{obj.ct_field}', which is not a field on '{obj.model._meta.label}'.", + obj=obj.__class__, + id="admin.E302", + ) + ] + try: + obj.model._meta.get_field(obj.ct_fk_field) + except FieldDoesNotExist: return [ checks.Error( - "'%s' has no GenericForeignKey using content type field '%s' and " - "object ID field '%s'." - % ( - obj.model._meta.label, - obj.ct_field, - obj.ct_fk_field, - ), + f"'ct_fk_field' references '{obj.ct_fk_field}', which is not a field on '{obj.model._meta.label}'.", obj=obj.__class__, - id="admin.E304", + id="admin.E303", ) ] + # There's one or more GenericForeignKeys; make sure that one of them + # uses the right ct_field and ct_fk_field. + for gfk in gfks: + if gfk.ct_field == obj.ct_field and gfk.fk_field == obj.ct_fk_field: + return [] + + return [ + checks.Error( + f"'{obj.model._meta.label}' has no GenericForeignKey using content type field '{obj.ct_field}' and object ID field '{obj.ct_fk_field}'.", + obj=obj.__class__, + id="admin.E304", + ) + ] + class GenericInlineModelAdmin(InlineModelAdmin): ct_field = "content_type" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/checks.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/checks.py index 753c5d22..307ddc28 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/checks.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/checks.py @@ -32,15 +32,13 @@ def check_model_name_lengths(app_configs=None, **kwargs): models = chain.from_iterable( app_config.get_models() for app_config in app_configs ) - errors = [] - for model in models: - if len(model._meta.model_name) > 100: - errors.append( - Error( - "Model names must be at most 100 characters (got %d)." - % (len(model._meta.model_name),), - obj=model, - id="contenttypes.E005", - ) - ) - return errors + return [ + Error( + "Model names must be at most 100 characters (got %d)." + % (len(model._meta.model_name),), + obj=model, + id="contenttypes.E005", + ) + for model in models + if len(model._meta.model_name) > 100 + ] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/fields.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/fields.py index 338562e6..da6b8925 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/fields.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/fields.py @@ -74,7 +74,7 @@ def get_forward_related_filter(self, obj): def __str__(self): model = self.model - return "%s.%s" % (model._meta.label, self.name) + return f"{model._meta.label}.{self.name}" def check(self, **kwargs): return [ @@ -131,8 +131,7 @@ def _check_content_type_field(self): if not isinstance(field, models.ForeignKey): return [ checks.Error( - "'%s.%s' is not a ForeignKey." - % (self.model._meta.object_name, self.ct_field), + f"'{self.model._meta.object_name}.{self.ct_field}' is not a ForeignKey.", hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." @@ -144,8 +143,7 @@ def _check_content_type_field(self): elif field.remote_field.model != ContentType: return [ checks.Error( - "'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." - % (self.model._meta.object_name, self.ct_field), + f"'{self.model._meta.object_name}.{self.ct_field}' is not a ForeignKey to 'contenttypes.ContentType'.", hint=( "GenericForeignKeys must use a ForeignKey to " "'contenttypes.ContentType' as the 'content_type' field." @@ -202,14 +200,13 @@ def gfk_key(obj): ct_id = getattr(obj, ct_attname) if ct_id is None: return None - else: - model = self.get_content_type( - id=ct_id, using=obj._state.db - ).model_class() - return ( - model._meta.pk.get_prep_value(getattr(obj, self.fk_field)), - model, - ) + model = self.get_content_type( + id=ct_id, using=obj._state.db + ).model_class() + return ( + model._meta.pk.get_prep_value(getattr(obj, self.fk_field)), + model, + ) return ( ret_val, @@ -364,18 +361,20 @@ def _check_generic_foreign_key_existence(self): target = self.remote_field.model if isinstance(target, ModelBase): fields = target._meta.private_fields - if any(self._is_matching_generic_foreign_key(field) for field in fields): - return [] - else: - return [ + return ( + [] + if any( + self._is_matching_generic_foreign_key(field) + for field in fields + ) + else [ checks.Error( - "The GenericRelation defines a relation with the model " - "'%s', but that model does not have a GenericForeignKey." - % target._meta.label, + f"The GenericRelation defines a relation with the model '{target._meta.label}', but that model does not have a GenericForeignKey.", obj=self, id="contenttypes.E004", ) ] + ) else: return [] @@ -394,18 +393,10 @@ def _get_path_info_with_parent(self, filtered_relation): The idea is that if you have a GFK defined on a parent model then we need to join the parent model first, then the child model. """ - # With an inheritance chain ChildTag -> Tag and Tag defines the - # GenericForeignKey, and a TaggedItem model has a GenericRelation to - # ChildTag, then we need to generate a join from TaggedItem to Tag - # (as Tag.object_id == TaggedItem.pk), and another join from Tag to - # ChildTag (as that is where the relation is to). Do this by first - # generating a join to the parent model, then generating joins to the - # child models. - path = [] opts = self.remote_field.model._meta.concrete_model._meta parent_opts = opts.get_field(self.object_id_field_name).model._meta target = parent_opts.pk - path.append( + path = [ PathInfo( from_opts=self.model._meta, to_opts=parent_opts, @@ -415,7 +406,7 @@ def _get_path_info_with_parent(self, filtered_relation): direct=False, filtered_relation=filtered_relation, ) - ) + ] # Collect joins needed for the parent -> child chain. This is easiest # to do if we collect joins for the child -> parent chain and then # reverse the direction (call to reverse() and use of @@ -435,19 +426,18 @@ def get_path_info(self, filtered_relation=None): object_id_field = opts.get_field(self.object_id_field_name) if object_id_field.model != opts.model: return self._get_path_info_with_parent(filtered_relation) - else: - target = opts.pk - return [ - PathInfo( - from_opts=self.model._meta, - to_opts=opts, - target_fields=(target,), - join_field=self.remote_field, - m2m=True, - direct=False, - filtered_relation=filtered_relation, - ) - ] + target = opts.pk + return [ + PathInfo( + from_opts=self.model._meta, + to_opts=opts, + target_fields=(target,), + join_field=self.remote_field, + m2m=True, + direct=False, + filtered_relation=filtered_relation, + ) + ] def get_reverse_path_info(self, filtered_relation=None): opts = self.model._meta @@ -523,11 +513,14 @@ def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS): """ return self.remote_field.model._base_manager.db_manager(using).filter( **{ - "%s__pk" - % self.content_type_field_name: ContentType.objects.db_manager(using) - .get_for_model(self.model, for_concrete_model=self.for_concrete_model) + f"{self.content_type_field_name}__pk": ContentType.objects.db_manager( + using + ) + .get_for_model( + self.model, for_concrete_model=self.for_concrete_model + ) .pk, - "%s__in" % self.object_id_field_name: [obj.pk for obj in objs], + f"{self.object_id_field_name}__in": [obj.pk for obj in objs], } ) @@ -560,6 +553,8 @@ def create_generic_related_manager(superclass, rel): specific to generic relations. """ + + class GenericRelatedObjectManager(superclass): def __init__(self, instance=None): super().__init__() @@ -578,7 +573,7 @@ def __init__(self, instance=None): self.pk_val = instance.pk self.core_filters = { - "%s__pk" % self.content_type_field_name: self.content_type.id, + f"{self.content_type_field_name}__pk": self.content_type.id, self.object_id_field_name: self.pk_val, } @@ -633,7 +628,7 @@ def get_prefetch_queryset(self, instances, queryset=None): # We (possibly) need to convert object IDs to the type of the # instances' PK in order to match up instances: object_id_converter = instances[0]._meta.pk.to_python - content_type_id_field_name = "%s_id" % self.content_type_field_name + content_type_id_field_name = f"{self.content_type_field_name}_id" return ( queryset.filter(query), lambda relobj: ( @@ -760,4 +755,5 @@ def update_or_create(self, **kwargs): update_or_create.alters_data = True + return GenericRelatedObjectManager diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/forms.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/forms.py index c0ff4f72..bc4d2228 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/forms.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/forms.py @@ -19,17 +19,9 @@ def __init__( queryset=None, **kwargs, ): - opts = self.model._meta self.instance = instance - self.rel_name = ( - opts.app_label - + "-" - + opts.model_name - + "-" - + self.ct_field.name - + "-" - + self.ct_fk_field.name - ) + opts = self.model._meta + self.rel_name = f"{opts.app_label}-{opts.model_name}-{self.ct_field.name}-{self.ct_fk_field.name}" self.save_as_new = save_as_new if self.instance is None or self.instance.pk is None: qs = self.model._default_manager.none() @@ -47,9 +39,7 @@ def __init__( super().__init__(queryset=qs, data=data, files=files, prefix=prefix, **kwargs) def initial_form_count(self): - if self.save_as_new: - return 0 - return super().initial_form_count() + return 0 if self.save_as_new else super().initial_form_count() @classmethod def get_default_prefix(cls): @@ -107,7 +97,7 @@ def generic_inlineformset_factory( not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType ): - raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) + raise Exception(f"fk_name '{ct_field}' is not a ForeignKey to ContentType") fk_field = opts.get_field(fk_field) # let the exception propagate exclude = [*(exclude or []), ct_field.name, fk_field.name] FormSet = modelformset_factory( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/__init__.py index 903b9ab1..5c1c476d 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/__init__.py @@ -65,14 +65,10 @@ def inject_rename_contenttypes_operations( for migration, backward in plan: if (migration.app_label, migration.name) == ("contenttypes", "0001_initial"): - # There's no point in going forward if the initial contenttypes - # migration is unapplied as the ContentType model will be - # unavailable from this point. if backward: break - else: - available = True - continue + available = True + continue # The ContentType model is not available yet. if not available: continue @@ -142,4 +138,4 @@ def create_contenttypes( ContentType.objects.using(using).bulk_create(cts) if verbosity >= 2: for ct in cts: - print("Adding content type '%s | %s'" % (ct.app_label, ct.model)) + print(f"Adding content type '{ct.app_label} | {ct.model}'") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py index aa42d019..a2bcd345 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py @@ -55,21 +55,15 @@ def handle(self, **options): if interactive: ct_info = [] for ct in to_remove: - ct_info.append( - " - Content type for %s.%s" % (ct.app_label, ct.model) - ) + ct_info.append(f" - Content type for {ct.app_label}.{ct.model}") collector = NoFastDeleteCollector(using=using) collector.collect([ct]) - for obj_type, objs in collector.data.items(): - if objs != {ct}: - ct_info.append( - " - %s %s object(s)" - % ( - len(objs), - obj_type._meta.label, - ) - ) + ct_info.extend( + f" - {len(objs)} {obj_type._meta.label} object(s)" + for obj_type, objs in collector.data.items() + if objs != {ct} + ) content_type_display = "\n".join(ct_info) self.stdout.write( """Some content types in your database are stale and can be deleted. @@ -92,14 +86,10 @@ def handle(self, **options): if ok_to_delete == "yes": for ct in to_remove: if verbosity >= 2: - self.stdout.write( - "Deleting stale content type '%s | %s'" - % (ct.app_label, ct.model) - ) + self.stdout.write(f"Deleting stale content type '{ct.app_label} | {ct.model}'") ct.delete() - else: - if verbosity >= 2: - self.stdout.write("Stale content types remain.") + elif verbosity >= 2: + self.stdout.write("Stale content types remain.") class NoFastDeleteCollector(Collector): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/models.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/models.py index ef4f3055..c573b919 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/models.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/models.py @@ -145,16 +145,16 @@ def __str__(self): @property def name(self): model = self.model_class() - if not model: - return self.model - return str(model._meta.verbose_name) + return str(model._meta.verbose_name) if model else self.model @property def app_labeled_name(self): model = self.model_class() - if not model: - return self.model - return "%s | %s" % (model._meta.app_label, model._meta.verbose_name) + return ( + f"{model._meta.app_label} | {model._meta.verbose_name}" + if model + else self.model + ) def model_class(self): """Return the model class for this type of content.""" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/views.py index bfde73c5..f633d56b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/contenttypes/views.py @@ -60,10 +60,7 @@ def shortcut(request, content_type_id, object_id): # The current site's domain matches a site attached to the # object. break - # Caveat: In the case of multiple related Sites, this just - # selects the *first* one, which is arbitrary. - site = site_qs.first() - if site: + if site := site_qs.first(): object_domain = site.domain break else: @@ -79,10 +76,7 @@ def shortcut(request, content_type_id, object_id): object_domain = site.domain break - # If all that malarkey found an object domain, use it. Otherwise, fall back - # to whatever get_absolute_url() returned. - if object_domain is not None: - protocol = request.scheme - return HttpResponseRedirect("%s://%s%s" % (protocol, object_domain, absurl)) - else: + if object_domain is None: return HttpResponseRedirect(absurl) + protocol = request.scheme + return HttpResponseRedirect(f"{protocol}://{object_domain}{absurl}") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/models.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/models.py index d001cd18..a8c94455 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/models.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/models.py @@ -35,7 +35,7 @@ class Meta: ordering = ["url"] def __str__(self): - return "%s -- %s" % (self.url, self.title) + return f"{self.url} -- {self.title}" def get_absolute_url(self): from .views import flatpage diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/templatetags/flatpages.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/templatetags/flatpages.py index 9ec6b880..138cd1d4 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/templatetags/flatpages.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/templatetags/flatpages.py @@ -9,14 +9,8 @@ class FlatpageNode(template.Node): def __init__(self, context_name, starts_with=None, user=None): self.context_name = context_name - if starts_with: - self.starts_with = template.Variable(starts_with) - else: - self.starts_with = None - if user: - self.user = template.Variable(user) - else: - self.user = None + self.starts_with = template.Variable(starts_with) if starts_with else None + self.user = template.Variable(user) if user else None def render(self, context): if "request" in context: @@ -75,27 +69,21 @@ def get_flatpages(parser, token): "%(tag_name)s expects a syntax of %(tag_name)s " "['url_starts_with'] [for user] as context_name" % {"tag_name": bits[0]} ) - # Must have at 3-6 bits in the tag - if 3 <= len(bits) <= 6: + if not 3 <= len(bits) <= 6: + raise template.TemplateSyntaxError(syntax_message) # If there's an even number of bits, there's no prefix - if len(bits) % 2 == 0: - prefix = bits[1] - else: - prefix = None + prefix = bits[1] if len(bits) % 2 == 0 else None + # The very last bit must be the context name + if bits[-2] != "as": + raise template.TemplateSyntaxError(syntax_message) + context_name = bits[-1] - # The very last bit must be the context name - if bits[-2] != "as": + # If there are 5 or 6 bits, there is a user defined + if len(bits) >= 5: + if bits[-4] != "for": raise template.TemplateSyntaxError(syntax_message) - context_name = bits[-1] - - # If there are 5 or 6 bits, there is a user defined - if len(bits) >= 5: - if bits[-4] != "for": - raise template.TemplateSyntaxError(syntax_message) - user = bits[-3] - else: - user = None - - return FlatpageNode(context_name, starts_with=prefix, user=user) + user = bits[-3] else: - raise template.TemplateSyntaxError(syntax_message) + user = None + + return FlatpageNode(context_name, starts_with=prefix, user=user) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/views.py index 776f1796..bb2469e2 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/flatpages/views.py @@ -31,7 +31,7 @@ def flatpage(request, url): `flatpages.flatpages` object """ if not url.startswith("/"): - url = "/" + url + url = f"/{url}" site_id = get_current_site(request).id try: f = get_object_or_404(FlatPage, url=url, sites=site_id) @@ -39,7 +39,7 @@ def flatpage(request, url): if not url.endswith("/") and settings.APPEND_SLASH: url += "/" f = get_object_or_404(FlatPage, url=url, sites=site_id) - return HttpResponsePermanentRedirect("%s/" % request.path) + return HttpResponsePermanentRedirect(f"{request.path}/") else: raise return render_flatpage(request, f) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/options.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/options.py index 9eb6af63..dbbdcee3 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/options.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/options.py @@ -14,13 +14,14 @@ class GeoModelAdminMixin: gis_widget_kwargs = {} def formfield_for_dbfield(self, db_field, request, **kwargs): - if isinstance(db_field, models.GeometryField) and ( - db_field.dim < 3 or self.gis_widget.supports_3d + if ( + not isinstance(db_field, models.GeometryField) + or db_field.dim >= 3 + and not self.gis_widget.supports_3d ): - kwargs["widget"] = self.gis_widget(**self.gis_widget_kwargs) - return db_field.formfield(**kwargs) - else: return super().formfield_for_dbfield(db_field, request, **kwargs) + kwargs["widget"] = self.gis_widget(**self.gis_widget_kwargs) + return db_field.formfield(**kwargs) class GISModelAdmin(GeoModelAdminMixin, ModelAdmin): @@ -93,12 +94,11 @@ def formfield_for_dbfield(self, db_field, request, **kwargs): for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing). """ - if isinstance(db_field, models.GeometryField) and db_field.dim < 3: - # Setting the widget with the newly defined widget. - kwargs["widget"] = self.get_map_widget(db_field) - return db_field.formfield(**kwargs) - else: + if not isinstance(db_field, models.GeometryField) or db_field.dim >= 3: return super().formfield_for_dbfield(db_field, request, **kwargs) + # Setting the widget with the newly defined widget. + kwargs["widget"] = self.get_map_widget(db_field) + return db_field.formfield(**kwargs) def get_map_widget(self, db_field): """ @@ -120,6 +120,8 @@ def get_map_widget(self, db_field): else: collection_type = "None" + + class OLMap(self.widget): template_name = self.map_template geom_type = db_field.geom_type @@ -127,7 +129,7 @@ class OLMap(self.widget): wms_options = "" if self.wms_options: wms_options = ["%s: '%s'" % pair for pair in self.wms_options.items()] - wms_options = ", %s" % ", ".join(wms_options) + wms_options = f', {", ".join(wms_options)}' params = { "default_lon": self.default_lon, @@ -166,6 +168,7 @@ class OLMap(self.widget): "debug": self.debug, } + return OLMap diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/widgets.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/widgets.py index 420c1706..b7724470 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/widgets.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/admin/widgets.py @@ -55,7 +55,7 @@ def get_context(self, name, value, attrs): # note: we must switch out dashes for underscores since js # functions are created using the module variable js_safe_name = self.params["name"].replace("-", "_") - self.params["module"] = "geodjango_%s" % js_safe_name + self.params["module"] = f"geodjango_{js_safe_name}" if value: # Transforming the geometry to the projection used on the @@ -88,10 +88,10 @@ def map_options(self): """Build the map options hash for the OpenLayers template.""" # JavaScript construction utilities for the Bounds and Projection. def ol_bounds(extent): - return "new OpenLayers.Bounds(%s)" % extent + return f"new OpenLayers.Bounds({extent})" def ol_projection(srid): - return 'new OpenLayers.Projection("EPSG:%s")' % srid + return f'new OpenLayers.Projection("EPSG:{srid}")' # An array of the parameter name, the name of their OpenLayers # counterpart, and the type of variable they are. @@ -117,7 +117,7 @@ def ol_projection(srid): elif option_type in (float, int): value = self.params[param_name] elif option_type in (str,): - value = '"%s"' % self.params[param_name] + value = f'"{self.params[param_name]}"' else: raise TypeError map_options[js_name] = value diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/features.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/features.py index cc4ce104..44566a10 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/features.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/features.py @@ -104,8 +104,7 @@ def supports_union_aggr(self): return models.Union not in self.connection.ops.disallowed_aggregates def __getattr__(self, name): - m = re.match(r"has_(\w*)_function$", name) - if m: + if m := re.match(r"has_(\w*)_function$", name): func_name = m[1] return func_name not in self.connection.ops.unsupported_functions raise AttributeError diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/models.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/models.py index 589c872d..f4f0ead4 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/models.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/models.py @@ -12,30 +12,28 @@ def srs(self): """ Return a GDAL SpatialReference object. """ - # TODO: Is caching really necessary here? Is complexity worth it? if hasattr(self, "_srs"): # Returning a clone of the cached SpatialReference object. return self._srs.clone() - else: - # Attempting to cache a SpatialReference object. - - # Trying to get from WKT first. - try: - self._srs = gdal.SpatialReference(self.wkt) - return self.srs - except Exception as e: - msg = e - - try: - self._srs = gdal.SpatialReference(self.proj4text) - return self.srs - except Exception as e: - msg = e - - raise Exception( - "Could not get OSR SpatialReference from WKT: %s\nError:\n%s" - % (self.wkt, msg) - ) + # Attempting to cache a SpatialReference object. + + # Trying to get from WKT first. + try: + self._srs = gdal.SpatialReference(self.wkt) + return self.srs + except Exception as e: + msg = e + + try: + self._srs = gdal.SpatialReference(self.proj4text) + return self.srs + except Exception as e: + msg = e + + raise Exception( + "Could not get OSR SpatialReference from WKT: %s\nError:\n%s" + % (self.wkt, msg) + ) @property def ellipsoid(self): @@ -125,13 +123,13 @@ def get_spheroid(cls, wkt, string=True): if not string: return sphere_name, sphere_params - else: # `string` parameter used to place in format acceptable by PostGIS - if len(sphere_params) == 3: - radius, flattening = sphere_params[0], sphere_params[2] - else: - radius, flattening = sphere_params - return 'SPHEROID["%s",%s,%s]' % (sphere_name, radius, flattening) + radius, flattening = ( + (sphere_params[0], sphere_params[2]) + if len(sphere_params) == 3 + else sphere_params + ) + return f'SPHEROID["{sphere_name}",{radius},{flattening}]' def __str__(self): """ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/operations.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/operations.py index e7bffb11..ba270e20 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/operations.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/operations.py @@ -83,7 +83,7 @@ def convert_extent3d(self, box, srid): # For quoting column values, rather than columns. def geo_quote_name(self, name): - return "'%s'" % name + return f"'{name}'" # GeometryField operations def geo_db_type(self, f): @@ -138,8 +138,7 @@ def transform_value(value, field): def check_expression_support(self, expression): if isinstance(expression, self.disallowed_aggregates): raise NotSupportedError( - "%s spatial aggregation is not supported by this database backend." - % expression.name + f"{expression.name} spatial aggregation is not supported by this database backend." ) super().check_expression_support(expression) @@ -151,7 +150,7 @@ def spatial_aggregate_name(self, agg_name): def spatial_function_name(self, func_name): if func_name in self.unsupported_functions: raise NotSupportedError( - "This backend doesn't support the %s function." % func_name + f"This backend doesn't support the {func_name} function." ) return self.function_names.get(func_name, self.geom_func_prefix + func_name) @@ -186,21 +185,18 @@ def get_area_att_for_field(self, field): if field.geodetic(self.connection): if self.connection.features.supports_area_geodetic: return "sq_m" - raise NotImplementedError( - "Area on geodetic coordinate systems not supported." - ) - else: - units_name = field.units_name(self.connection) - if units_name: - return AreaMeasure.unit_attname(units_name) + else: + raise NotImplementedError( + "Area on geodetic coordinate systems not supported." + ) + elif units_name := field.units_name(self.connection): + return AreaMeasure.unit_attname(units_name) def get_distance_att_for_field(self, field): dist_att = None if field.geodetic(self.connection): if self.connection.features.supports_distance_geodetic: dist_att = "m" - else: - units = field.units_name(self.connection) - if units: - dist_att = DistanceMeasure.unit_attname(units) + elif units := field.units_name(self.connection): + dist_att = DistanceMeasure.unit_attname(units) return dist_att diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/introspection.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/introspection.py index 3561869a..ca8f1066 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/introspection.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/introspection.py @@ -14,7 +14,7 @@ def get_geometry_type(self, table_name, description): with self.connection.cursor() as cursor: # In order to get the specific geometry type of the field, # we introspect on the table definition using `DESCRIBE`. - cursor.execute("DESCRIBE %s" % self.connection.ops.quote_name(table_name)) + cursor.execute(f"DESCRIBE {self.connection.ops.quote_name(table_name)}") # Increment over description info until we get to the geometry # column. for column, typ, null, key, default, extra in cursor.fetchall(): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/operations.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/operations.py index 728e93ad..86ac2a84 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/operations.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/operations.py @@ -25,11 +25,11 @@ def mysql(self): @cached_property def select(self): - return self.geom_func_prefix + "AsBinary(%s)" + return f"{self.geom_func_prefix}AsBinary(%s)" @cached_property def from_text(self): - return self.geom_func_prefix + "GeomFromText" + return f"{self.geom_func_prefix}GeomFromText" @cached_property def gis_operators(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/schema.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/schema.py index 28f7048f..1fdc41d4 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/schema.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/mysql/schema.py @@ -68,7 +68,7 @@ def remove_field(self, model, field): super().remove_field(model, field) def _create_spatial_index_name(self, model, field): - return "%s_%s_id" % (model._meta.db_table, field.column) + return f"{model._meta.db_table}_{field.column}_id" def create_spatial_indexes(self): for sql in self.geometry_sql: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/introspection.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/introspection.py index 096fee54..58f46841 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/introspection.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/introspection.py @@ -27,17 +27,15 @@ def get_geometry_type(self, table_name, description): row = cursor.fetchone() except Exception as exc: raise Exception( - "Could not find entry in USER_SDO_GEOM_METADATA " - 'corresponding to "%s"."%s"' % (table_name, description.name) + f'Could not find entry in USER_SDO_GEOM_METADATA corresponding to "{table_name}"."{description.name}"' ) from exc # TODO: Research way to find a more specific geometry field type for # the column's contents. field_type = "GeometryField" - # Getting the field parameters. - field_params = {} dim, srid = row + field_params = {} if srid != 4326: field_params["srid"] = srid # Size of object array (SDO_DIM_ARRAY) is number of dimensions. diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/models.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/models.py index f06f7314..3c52b0d1 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/models.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/models.py @@ -24,7 +24,7 @@ class Meta: managed = False def __str__(self): - return "%s - %s (SRID: %s)" % (self.table_name, self.column_name, self.srid) + return f"{self.table_name} - {self.column_name} (SRID: {self.srid})" @classmethod def table_name_col(cls): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/operations.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/operations.py index ba7e3ca4..f0577817 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/operations.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/operations.py @@ -46,7 +46,7 @@ def check_relate_argument(self, arg): ) mask_regex = re.compile(r"^(%s)(\+(%s))*$" % (masks, masks), re.I) if not isinstance(arg, str) or not mask_regex.match(arg): - raise ValueError('Invalid SDO_RELATE mask: "%s"' % arg) + raise ValueError(f'Invalid SDO_RELATE mask: "{arg}"') def as_sql(self, connection, lookup, template_params, sql_params): template_params["mask"] = sql_params[-1] @@ -134,28 +134,25 @@ def geo_quote_name(self, name): return super().geo_quote_name(name).upper() def convert_extent(self, clob): - if clob: - # Generally, Oracle returns a polygon for the extent -- however, - # it can return a single point if there's only one Point in the - # table. - ext_geom = GEOSGeometry(memoryview(clob.read())) - gtype = str(ext_geom.geom_type) - if gtype == "Polygon": - # Construct the 4-tuple from the coordinates in the polygon. - shell = ext_geom.shell - ll, ur = shell[0][:2], shell[2][:2] - elif gtype == "Point": - ll = ext_geom.coords[:2] - ur = ll - else: - raise Exception( - "Unexpected geometry type returned for extent: %s" % gtype - ) - xmin, ymin = ll - xmax, ymax = ur - return (xmin, ymin, xmax, ymax) - else: + if not clob: return None + # Generally, Oracle returns a polygon for the extent -- however, + # it can return a single point if there's only one Point in the + # table. + ext_geom = GEOSGeometry(memoryview(clob.read())) + gtype = str(ext_geom.geom_type) + if gtype == "Point": + ll = ext_geom.coords[:2] + ur = ll + elif gtype == "Polygon": + # Construct the 4-tuple from the coordinates in the polygon. + shell = ext_geom.shell + ll, ur = shell[0][:2], shell[2][:2] + else: + raise Exception(f"Unexpected geometry type returned for extent: {gtype}") + xmin, ymin = ll + xmax, ymax = ur + return (xmin, ymin, xmax, ymax) def geo_db_type(self, f): """ @@ -188,7 +185,7 @@ def get_distance(self, f, value, lookup_type): # dwithin lookups on Oracle require a special string parameter # that starts with "distance=". if lookup_type == "dwithin": - dist_param = "distance=%s" % dist_param + dist_param = f"distance={dist_param}" return [dist_param] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/schema.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/schema.py index d8fdd534..70f20a40 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/schema.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/oracle/schema.py @@ -112,5 +112,5 @@ def _create_spatial_index_name(self, model, field): # Oracle doesn't allow object names > 30 characters. Use this scheme # instead of self._create_index_name() for backwards compatibility. return truncate_name( - "%s_%s_id" % (strip_quotes(model._meta.db_table), field.column), 30 + f"{strip_quotes(model._meta.db_table)}_{field.column}_id", 30 ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/adapter.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/adapter.py index 50e6c946..9d95bcfe 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/adapter.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/adapter.py @@ -62,10 +62,7 @@ def getquoted(self): """ if self.is_geometry: # Psycopg will figure out whether to use E'\\000' or '\000'. - return "%s(%s)" % ( - "ST_GeogFromWKB" if self.geography else "ST_GeomFromEWKB", - self._adapter.getquoted().decode(), - ) + return f'{"ST_GeogFromWKB" if self.geography else "ST_GeomFromEWKB"}({self._adapter.getquoted().decode()})' else: # For rasters, add explicit type cast to WKB string. - return "'%s'::raster" % self.ewkb + return f"'{self.ewkb}'::raster" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/introspection.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/introspection.py index 766c0fa5..bc487c65 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/introspection.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/introspection.py @@ -53,8 +53,7 @@ def get_geometry_type(self, table_name, description): row = cursor.fetchone() if not row: raise Exception( - 'Could not find a geometry or geography column for "%s"."%s"' - % (table_name, description.name) + f'Could not find a geometry or geography column for "{table_name}"."{description.name}"' ) dim, srid, field_type = row # OGRGeomType does not require GDAL and makes it easy to convert diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/operations.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/operations.py index 36bec4ba..418eab92 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/operations.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/operations.py @@ -59,10 +59,7 @@ def check_raster(self, lookup, template_params): "Band indices are not allowed for this operator, it works on bbox " "only." ) - template_params["lhs"] = "%s, %s" % ( - template_params["lhs"], - lookup.band_lhs, - ) + template_params["lhs"] = f'{template_params["lhs"]}, {lookup.band_lhs}' if lookup.band_rhs is not None and rhs_is_raster: if not self.func: @@ -70,25 +67,22 @@ def check_raster(self, lookup, template_params): "Band indices are not allowed for this operator, it works on bbox " "only." ) - template_params["rhs"] = "%s, %s" % ( - template_params["rhs"], - lookup.band_rhs, - ) + template_params["rhs"] = f'{template_params["rhs"]}, {lookup.band_rhs}' # Convert rasters to polygons if necessary. if not self.raster or spheroid: # Operators without raster support. if lhs_is_raster: - template_params["lhs"] = "ST_Polygon(%s)" % template_params["lhs"] + template_params["lhs"] = f'ST_Polygon({template_params["lhs"]})' if rhs_is_raster: - template_params["rhs"] = "ST_Polygon(%s)" % template_params["rhs"] + template_params["rhs"] = f'ST_Polygon({template_params["rhs"]})' elif self.raster == BILATERAL: # Operators with raster support but don't support mixed (rast-geom) # lookups. if lhs_is_raster and not rhs_is_raster: - template_params["lhs"] = "ST_Polygon(%s)" % template_params["lhs"] + template_params["lhs"] = f'ST_Polygon({template_params["lhs"]})' elif rhs_is_raster and not lhs_is_raster: - template_params["rhs"] = "ST_Polygon(%s)" % template_params["rhs"] + template_params["rhs"] = f'ST_Polygon({template_params["rhs"]})' return template_params @@ -179,32 +173,20 @@ def function_names(self): @cached_property def spatial_version(self): """Determine the version of the PostGIS library.""" - # Trying to get the PostGIS version because the function - # signatures will depend on the version used. The cost - # here is a database query to determine the version, which - # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple - # comprising user-supplied values for the major, minor, and - # subminor revision of PostGIS. if hasattr(settings, "POSTGIS_VERSION"): - version = settings.POSTGIS_VERSION - else: - # Run a basic query to check the status of the connection so we're - # sure we only raise the error below if the problem comes from - # PostGIS and not from PostgreSQL itself (see #24862). - self._get_postgis_func("version") - - try: - vtup = self.postgis_version_tuple() - except ProgrammingError: - raise ImproperlyConfigured( - 'Cannot determine PostGIS version for database "%s" ' - 'using command "SELECT postgis_lib_version()". ' - "GeoDjango requires at least PostGIS version 2.4. " - "Was the database created from a spatial database " - "template?" % self.connection.settings_dict["NAME"] - ) - version = vtup[1:] - return version + return settings.POSTGIS_VERSION + # Run a basic query to check the status of the connection so we're + # sure we only raise the error below if the problem comes from + # PostGIS and not from PostgreSQL itself (see #24862). + self._get_postgis_func("version") + + try: + vtup = self.postgis_version_tuple() + except ProgrammingError: + raise ImproperlyConfigured( + f'Cannot determine PostGIS version for database "{self.connection.settings_dict["NAME"]}" using command "SELECT postgis_lib_version()". GeoDjango requires at least PostGIS version 2.4. Was the database created from a spatial database template?' + ) + return vtup[1:] def convert_extent(self, box): """ @@ -241,19 +223,15 @@ def geo_db_type(self, f): # Type-based geometries. # TODO: Support 'M' extension. - if f.dim == 3: - geom_type = f.geom_type + "Z" - else: - geom_type = f.geom_type - if f.geography: - if f.srid != 4326: - raise NotSupportedError( - "PostGIS only supports geography columns with an SRID of 4326." - ) - - return "geography(%s,%d)" % (geom_type, f.srid) - else: + geom_type = f"{f.geom_type}Z" if f.dim == 3 else f.geom_type + if not f.geography: return "geometry(%s,%d)" % (geom_type, f.srid) + if f.srid != 4326: + raise NotSupportedError( + "PostGIS only supports geography columns with an SRID of 4326." + ) + + return "geography(%s,%d)" % (geom_type, f.srid) def get_distance(self, f, dist_val, lookup_type): """ @@ -270,17 +248,15 @@ def get_distance(self, f, dist_val, lookup_type): # Shorthand boolean flags. geodetic = f.geodetic(self.connection) - geography = f.geography - if isinstance(value, Distance): - if geography: - dist_param = value.m - elif geodetic: - if lookup_type == "dwithin": - raise ValueError( - "Only numeric values of degree units are " - "allowed on geographic DWithin queries." - ) + geography = f.geography + + if not geography and geodetic and lookup_type == "dwithin": + raise ValueError( + "Only numeric values of degree units are " + "allowed on geographic DWithin queries." + ) + elif not geography and geodetic or geography: dist_param = value.m else: dist_param = getattr( @@ -300,26 +276,18 @@ def get_geom_placeholder(self, f, value, compiler): """ transform_func = self.spatial_function_name("Transform") if hasattr(value, "as_sql"): - if value.field.srid == f.srid: - placeholder = "%s" - else: - placeholder = "%s(%%s, %s)" % (transform_func, f.srid) - return placeholder - + return ( + "%s" + if value.field.srid == f.srid + else "%s(%%s, %s)" % (transform_func, f.srid) + ) # Get the srid for this object - if value is None: - value_srid = None - else: - value_srid = value.srid - - # Adding Transform() to the SQL placeholder if the value srid - # is not equal to the field srid. - if value_srid is None or value_srid == f.srid: - placeholder = "%s" - else: - placeholder = "%s(%%s, %s)" % (transform_func, f.srid) - - return placeholder + value_srid = None if value is None else value.srid + return ( + "%s" + if value_srid is None or value_srid == f.srid + else "%s(%%s, %s)" % (transform_func, f.srid) + ) def _get_postgis_func(self, func): """ @@ -327,7 +295,7 @@ def _get_postgis_func(self, func): """ # Close out the connection. See #9437. with self.connection.temporary_connection() as cursor: - cursor.execute("SELECT %s()" % func) + cursor.execute(f"SELECT {func}()") return cursor.fetchone()[0] def postgis_geos_version(self): @@ -365,8 +333,7 @@ def proj_version_tuple(self): """ proj_regex = re.compile(r"(\d+)\.(\d+)\.(\d+)") proj_ver_str = self.postgis_proj_version() - m = proj_regex.search(proj_ver_str) - if m: + if m := proj_regex.search(proj_ver_str): return tuple(map(int, m.groups())) else: raise Exception("Could not determine PROJ version from PostGIS.") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/pgraster.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/pgraster.py index 22794342..252ca10e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/pgraster.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/pgraster.py @@ -17,14 +17,14 @@ def pack(structure, data): """ Pack data into hex string with little endian format. """ - return struct.pack("<" + structure, *data) + return struct.pack(f"<{structure}", *data) def unpack(structure, data): """ Unpack little endian hexlified binary string into a list. """ - return struct.unpack("<" + structure, bytes.fromhex(data)) + return struct.unpack(f"<{structure}", bytes.fromhex(data)) def chunk(data, index): @@ -134,7 +134,7 @@ def to_pgraster(rast): # For example, if the byte value is 71, then the datatype is # 71 & ~BANDTYPE_FLAG_HASNODATA = 7 (32BSI) # and the nodata value is True. - structure = "B" + GDAL_TO_STRUCT[band.datatype()] + structure = f"B{GDAL_TO_STRUCT[band.datatype()]}" # Get band pixel type in PostGIS notation pixeltype = GDAL_TO_POSTGIS[band.datatype()] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/schema.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/schema.py index 77a9096e..431d9e18 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/schema.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/schema.py @@ -45,7 +45,7 @@ def _create_index_sql(self, model, *, fields=None, **kwargs): model, fields=fields, name=name, - using=" USING %s" % self.geom_index_type, + using=f" USING {self.geom_index_type}", opclasses=opclasses, expressions=expressions, ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/introspection.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/introspection.py index 8d0003fd..7159c35d 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/introspection.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/introspection.py @@ -38,8 +38,7 @@ def get_geometry_type(self, table_name, description): row = cursor.fetchone() if not row: raise Exception( - 'Could not find a geometry column for "%s"."%s"' - % (table_name, description.name) + f'Could not find a geometry column for "{table_name}"."{description.name}"' ) # OGRGeomType does not require GDAL and makes it easy to convert @@ -71,7 +70,7 @@ def get_constraints(self, cursor, table_name): (table_name,), ) for row in cursor.fetchall(): - constraints["%s__spatial__index" % row[0]] = { + constraints[f"{row[0]}__spatial__index"] = { "columns": [row[0]], "primary_key": False, "unique": False, diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/operations.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/operations.py index 8003fcb6..b06506f6 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/operations.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/operations.py @@ -18,7 +18,7 @@ class SpatialiteNullCheckOperator(SpatialOperator): def as_sql(self, connection, lookup, template_params, sql_params): sql, params = super().as_sql(connection, lookup, template_params, sql_params) - return "%s > 0" % sql, params + return f"{sql} > 0", params class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): @@ -148,7 +148,7 @@ def _get_spatialite_func(self, func): """ cursor = self.connection._cursor() try: - cursor.execute("SELECT %s" % func) + cursor.execute(f"SELECT {func}") row = cursor.fetchone() finally: cursor.close() diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/schema.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/schema.py index d37632ed..7a29d533 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/schema.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/spatialite/schema.py @@ -179,13 +179,15 @@ def alter_db_table( ) if getattr(field, "spatial_index", False): self.execute( - self.sql_rename_table - % { - "old_table": self.quote_name( - "idx_%s_%s" % (old_db_table, field.column) - ), - "new_table": self.quote_name( - "idx_%s_%s" % (new_db_table, field.column) - ), - } + ( + self.sql_rename_table + % { + "old_table": self.quote_name( + f"idx_{old_db_table}_{field.column}" + ), + "new_table": self.quote_name( + f"idx_{new_db_table}_{field.column}" + ), + } + ) ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/utils.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/utils.py index ffb74200..24b299b1 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/utils.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/backends/utils.py @@ -17,10 +17,7 @@ def __init__(self, op=None, func=None): @property def default_template(self): - if self.func: - return "%(func)s(%(lhs)s, %(rhs)s)" - else: - return "%(lhs)s %(op)s %(rhs)s" + return "%(func)s(%(lhs)s, %(rhs)s)" if self.func else "%(lhs)s %(op)s %(rhs)s" def as_sql(self, connection, lookup, template_params, sql_params): sql_template = self.sql_template or lookup.sql_template or self.default_template diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/fields.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/fields.py index 889c1cfe..2732fc27 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/fields.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/fields.py @@ -61,8 +61,7 @@ def get_srid_info(srid, connection): _srid_cache[alias][srid] = SRIDCacheEntry( units=units, units_name=units_name, - spheroid='SPHEROID["%s",%s,%s]' - % (srs["spheroid"], srs.semi_major, srs.inverse_flattening), + spheroid=f'SPHEROID["{srs["spheroid"]}",{srs.semi_major},{srs.inverse_flattening}]', geodetic=srs.geographic, ) @@ -152,10 +151,7 @@ def get_srid(self, obj): returned. """ srid = obj.srid # SRID of given geometry. - if srid is None or self.srid == -1 or (srid == -1 and self.srid != -1): - return self.srid - else: - return srid + return self.srid if srid is None or self.srid == -1 or srid == -1 else srid def get_db_prep_value(self, value, connection, *args, **kwargs): if value is None: @@ -185,7 +181,7 @@ def get_raster_prep_value(self, value, is_candidate): return gdal.GDALRaster(value) except GDALException: raise ValueError( - "Couldn't create spatial object from lookup value '%s'." % value + f"Couldn't create spatial object from lookup value '{value}'." ) def get_prep_value(self, value): @@ -194,29 +190,21 @@ def get_prep_value(self, value): return None # When the input is not a geometry or raster, attempt to construct one # from the given string input. - if isinstance(obj, GEOSGeometry): - pass - else: + if not isinstance(obj, GEOSGeometry): # Check if input is a candidate for conversion to raster or geometry. is_candidate = isinstance(obj, (bytes, str)) or hasattr( obj, "__geo_interface__" ) - # Try to convert the input to raster. - raster = self.get_raster_prep_value(obj, is_candidate) - - if raster: + if raster := self.get_raster_prep_value(obj, is_candidate): obj = raster elif is_candidate: try: obj = GEOSGeometry(obj) except (GEOSException, GDALException): - raise ValueError( - "Couldn't create spatial object from lookup value '%s'." % obj - ) + raise ValueError(f"Couldn't create spatial object from lookup value '{obj}'.") else: raise ValueError( - "Cannot use object with type %s for a spatial lookup parameter." - % type(obj).__name__ + f"Cannot use object with type {type(obj).__name__} for a spatial lookup parameter." ) # Assigning the SRID value. @@ -319,9 +307,11 @@ def select_format(self, compiler, sql, params): of the spatial backend. For example, Oracle and MySQL require custom selection formats in order to retrieve geometries in OGC WKB. """ - if not compiler.query.subquery: - return compiler.connection.ops.select % sql, params - return sql, params + return ( + (sql, params) + if compiler.query.subquery + else (compiler.connection.ops.select % sql, params) + ) # The OpenGIS Geometry Type Fields diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/functions.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/functions.py index 5f6c7b5c..626a468b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/functions.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/functions.py @@ -76,12 +76,7 @@ def resolve_expression(self, *args, **kwargs): field = source_fields[pos] if not isinstance(field, GeometryField): raise TypeError( - "%s function requires a GeometryField in position %s, got %s." - % ( - self.name, - pos + 1, - type(field).__name__, - ) + f"{self.name} function requires a GeometryField in position {pos + 1}, got {type(field).__name__}." ) base_srid = res.geo_field.srid @@ -96,12 +91,14 @@ def resolve_expression(self, *args, **kwargs): return res def _handle_param(self, value, param_name="", check_types=None): - if not hasattr(value, "resolve_expression"): - if check_types and not isinstance(value, check_types): - raise TypeError( - "The %s parameter has the wrong type: should be %s." - % (param_name, check_types) - ) + if ( + not hasattr(value, "resolve_expression") + and check_types + and not isinstance(value, check_types) + ): + raise TypeError( + f"The {param_name} parameter has the wrong type: should be {check_types}." + ) return value @@ -388,7 +385,7 @@ class IsValid(OracleToleranceMixin, GeoFuncMixin, Transform): def as_oracle(self, compiler, connection, **extra_context): sql, params = super().as_oracle(compiler, connection, **extra_context) - return "CASE %s WHEN 'TRUE' THEN 1 ELSE 0 END" % sql, params + return f"CASE {sql} WHEN 'TRUE' THEN 1 ELSE 0 END", params class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc): @@ -459,14 +456,12 @@ class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc): arity = 1 def as_postgresql(self, compiler, connection, **extra_context): - function = None if self.geo_field.geodetic(connection) and not self.source_is_geography(): raise NotSupportedError( "ST_Perimeter cannot use a non-projected non-geography field." ) dim = min(f.dim for f in self.get_source_fields()) - if dim > 2: - function = connection.ops.perimeter3d + function = connection.ops.perimeter3d if dim > 2 else None return super().as_sql(compiler, connection, function=function, **extra_context) def as_sqlite(self, compiler, connection, **extra_context): @@ -499,7 +494,7 @@ class SnapToGrid(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc): def __init__(self, expression, *args, **extra): nargs = len(args) expressions = [expression] - if nargs in (1, 2): + if nargs in {1, 2}: expressions.extend( [self._handle_param(arg, "", NUMERIC_TYPES) for arg in args] ) @@ -507,7 +502,7 @@ def __init__(self, expression, *args, **extra): # Reverse origin and size param ordering expressions += [ *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[2:]), - *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[0:2]), + *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[:2]), ] else: raise ValueError("Must provide 1, 2, or 4 arguments to `SnapToGrid`.") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/lookups.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/lookups.py index 07762d0a..c84b521d 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/lookups.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/lookups.py @@ -30,7 +30,7 @@ def process_rhs_params(self): if len(self.rhs_params) == (2 if self.lookup_name == "relate" else 1): self.process_band_indices() elif len(self.rhs_params) > 1: - raise ValueError("Tuple too long for lookup %s." % self.lookup_name) + raise ValueError(f"Tuple too long for lookup {self.lookup_name}.") elif isinstance(self.lhs, RasterBandTransform): self.process_band_indices(only_lhs=True) @@ -282,7 +282,7 @@ def process_rhs(self, compiler, connection): if hasattr(backend_op, "check_relate_argument"): backend_op.check_relate_argument(pattern) elif not isinstance(pattern, str) or not self.pattern_regex.match(pattern): - raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) + raise ValueError(f'Invalid intersection matrix pattern "{pattern}".') sql, params = super().process_rhs(compiler, connection) return sql, params + [pattern] @@ -304,7 +304,7 @@ class DistanceLookupBase(GISLookup): def process_rhs_params(self): if not 1 <= len(self.rhs_params) <= 3: raise ValueError( - "2, 3, or 4-element tuple required for '%s' lookup." % self.lookup_name + f"2, 3, or 4-element tuple required for '{self.lookup_name}' lookup." ) elif len(self.rhs_params) == 3 and self.rhs_params[2] != "spheroid": raise ValueError( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/proxy.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/proxy.py index 4db365dc..386df204 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/proxy.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/proxy.py @@ -69,13 +69,9 @@ def __set__(self, instance, value): if value.srid is None: # Assigning the field SRID if the geometry has no SRID. value.srid = self.field.srid - elif value is None or isinstance(value, (str, memoryview)): - # Set geometries with None, WKT, HEX, or WKB - pass - else: + elif value is not None and not isinstance(value, (str, memoryview)): raise TypeError( - "Cannot set %s SpatialProxy (%s) with value of type: %s" - % (instance.__class__.__name__, gtype, type(value)) + f"Cannot set {instance.__class__.__name__} SpatialProxy ({gtype}) with value of type: {type(value)}" ) # Setting the objects dictionary with the value, and returning. diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/sql/conversion.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/sql/conversion.py index be712319..3093cdc9 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/sql/conversion.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/db/models/sql/conversion.py @@ -49,19 +49,19 @@ def __init__(self, geo_field): self.geo_field = geo_field def get_prep_value(self, value): - if isinstance(value, Distance): - return value - return super().get_prep_value(value) + return value if isinstance(value, Distance) else super().get_prep_value(value) def get_db_prep_value(self, value, connection, prepared=False): if not isinstance(value, Distance): return value - distance_att = connection.ops.get_distance_att_for_field(self.geo_field) - if not distance_att: + if distance_att := connection.ops.get_distance_att_for_field( + self.geo_field + ): + return getattr(value, distance_att) + else: raise ValueError( "Distance measure is supplied, but units are unknown for result." ) - return getattr(value, distance_att) def from_db_value(self, value, expression, connection): if value is None: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/feeds.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/feeds.py index ebd45118..148ca2c5 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/feeds.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/feeds.py @@ -44,15 +44,14 @@ def add_georss_element(self, handler, item, w3c_geo=False): box_coords = geom else: raise ValueError("Only should be two sets of coordinates.") + elif len(geom) == 2: + # Point: (X, Y) + self.add_georss_point(handler, geom, w3c_geo=w3c_geo) + elif len(geom) == 4: + # Box: (X0, Y0, X1, Y1) + box_coords = (geom[:2], geom[2:]) else: - if len(geom) == 2: - # Point: (X, Y) - self.add_georss_point(handler, geom, w3c_geo=w3c_geo) - elif len(geom) == 4: - # Box: (X0, Y0, X1, Y1) - box_coords = (geom[:2], geom[2:]) - else: - raise ValueError("Only should be 2 or 4 numeric elements.") + raise ValueError("Only should be 2 or 4 numeric elements.") # If a GeoRSS box was given via tuple. if box_coords is not None: if w3c_geo: @@ -72,19 +71,17 @@ def add_georss_element(self, handler, item, w3c_geo=False): raise ValueError("W3C Geo only supports Point geometries.") # For formatting consistent w/the GeoRSS simple standard: # http://georss.org/1.0#simple - if gtype in ("linestring", "linearring"): + if gtype in {"linestring", "linearring"}: handler.addQuickElement( "georss:line", self.georss_coords(geom.coords) ) - elif gtype in ("polygon",): + elif gtype in {"polygon"}: # Only support the exterior ring. handler.addQuickElement( "georss:polygon", self.georss_coords(geom[0].coords) ) else: - raise ValueError( - 'Geometry type "%s" not supported.' % geom.geom_type - ) + raise ValueError(f'Geometry type "{geom.geom_type}" not supported.') # ### SyndicationFeed subclasses ### diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/fields.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/fields.py index 1fd31530..45fef37e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/fields.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/fields.py @@ -76,10 +76,7 @@ def clean(self, value): # Ensuring that the geometry is of the correct type (indicated # using the OGC string label). - if ( - str(geom.geom_type).upper() != self.geom_type - and self.geom_type != "GEOMETRY" - ): + if str(geom.geom_type).upper() != self.geom_type != "GEOMETRY": raise ValidationError( self.error_messages["invalid_geom_type"], code="invalid_geom_type" ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/widgets.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/widgets.py index 0f53ee2e..3a400165 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/widgets.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/forms/widgets.py @@ -30,7 +30,7 @@ def __init__(self, attrs=None): for key in ("geom_type", "map_srid", "map_width", "map_height", "display_raw"): self.attrs[key] = getattr(self, key) if attrs: - self.attrs.update(attrs) + self.attrs |= attrs def serialize(self, value): return value.wkt if value else "" @@ -49,20 +49,18 @@ def get_context(self, name, value, attrs): if value and isinstance(value, str): value = self.deserialize(value) - if value: - # Check that srid of value and map match - if value.srid and value.srid != self.map_srid: - try: - ogr = value.ogr - ogr.transform(self.map_srid) - value = ogr - except gdal.GDALException as err: - logger.error( - "Error transforming geometry from srid '%s' to srid '%s' (%s)", - value.srid, - self.map_srid, - err, - ) + if value and value.srid and value.srid != self.map_srid: + try: + ogr = value.ogr + ogr.transform(self.map_srid) + value = ogr + except gdal.GDALException as err: + logger.error( + "Error transforming geometry from srid '%s' to srid '%s' (%s)", + value.srid, + self.map_srid, + err, + ) geom_type = gdal.OGRGeomType(self.attrs["geom_type"]).name context.update( @@ -70,9 +68,11 @@ def get_context(self, name, value, attrs): self.attrs, { "name": name, - "module": "geodjango_%s" % name.replace("-", "_"), # JS-safe + "module": f'geodjango_{name.replace("-", "_")}', "serialized": self.serialize(value), - "geom_type": "Geometry" if geom_type == "Unknown" else geom_type, + "geom_type": "Geometry" + if geom_type == "Unknown" + else geom_type, "STATIC_URL": settings.STATIC_URL, "LANGUAGE_BIDI": translation.get_language_bidi(), **(attrs or {}), diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/datasource.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/datasource.py index d1695aa8..92251eb0 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/datasource.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/datasource.py @@ -54,10 +54,7 @@ class DataSource(GDALBase): def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"): # The write flag. - if write: - self._write = 1 - else: - self._write = 0 + self._write = 1 if write else 0 # See also https://trac.osgeo.org/gdal/wiki/rfc23_ogr_unicode self.encoding = encoding @@ -72,20 +69,20 @@ def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"): except GDALException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". - raise GDALException('Could not open the datasource at "%s"' % ds_input) + raise GDALException(f'Could not open the datasource at "{ds_input}"') elif isinstance(ds_input, self.ptr_type) and isinstance( ds_driver, Driver.ptr_type ): ds = ds_input else: - raise GDALException("Invalid data source input type: %s" % type(ds_input)) + raise GDALException(f"Invalid data source input type: {type(ds_input)}") if ds: self.ptr = ds self.driver = Driver(ds_driver) else: # Raise an exception if the returned pointer is NULL - raise GDALException('Invalid data source file "%s"' % ds_input) + raise GDALException(f'Invalid data source file "{ds_input}"') def __getitem__(self, index): "Allows use of the index [] operator to get a layer at the index." @@ -93,17 +90,16 @@ def __getitem__(self, index): try: layer = capi.get_layer_by_name(self.ptr, force_bytes(index)) except GDALException: - raise IndexError("Invalid OGR layer name given: %s." % index) + raise IndexError(f"Invalid OGR layer name given: {index}.") elif isinstance(index, int): if 0 <= index < self.layer_count: layer = capi.get_layer(self._ptr, index) else: raise IndexError( - "Index out of range when accessing layers in a datasource: %s." - % index + f"Index out of range when accessing layers in a datasource: {index}." ) else: - raise TypeError("Invalid index type: %s" % type(index)) + raise TypeError(f"Invalid index type: {type(index)}") return Layer(layer, self) def __len__(self): @@ -112,7 +108,7 @@ def __len__(self): def __str__(self): "Return OGR GetName and Driver for the Data Source." - return "%s (%s)" % (self.name, self.driver) + return f"{self.name} ({self.driver})" @property def layer_count(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/driver.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/driver.py index 0ce7a2cd..5e063982 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/driver.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/driver.py @@ -63,13 +63,13 @@ def __init__(self, dr_input): driver = dr_input else: raise GDALException( - "Unrecognized input type for GDAL/OGR Driver: %s" % type(dr_input) + f"Unrecognized input type for GDAL/OGR Driver: {type(dr_input)}" ) # Making sure we get a valid pointer to the OGR Driver if not driver: raise GDALException( - "Could not initialize GDAL/OGR Driver on input: %s" % dr_input + f"Could not initialize GDAL/OGR Driver on input: {dr_input}" ) self.ptr = driver diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/envelope.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/envelope.py index 4c2c1e4a..f2980b88 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/envelope.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/envelope.py @@ -54,7 +54,7 @@ def __init__(self, *args): else: self._from_sequence(args[0]) else: - raise TypeError("Incorrect type of argument: %s" % type(args[0])) + raise TypeError(f"Incorrect type of argument: {type(args[0])}") elif len(args) == 4: # Individual parameters passed in. # Thanks to ww for the help @@ -140,7 +140,7 @@ def expand_to_include(self, *args): "Incorrect number of tuple elements (%d)." % len(args[0]) ) else: - raise TypeError("Incorrect type of argument: %s" % type(args[0])) + raise TypeError(f"Incorrect type of argument: {type(args[0])}") elif len(args) == 2: # An x and an y parameter were passed in return self.expand_to_include((args[0], args[1], args[0], args[1])) @@ -189,15 +189,4 @@ def tuple(self): def wkt(self): "Return WKT representing a Polygon for this envelope." # TODO: Fix significant figures. - return "POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))" % ( - self.min_x, - self.min_y, - self.min_x, - self.max_y, - self.max_x, - self.max_y, - self.max_x, - self.min_y, - self.min_x, - self.min_y, - ) + return f"POLYGON(({self.min_x} {self.min_y},{self.min_x} {self.max_y},{self.max_x} {self.max_y},{self.max_x} {self.min_y},{self.min_x} {self.min_y}))" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/error.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/error.py index df19c2e4..4e4b5dfc 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/error.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/error.py @@ -58,4 +58,4 @@ def check_err(code, cpl=False): e, msg = err_dict[code] raise e(msg) else: - raise GDALException('Unknown error code: "%s"' % code) + raise GDALException(f'Unknown error code: "{code}"') diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/feature.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/feature.py index 6f089699..d21aa734 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/feature.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/feature.py @@ -41,7 +41,7 @@ def __getitem__(self, index): i = index else: raise IndexError( - "Index out of range when accessing field in a feature: %s." % index + f"Index out of range when accessing field in a feature: {index}." ) return Field(self, i) @@ -116,5 +116,5 @@ def index(self, field_name): "Return the index of the given field name." i = capi.get_field_index(self.ptr, force_bytes(field_name)) if i < 0: - raise IndexError("Invalid OFT field name given: %s." % field_name) + raise IndexError(f"Invalid OFT field name given: {field_name}.") return i diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/field.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/field.py index b9964ab7..b6576834 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/field.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/field.py @@ -73,8 +73,8 @@ def as_datetime(self): "Retrieve the Field's value as a tuple of date & time components." if not self.is_set: return None - yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] - status = capi.get_field_as_datetime( + yy, mm, dd, hh, mn, ss, tz = [c_int() for _ in range(7)] + if status := capi.get_field_as_datetime( self._feat.ptr, self._index, byref(yy), @@ -84,8 +84,7 @@ def as_datetime(self): byref(mn), byref(ss), byref(tz), - ) - if status: + ): return (yy, mm, dd, hh, mn, ss, tz) else: raise GDALException( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geometries.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geometries.py index f74dc688..1b9d39cb 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geometries.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geometries.py @@ -106,16 +106,13 @@ def __init__(self, geom_input, srs=None): g = geom_input else: raise GDALException( - "Invalid input type for OGR Geometry construction: %s" - % type(geom_input) + f"Invalid input type for OGR Geometry construction: {type(geom_input)}" ) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: - raise GDALException( - "Cannot create OGR Geometry from input: %s" % geom_input - ) + raise GDALException(f"Cannot create OGR Geometry from input: {geom_input}") self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. @@ -128,10 +125,7 @@ def __init__(self, geom_input, srs=None): # Pickle routines def __getstate__(self): srs = self.srs - if srs: - srs = srs.wkt - else: - srs = None + srs = srs.wkt if srs else None return bytes(self.wkb), srs def __setstate__(self, state): @@ -157,8 +151,7 @@ def from_bbox(cls, bbox): "Construct a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox return OGRGeometry( - "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" - % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) + f"POLYGON(({x0} {y0}, {x0} {y1}, {x1} {y1}, {x1} {y0}, {x0} {y0}))" ) @staticmethod @@ -292,7 +285,7 @@ def _set_srs(self, srs): srs_ptr = None else: raise TypeError( - "Cannot assign spatial reference with object of type: %s" % type(srs) + f"Cannot assign spatial reference with object of type: {type(srs)}" ) capi.assign_srs(self.ptr, srs_ptr) @@ -300,10 +293,7 @@ def _set_srs(self, srs): # The SRID property def _get_srid(self): - srs = self.srs - if srs: - return srs.srid - return None + return srs.srid if (srs := self.srs) else None def _set_srid(self, srid): if isinstance(srid, int) or srid is None: @@ -358,10 +348,7 @@ def wkb_size(self): @property def wkb(self): "Return the WKB representation of the Geometry." - if sys.byteorder == "little": - byteorder = 1 # wkbNDR (from ogr_core.h) - else: - byteorder = 0 # wkbXDR + byteorder = 1 if sys.byteorder == "little" else 0 sz = self.wkb_size # Creating the unsigned character buffer, and passing it in by reference. buf = (c_ubyte * sz)() @@ -378,10 +365,7 @@ def wkt(self): def ewkt(self): "Return the EWKT representation of the Geometry." srs = self.srs - if srs and srs.srid: - return "SRID=%s;%s" % (srs.srid, self.wkt) - else: - return self.wkt + return f"SRID={srs.srid};{self.wkt}" if srs and srs.srid else self.wkt # #### Geometry Methods #### def clone(self): @@ -561,20 +545,19 @@ def tuple(self): class LineString(OGRGeometry): def __getitem__(self, index): "Return the Point at the given index." - if 0 <= index < self.point_count: - x, y, z = c_double(), c_double(), c_double() - capi.get_point(self.ptr, index, byref(x), byref(y), byref(z)) - dim = self.coord_dim - if dim == 1: - return (x.value,) - elif dim == 2: - return (x.value, y.value) - elif dim == 3: - return (x.value, y.value, z.value) - else: + if not 0 <= index < self.point_count: raise IndexError( - "Index out of range when accessing points of a line string: %s." % index + f"Index out of range when accessing points of a line string: {index}." ) + x, y, z = c_double(), c_double(), c_double() + capi.get_point(self.ptr, index, byref(x), byref(y), byref(z)) + dim = self.coord_dim + if dim == 1: + return (x.value,) + elif dim == 2: + return (x.value, y.value) + elif dim == 3: + return (x.value, y.value, z.value) def __len__(self): "Return the number of points in the LineString." @@ -629,7 +612,7 @@ def __getitem__(self, index): ) else: raise IndexError( - "Index out of range when accessing rings of a polygon: %s." % index + f"Index out of range when accessing rings of a polygon: {index}." ) # Polygon Properties @@ -674,8 +657,7 @@ def __getitem__(self, index): ) else: raise IndexError( - "Index out of range when accessing geometry in a collection: %s." - % index + f"Index out of range when accessing geometry in a collection: {index}." ) def __len__(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geomtype.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geomtype.py index 8b77cafa..a6824dfa 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geomtype.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/geomtype.py @@ -40,7 +40,7 @@ def __init__(self, type_input): type_input = "unknown" num = self._str_types.get(type_input) if num is None: - raise GDALException('Invalid OGR String Type "%s"' % type_input) + raise GDALException(f'Invalid OGR String Type "{type_input}"') elif isinstance(type_input, int): if type_input not in self._types: raise GDALException("Invalid OGR Integer Type: %d" % type_input) @@ -84,7 +84,7 @@ def django(self): s = "Geometry" elif s == "PointZ": s = "Point" - return s + "Field" + return f"{s}Field" def to_multi(self): """ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/layer.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/layer.py index 1afa0469..54616dc8 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/layer.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/layer.py @@ -61,7 +61,7 @@ def __iter__(self): "Iterate over each Feature in the Layer." # ResetReading() must be called before iteration is to begin. capi.reset_reading(self._ptr) - for i in range(self.num_feat): + for _ in range(self.num_feat): yield Feature(capi.get_next_feature(self._ptr), self) def __len__(self): @@ -92,7 +92,7 @@ def _make_feature(self, feat_id): if feat.fid == feat_id: return feat # Should have returned a Feature, raise an IndexError. - raise IndexError("Invalid feature id: %s." % feat_id) + raise IndexError(f"Invalid feature id: {feat_id}.") # #### Layer properties #### @property @@ -185,7 +185,7 @@ def _set_spatial_filter(self, filter): if isinstance(filter, OGRGeometry): capi.set_spatial_filter(self.ptr, filter.ptr) elif isinstance(filter, (tuple, list)): - if not len(filter) == 4: + if len(filter) != 4: raise ValueError("Spatial filter list/tuple must have 4 elements.") # Map c_double onto params -- if a bad type is passed in it # will be caught here. @@ -208,7 +208,7 @@ def get_fields(self, field_name): in the Layer. """ if field_name not in self.fields: - raise GDALException("invalid field name: %s" % field_name) + raise GDALException(f"invalid field name: {field_name}") return [feat.get(field_name) for feat in self] def get_geoms(self, geos=False): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/libgdal.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/libgdal.py index 6a7b7867..5b1e3d1b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/libgdal.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/libgdal.py @@ -48,7 +48,7 @@ "gdal2.0.0", ] else: - raise ImproperlyConfigured('GDAL is unsupported on OS "%s".' % os.name) + raise ImproperlyConfigured(f'GDAL is unsupported on OS "{os.name}".') # Using the ctypes `find_library` utility to find the # path to the GDAL library from the list of library names. @@ -83,10 +83,7 @@ def std_call(func): Return the correct STDCALL function for certain OSR routines on Win32 platforms. """ - if os.name == "nt": - return lwingdal[func] - else: - return lgdal[func] + return lwingdal[func] if os.name == "nt" else lgdal[func] # #### Version-information functions. #### @@ -111,7 +108,7 @@ def gdal_version_info(): ver = gdal_version() m = re.match(rb"^(?P\d+)\.(?P\d+)(?:\.(?P\d+))?", ver) if not m: - raise GDALException('Could not parse GDAL version string "%s"' % ver) + raise GDALException(f'Could not parse GDAL version string "{ver}"') major, minor, subminor = m.groups() return (int(major), int(minor), subminor and int(subminor)) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/errcheck.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/errcheck.py index 52bb7cb0..2a2b3d06 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/errcheck.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/errcheck.py @@ -45,10 +45,7 @@ def check_string(result, func, cargs, offset=-1, str_result=False): if str_result: # For routines that return a string. ptr = result - if not ptr: - s = None - else: - s = string_at(result) + s = string_at(result) if ptr else None else: # Error-code return specified. check_err(result) @@ -80,7 +77,7 @@ def check_geom(result, func, cargs): result = c_void_p(result) if not result: raise GDALException( - 'Invalid geometry pointer returned from "%s".' % func.__name__ + f'Invalid geometry pointer returned from "{func.__name__}".' ) return result @@ -98,7 +95,7 @@ def check_srs(result, func, cargs): result = c_void_p(result) if not result: raise SRSException( - 'Invalid spatial reference pointer returned from "%s".' % func.__name__ + f'Invalid spatial reference pointer returned from "{func.__name__}".' ) return result @@ -127,7 +124,7 @@ def check_pointer(result, func, cargs): if result: return result else: - raise GDALException('Invalid pointer returned from "%s"' % func.__name__) + raise GDALException(f'Invalid pointer returned from "{func.__name__}"') def check_str_arg(result, func, cargs): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/generation.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/generation.py index 230e56f6..29bf25fe 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/generation.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/generation.py @@ -96,11 +96,7 @@ def srs_output(func, argtypes): def const_string_output(func, argtypes, offset=None, decoding=None, cpl=False): func.argtypes = argtypes - if offset: - func.restype = c_int - else: - func.restype = c_char_p - + func.restype = c_int if offset else c_char_p def _check_const(result, func, cargs): res = check_const_string(result, func, cargs, offset=offset, cpl=cpl) if res and decoding: @@ -121,14 +117,7 @@ def string_output(func, argtypes, offset=-1, str_result=False, decoding=None): only when `str_result` is True. """ func.argtypes = argtypes - if str_result: - # Use subclass of c_char_p so the error checking routine - # can free the memory at the pointer's address. - func.restype = gdal_char_p - else: - # Error code is returned - func.restype = c_int - + func.restype = gdal_char_p if str_result else c_int # Dynamically defining our error-checking function with the # given offset. def _check_str(result, func, cargs): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/base.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/base.py index 3d95c90d..1a9df075 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/base.py @@ -24,12 +24,9 @@ def metadata(self): # The number of domains is unknown, so retrieve data until there # are no more values in the ctypes array. counter = 0 - domain = meta_list[counter] - while domain: + while domain := meta_list[counter]: domain_list.append(domain.decode()) counter += 1 - domain = meta_list[counter] - # Free domain list array. capi.free_dsl(meta_list) @@ -47,12 +44,10 @@ def metadata(self): # there are no more values in the ctypes array. domain_meta = {} counter = 0 - item = data[counter] - while item: + while item := data[counter]: key, val = item.decode().split("=") domain_meta[key] = val counter += 1 - item = data[counter] # The default domain values are returned if domain is None. result[domain or "DEFAULT"] = domain_meta return result diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/source.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/source.py index ca787575..8e07c2a0 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/source.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/raster/source.py @@ -87,16 +87,12 @@ def __init__(self, ds_input, write=False): if not ds_input.startswith(VSI_FILESYSTEM_PREFIX) and not os.path.exists( ds_input ): - raise GDALException( - 'Unable to read raster source input "%s".' % ds_input - ) + raise GDALException(f'Unable to read raster source input "{ds_input}".') try: # GDALOpen will auto-detect the data source type. self._ptr = capi.open_ds(force_bytes(ds_input), self._write) except GDALException as err: - raise GDALException( - 'Could not open the datasource at "{}" ({}).'.format(ds_input, err) - ) + raise GDALException(f'Could not open the datasource at "{ds_input}" ({err}).') elif isinstance(ds_input, bytes): # Create a new raster in write mode. self._write = 1 @@ -132,9 +128,7 @@ def __init__(self, ds_input, write=False): # For out of memory drivers, check filename argument if driver.name != "MEM" and "name" not in ds_input: raise GDALException( - 'Specify name for creation of raster with driver "{}".'.format( - driver.name - ) + f'Specify name for creation of raster with driver "{driver.name}".' ) # Check if width and height where specified @@ -150,7 +144,7 @@ def __init__(self, ds_input, write=False): # Create null terminated gdal options array. papsz_options = [] for key, val in ds_input.get("papsz_options", {}).items(): - option = "{}={}".format(key, val) + option = f"{key}={val}" papsz_options.append(option.upper().encode()) papsz_options.append(None) @@ -205,9 +199,7 @@ def __init__(self, ds_input, write=False): # Instantiate the object using an existing pointer to a gdal raster. self._ptr = ds_input else: - raise GDALException( - 'Invalid data source input type: "{}".'.format(type(ds_input)) - ) + raise GDALException(f'Invalid data source input type: "{type(ds_input)}".') def __del__(self): if self.is_vsi_based: @@ -222,7 +214,7 @@ def __repr__(self): """ Short-hand representation because WKB may be very large. """ - return "" % hex(addressof(self._ptr)) + return f"" def _flush(self): """ @@ -296,9 +288,7 @@ def srs(self): """ try: wkt = capi.get_ds_projection_ref(self._ptr) - if not wkt: - return None - return SpatialReference(wkt, srs_type="wkt") + return SpatialReference(wkt, srs_type="wkt") if wkt else None except SRSException: return None @@ -423,7 +413,7 @@ def warp(self, ds_input, resampling="NearestNeighbour", max_error=0.0): ds_input.setdefault("driver", self.driver.name) if "name" not in ds_input: - ds_input["name"] = self.name + "_copy." + self.driver.name + ds_input["name"] = f"{self.name}_copy.{self.driver.name}" if "datatype" not in ds_input: ds_input["datatype"] = self.bands[0].datatype() @@ -461,7 +451,7 @@ def clone(self, name=None): if name: clone_name = name elif self.driver.name != "MEM": - clone_name = self.name + "_copy." + self.driver.name + clone_name = f"{self.name}_copy.{self.driver.name}" else: clone_name = os.path.join(VSI_MEM_FILESYSTEM_BASE_PATH, str(uuid.uuid4())) return GDALRaster( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/srs.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/srs.py index 2e335fe5..221cceae 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/srs.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/gdal/srs.py @@ -68,7 +68,7 @@ def __init__(self, srs_input="", srs_type="user", axis_order=None): if self.axis_order == AxisOrder.TRADITIONAL and GDAL_VERSION >= (3, 0): capi.set_axis_strategy(self.ptr, self.axis_order) elif self.axis_order != AxisOrder.TRADITIONAL and GDAL_VERSION < (3, 0): - raise ValueError("%s is not supported in GDAL < 3.0." % self.axis_order) + raise ValueError(f"{self.axis_order} is not supported in GDAL < 3.0.") return elif isinstance(srs_input, str): try: @@ -85,7 +85,7 @@ def __init__(self, srs_input="", srs_type="user", axis_order=None): srs = srs_input srs_type = "ogr" else: - raise TypeError('Invalid SRS type "%s"' % srs_type) + raise TypeError(f'Invalid SRS type "{srs_type}"') if srs_type == "ogr": # Input is already an SRS pointer. @@ -97,16 +97,14 @@ def __init__(self, srs_input="", srs_type="user", axis_order=None): # If the pointer is NULL, throw an exception. if not srs: - raise SRSException( - "Could not create spatial reference from: %s" % srs_input - ) + raise SRSException(f"Could not create spatial reference from: {srs_input}") else: self.ptr = srs if self.axis_order == AxisOrder.TRADITIONAL and GDAL_VERSION >= (3, 0): capi.set_axis_strategy(self.ptr, self.axis_order) elif self.axis_order != AxisOrder.TRADITIONAL and GDAL_VERSION < (3, 0): - raise ValueError("%s is not supported in GDAL < 3.0." % self.axis_order) + raise ValueError(f"{self.axis_order} is not supported in GDAL < 3.0.") # Importing from either the user input string or an integer SRID. if srs_type == "user": self.import_user_input(srs_input) @@ -357,4 +355,4 @@ def __init__(self, source, target): self._srs2_name = target.name def __str__(self): - return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name) + return f'Transform from "{self._srs1_name}" to "{self._srs2_name}"' diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geoip2/base.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geoip2/base.py index 221ae1fb..bb892623 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geoip2/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geoip2/base.py @@ -72,7 +72,7 @@ def __init__(self, path=None, cache=0, country=None, city=None): if cache in self.cache_options: self._cache = cache else: - raise GeoIP2Exception("Invalid GeoIP caching option: %s" % cache) + raise GeoIP2Exception(f"Invalid GeoIP caching option: {cache}") # Getting the GeoIP data path. path = path or GEOIP_SETTINGS["GEOIP_PATH"] @@ -96,7 +96,7 @@ def __init__(self, path=None, cache=0, country=None, city=None): self._city = geoip2.database.Reader(str(city_db), mode=cache) self._city_file = city_db if not self._reader: - raise GeoIP2Exception("Could not load a database from %s." % path) + raise GeoIP2Exception(f"Could not load a database from {path}.") elif path.is_file(): # Otherwise, some detective work will be needed to figure out # whether the given database path is for the GeoIP country or city @@ -113,9 +113,7 @@ def __init__(self, path=None, cache=0, country=None, city=None): self._country = reader self._country_file = path else: - raise GeoIP2Exception( - "Unable to recognize database edition: %s" % db_type - ) + raise GeoIP2Exception(f"Unable to recognize database edition: {db_type}") else: raise GeoIP2Exception("GeoIP path must be a valid file or directory.") @@ -125,10 +123,7 @@ def _reader(self): @property def _country_or_city(self): - if self._country: - return self._country.country - else: - return self._city.city + return self._country.country if self._country else self._city.city def __del__(self): # Cleanup any GeoIP file handles lying around. @@ -137,10 +132,7 @@ def __del__(self): def __repr__(self): meta = self._reader.metadata() - version = "[v%s.%s]" % ( - meta.binary_format_major_version, - meta.binary_format_minor_version, - ) + version = f"[v{meta.binary_format_major_version}.{meta.binary_format_minor_version}]" return ( '<%(cls)s %(version)s _country_file="%(country)s", _city_file="%(city)s">' % { @@ -156,18 +148,16 @@ def _check_query(self, query, country=False, city=False, city_or_country=False): # Making sure a string was passed in for the query. if not isinstance(query, str): raise TypeError( - "GeoIP query must be a string, not type %s" % type(query).__name__ + f"GeoIP query must be a string, not type {type(query).__name__}" ) # Extra checks for the existence of country and city databases. - if city_or_country and not (self._country or self._city): + if city_or_country and not self._country and not self._city: raise GeoIP2Exception("Invalid GeoIP country and city data files.") elif country and not self._country: - raise GeoIP2Exception( - "Invalid GeoIP country data file: %s" % self._country_file - ) + raise GeoIP2Exception(f"Invalid GeoIP country data file: {self._country_file}") elif city and not self._city: - raise GeoIP2Exception("Invalid GeoIP city data file: %s" % self._city_file) + raise GeoIP2Exception(f"Invalid GeoIP city data file: {self._city_file}") # Return the query string back to the caller. GeoIP2 only takes IP addresses. try: @@ -209,10 +199,7 @@ def country(self, query): # #### Coordinate retrieval routines #### def coords(self, query, ordering=("longitude", "latitude")): cdict = self.city(query) - if cdict is None: - return None - else: - return tuple(cdict[o] for o in ordering) + return None if cdict is None else tuple(cdict[o] for o in ordering) def lon_lat(self, query): "Return a tuple of the (longitude, latitude) for the given query." @@ -224,8 +211,7 @@ def lat_lon(self, query): def geos(self, query): "Return a GEOS Point object for the given query." - ll = self.lon_lat(query) - if ll: + if ll := self.lon_lat(query): from django.contrib.gis.geos import Point return Point(ll, srid=4326) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/collections.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/collections.py index abfec8af..fd387da0 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/collections.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/collections.py @@ -19,10 +19,7 @@ def __init__(self, *args, **kwargs): if len(args) == 1: # If only one geometry provided or a list of geometries is provided # in the first argument. - if isinstance(args[0], (tuple, list)): - init_geoms = args[0] - else: - init_geoms = args + init_geoms = args[0] if isinstance(args[0], (tuple, list)) else args else: init_geoms = args @@ -81,7 +78,7 @@ def _set_list(self, length, items): @property def kml(self): "Return the KML for this Geometry Collection." - return "%s" % "".join(g.kml for g in self) + return f'{"".join(g.kml for g in self)}' @property def tuple(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/coordseq.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/coordseq.py index 07a3b7d2..d0eac3ce 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/coordseq.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/coordseq.py @@ -47,9 +47,7 @@ def __setitem__(self, index, value): # Checking the input value if isinstance(value, (list, tuple)): pass - elif numpy and isinstance(value, numpy.ndarray): - pass - else: + elif not numpy or not isinstance(value, numpy.ndarray): raise TypeError( "Must set coordinate with a sequence (list, tuple, or numpy array)." ) @@ -69,7 +67,7 @@ def __setitem__(self, index, value): def _checkindex(self, index): "Check the given index." if not (0 <= index < self.size): - raise IndexError("invalid GEOS Geometry index: %s" % index) + raise IndexError(f"invalid GEOS Geometry index: {index}") def _checkdim(self, dim): "Check the given dimension." @@ -181,23 +179,15 @@ def kml(self): "Return the KML representation for the coordinates." # Getting the substitution string depending on whether the coordinates have # a Z dimension. - if self.hasz: - substr = "%s,%s,%s " - else: - substr = "%s,%s,0 " - return ( - "%s" - % "".join(substr % self[i] for i in range(len(self))).strip() - ) + substr = "%s,%s,%s " if self.hasz else "%s,%s,0 " + return f'{"".join(substr % self[i] for i in range(len(self))).strip()}' @property def tuple(self): "Return a tuple version of this coordinate sequence." n = self.size get_point = self._point_getter - if n == 1: - return get_point(0) - return tuple(get_point(i) for i in range(n)) + return get_point(0) if n == 1 else tuple(get_point(i) for i in range(n)) @property def is_counterclockwise(self): @@ -215,6 +205,6 @@ def is_counterclockwise(self): ret = c_byte() if not capi.cs_is_ccw(self.ptr, byref(ret)): raise GEOSException( - 'Error encountered in GEOS C function "%s".' % capi.cs_is_ccw.func_name + f'Error encountered in GEOS C function "{capi.cs_is_ccw.func_name}".' ) return ret.value == 1 diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/factory.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/factory.py index 2c1c2474..8b5a93fa 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/factory.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/factory.py @@ -13,18 +13,16 @@ def fromfile(file_h): else: buf = file_h.read() - # If we get WKB need to wrap in memoryview(), so run through regexes. - if isinstance(buf, bytes): - try: - decoded = buf.decode() - except UnicodeDecodeError: - pass - else: - if wkt_regex.match(decoded) or hex_regex.match(decoded): - return GEOSGeometry(decoded) - else: + if not isinstance(buf, bytes): return GEOSGeometry(buf) + try: + decoded = buf.decode() + except UnicodeDecodeError: + pass + else: + if wkt_regex.match(decoded) or hex_regex.match(decoded): + return GEOSGeometry(decoded) return GEOSGeometry(memoryview(buf)) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/geometry.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/geometry.py index 8cee9a35..0d0a885f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/geometry.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/geometry.py @@ -88,7 +88,7 @@ def __str__(self): def __repr__(self): "Short-hand representation because WKT may be very large." - return "<%s object at %s>" % (self.geom_type, hex(addressof(self.ptr))) + return f"<{self.geom_type} object at {hex(addressof(self.ptr))}>" # Pickling support def _to_pickle_wkb(self): @@ -123,10 +123,10 @@ def from_ewkt(ewkt): parts = ewkt.split(b";", 1) if len(parts) == 2: srid_part, wkt = parts - match = re.match(rb"SRID=(?P\-?\d+)", srid_part) - if not match: + if match := re.match(rb"SRID=(?P\-?\d+)", srid_part): + srid = int(match["srid"]) + else: raise ValueError("EWKT has invalid SRID part.") - srid = int(match["srid"]) else: wkt = ewkt if not wkt: @@ -343,10 +343,7 @@ def within(self, other): def srid(self): "Get the SRID for the geometry. Return None if no SRID is set." s = capi.geos_get_srid(self.ptr) - if s == 0: - return None - else: - return s + return None if s == 0 else s @srid.setter def srid(self, srid): @@ -360,7 +357,7 @@ def ewkt(self): Return the EWKT (SRID + WKT) of the Geometry. """ srid = self.srid - return "SRID=%s;%s" % (srid, self.wkt) if srid else self.wkt + return f"SRID={srid};{self.wkt}" if srid else self.wkt @property def wkt(self): @@ -418,7 +415,7 @@ def ewkb(self): def kml(self): "Return the KML representation of this Geometry." gtype = self.geom_type - return "<%s>%s" % (gtype, self.coord_seq.kml, gtype) + return f"<{gtype}>{self.coord_seq.kml}" @property def prepared(self): @@ -714,8 +711,7 @@ def __init__(self, geo_input, srid=None): if isinstance(geo_input, bytes): geo_input = force_str(geo_input) if isinstance(geo_input, str): - wkt_m = wkt_regex.match(geo_input) - if wkt_m: + if wkt_m := wkt_regex.match(geo_input): # Handle WKT input. if wkt_m["srid"]: input_srid = int(wkt_m["srid"]) @@ -739,7 +735,7 @@ def __init__(self, geo_input, srid=None): elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: - raise TypeError("Improper geometry input type: %s" % type(geo_input)) + raise TypeError(f"Improper geometry input type: {type(geo_input)}") if not g: raise GEOSException("Could not initialize GEOS Geometry with given input.") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/libgeos.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/libgeos.py index 0002bef6..67fe9da1 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/libgeos.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/libgeos.py @@ -37,7 +37,7 @@ def load_geos(): # *NIX libraries lib_names = ["geos_c", "GEOS"] else: - raise ImportError('Unsupported OS "%s"' % os.name) + raise ImportError(f'Unsupported OS "{os.name}"') # Using the ctypes `find_library` utility to find the path to the GEOS # shared library. This is better than manually specifying each library name @@ -51,8 +51,7 @@ def load_geos(): # No GEOS library could be found. if lib_path is None: raise ImportError( - 'Could not find the GEOS library (tried "%s"). ' - "Try setting GEOS_LIBRARY_PATH in your settings." % '", "'.join(lib_names) + f"""Could not find the GEOS library (tried "{'", "'.join(lib_names)}"). Try setting GEOS_LIBRARY_PATH in your settings.""" ) # Getting the GEOS C library. The C interface (CDLL) is used for # both *NIX and Windows. @@ -64,9 +63,9 @@ def load_geos(): # attached to a GEOS context handle -- this actually occurs in # geos/prototypes/threadsafe.py. _lgeos.initGEOS_r.restype = CONTEXT_PTR - _lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR] # Set restype for compatibility across 32 and 64-bit platforms. _lgeos.GEOSversion.restype = c_char_p + _lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR] return _lgeos diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/linestring.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/linestring.py index 78a265ce..968e7757 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/linestring.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/linestring.py @@ -24,11 +24,7 @@ def __init__(self, *args, **kwargs): ls = LineString(Point(1, 1), Point(2, 2)) """ # If only one argument provided, set the coords array appropriately - if len(args) == 1: - coords = args[0] - else: - coords = args - + coords = args[0] if len(args) == 1 else args if not ( isinstance(coords, (tuple, list)) or numpy @@ -80,7 +76,7 @@ def __init__(self, *args, **kwargs): # Creating a coordinate sequence object because it is easier to # set the points using its methods. - cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim == 3)) + cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=ndim == 3) point_setter = cs._set_point_3d if ndim == 3 else cs._set_point_2d for i in range(ncoords): @@ -120,8 +116,7 @@ def _set_list(self, length, items): for i, c in enumerate(items): cs[i] = c - ptr = self._init_func(cs.ptr) - if ptr: + if ptr := self._init_func(cs.ptr): capi.destroy_geom(self.ptr) self.ptr = ptr if srid is not None: @@ -152,10 +147,7 @@ def _listarr(self, func): Return a numpy array if possible. """ lst = [func(i) for i in range(len(self))] - if numpy: - return numpy.array(lst) # ARRRR! - else: - return lst + return numpy.array(lst) if numpy else lst @property def array(self): @@ -175,10 +167,7 @@ def y(self): @property def z(self): "Return a list or numpy array of the Z variable." - if not self.hasz: - return None - else: - return self._listarr(self._cs.getZ) + return self._listarr(self._cs.getZ) if self.hasz else None # LinearRings are LineStrings used within Polygons. diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/mutable_list.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/mutable_list.py index 36131fe9..62c02dc9 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/mutable_list.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/mutable_list.py @@ -75,14 +75,13 @@ def __getitem__(self, index): return [ self._get_single_external(i) for i in range(*index.indices(len(self))) ] - else: - index = self._checkindex(index) - return self._get_single_external(index) + index = self._checkindex(index) + return self._get_single_external(index) def __delitem__(self, index): "Delete the item(s) at the specified index/slice." if not isinstance(index, (int, slice)): - raise TypeError("%s is not a legal index" % index) + raise TypeError(f"{index} is not a legal index") # calculate new length and dimensions origLen = len(self) @@ -136,7 +135,7 @@ def __imul__(self, n): del self[:] else: cache = list(self) - for i in range(n - 1): + for _ in range(n - 1): self.extend(cache) return self @@ -170,18 +169,14 @@ def __lt__(self, other): # ## Non-mutating ## def count(self, val): "Standard list count method" - count = 0 - for i in self: - if val == i: - count += 1 - return count + return sum(val == i for i in self) def index(self, val): "Standard list index method" - for i in range(0, len(self)): + for i in range(len(self)): if self[i] == val: return i - raise ValueError("%s not found in object" % val) + raise ValueError(f"{val} not found in object") # ## Mutating ## def append(self, val): @@ -195,7 +190,7 @@ def extend(self, vals): def insert(self, index, val): "Standard list insert method" if not isinstance(index, int): - raise TypeError("%s is not a legal index" % index) + raise TypeError(f"{index} is not a legal index") self[index:index] = [val] def pop(self, index=-1): @@ -234,12 +229,13 @@ def _checkindex(self, index): return index if -length <= index < 0: return index + length - raise IndexError("invalid index: %s" % index) + raise IndexError(f"invalid index: {index}") def _check_allowed(self, items): - if hasattr(self, "_allowed"): - if False in [isinstance(val, self._allowed) for val in items]: - raise TypeError("Invalid type encountered in the arguments.") + if hasattr(self, "_allowed") and False in [ + isinstance(val, self._allowed) for val in items + ]: + raise TypeError("Invalid type encountered in the arguments.") def _set_slice(self, index, values): "Assign values to a slice of the object" @@ -307,8 +303,7 @@ def newItems(): if i == start: yield from valueList - if i < origLen: - if i < start or i >= stop: - yield self._get_single_internal(i) + if i < origLen and (i < start or i >= stop): + yield self._get_single_internal(i) self._rebuild(newLen, newItems()) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/point.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/point.py index 06b26686..49199bb9 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/point.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/point.py @@ -27,10 +27,7 @@ def __init__(self, x=None, y=None, z=None, srid=None): coords = x elif isinstance(x, (float, int)) and isinstance(y, (float, int)): # Here X, Y, and (optionally) Z were passed in individually, as parameters. - if isinstance(z, (float, int)): - coords = [x, y, z] - else: - coords = [x, y] + coords = [x, y, z] if isinstance(z, (float, int)) else [x, y] else: raise TypeError("Invalid parameters given for Point initialization.") @@ -64,7 +61,7 @@ def _create_point(cls, ndim, coords): return capi.create_point(None) if ndim < 2 or ndim > 3: - raise TypeError("Invalid point dimension: %s" % ndim) + raise TypeError(f"Invalid point dimension: {ndim}") cs = capi.create_cs(c_uint(1), c_uint(ndim)) i = iter(coords) @@ -76,8 +73,7 @@ def _create_point(cls, ndim, coords): return capi.create_point(cs) def _set_list(self, length, items): - ptr = self._create_point(length, items) - if ptr: + if ptr := self._create_point(length, items): srid = self.srid capi.destroy_geom(self.ptr) self._ptr = ptr @@ -100,10 +96,7 @@ def __len__(self): "Return the number of dimensions for this Point (either 0, 2 or 3)." if self.empty: return 0 - if self.hasz: - return 3 - else: - return 2 + return 3 if self.hasz else 2 def _get_single_external(self, index): if index == 0: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/polygon.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/polygon.py index e384614b..fe6a8b22 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/polygon.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/polygon.py @@ -61,8 +61,7 @@ def from_bbox(cls, bbox): for z in bbox: if not isinstance(z, (float, int)): return GEOSGeometry( - "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" - % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) + f"POLYGON(({x0} {y0}, {x0} {y1}, {x1} {y1}, {x1} {y0}, {x0} {y0}))" ) return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0))) @@ -110,8 +109,7 @@ def _construct_ring( if isinstance(param, LinearRing): return param try: - ring = LinearRing(param) - return ring + return LinearRing(param) except TypeError: raise TypeError(msg) @@ -181,10 +179,7 @@ def tuple(self): def kml(self): "Return the KML representation of this Polygon." inner_kml = "".join( - "%s" % self[i + 1].kml + f"{self[i + 1].kml}" for i in range(self.num_interior_rings) ) - return "%s%s" % ( - self[0].kml, - inner_kml, - ) + return f"{self[0].kml}{inner_kml}" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/errcheck.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/errcheck.py index a527f513..a0e46218 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/errcheck.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/errcheck.py @@ -20,18 +20,14 @@ def last_arg_byref(args): def check_dbl(result, func, cargs): "Check the status code and returns the double value passed in by reference." # Checking the status code - if result != 1: - return None - # Double passed in by reference, return its value. - return last_arg_byref(cargs) + return None if result != 1 else last_arg_byref(cargs) def check_geom(result, func, cargs): "Error checking on routines that return Geometries." if not result: raise GEOSException( - 'Error encountered checking Geometry returned from GEOS C function "%s".' - % func.__name__ + f'Error encountered checking Geometry returned from GEOS C function "{func.__name__}".' ) return result @@ -39,9 +35,7 @@ def check_geom(result, func, cargs): def check_minus_one(result, func, cargs): "Error checking on routines that should not return -1." if result == -1: - raise GEOSException( - 'Error encountered in GEOS C function "%s".' % func.__name__ - ) + raise GEOSException(f'Error encountered in GEOS C function "{func.__name__}".') else: return result @@ -54,7 +48,7 @@ def check_predicate(result, func, cargs): return False else: raise GEOSException( - 'Error encountered on GEOS C predicate function "%s".' % func.__name__ + f'Error encountered on GEOS C predicate function "{func.__name__}".' ) @@ -66,7 +60,7 @@ def check_sized_string(result, func, cargs): """ if not result: raise GEOSException( - 'Invalid string pointer returned by GEOS C function "%s"' % func.__name__ + f'Invalid string pointer returned by GEOS C function "{func.__name__}"' ) # A c_size_t object is passed in by reference for the second # argument on these routines, and its needed to determine the @@ -85,8 +79,7 @@ def check_string(result, func, cargs): """ if not result: raise GEOSException( - 'Error encountered checking string return value in GEOS C function "%s".' - % func.__name__ + f'Error encountered checking string return value in GEOS C function "{func.__name__}".' ) # Getting the string value at the pointer address. s = string_at(result) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py index d4f7ffb8..ee66acc5 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py @@ -34,7 +34,7 @@ class GEOSFunc: def __init__(self, func_name): # GEOS thread-safe function signatures end with '_r' and take an # additional context handle parameter. - self.cfunc = getattr(lgeos, func_name + "_r") + self.cfunc = getattr(lgeos, f"{func_name}_r") # Create a reference to thread_context so it's not garbage-collected # before an attempt to call this object. self.thread_context = thread_context diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/management/commands/ogrinspect.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/management/commands/ogrinspect.py index 2d2bd631..c073e253 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/management/commands/ogrinspect.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/management/commands/ogrinspect.py @@ -127,7 +127,7 @@ def handle(self, *args, **options): for k, v in options.items() if k in get_func_args(_ogrinspect) and v is not None } - output = [s for s in _ogrinspect(ds, model_name, **ogr_options)] + output = list(_ogrinspect(ds, model_name, **ogr_options)) if options["mapping"]: # Constructing the keyword arguments for `mapping`, and @@ -145,19 +145,17 @@ def handle(self, *args, **options): [ "", "", - "# Auto-generated `LayerMapping` dictionary for %s model" - % model_name, + f"# Auto-generated `LayerMapping` dictionary for {model_name} model", "%s_mapping = {" % model_name.lower(), ] ) output.extend( - " '%s': '%s'," % (rev_mapping[ogr_fld], ogr_fld) + f" '{rev_mapping[ogr_fld]}': '{ogr_fld}'," for ogr_fld in ds[options["layer_key"]].fields ) output.extend( [ - " '%s': '%s'," - % (options["geom_name"], mapping_dict[options["geom_name"]]), + f""" '{options["geom_name"]}': '{mapping_dict[options["geom_name"]]}',""", "}", ] ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/measure.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/measure.py index 640f0e00..18338be7 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/measure.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/measure.py @@ -73,17 +73,13 @@ def __getattr__(self, name): if name in self.UNITS: return self.standard / self.UNITS[name] else: - raise AttributeError("Unknown unit type: %s" % name) + raise AttributeError(f"Unknown unit type: {name}") def __repr__(self): - return "%s(%s=%s)" % ( - pretty_name(self), - self._default_unit, - getattr(self, self._default_unit), - ) + return f"{pretty_name(self)}({self._default_unit}={getattr(self, self._default_unit)})" def __str__(self): - return "%s %s" % (getattr(self, self._default_unit), self._default_unit) + return f"{getattr(self, self._default_unit)} {self._default_unit}" # **** Comparison methods **** @@ -224,7 +220,7 @@ def default_units(self, kwargs): val += self.UNITS[u] * value default_unit = u else: - raise AttributeError("Unknown unit type: %s" % unit) + raise AttributeError(f"Unknown unit type: {unit}") return val, default_unit @classmethod @@ -242,9 +238,7 @@ def unit_attname(cls, unit_str): elif lower in cls.LALIAS: return cls.LALIAS[lower] else: - raise Exception( - 'Could not find a unit keyword associated with "%s"' % unit_str - ) + raise Exception(f'Could not find a unit keyword associated with "{unit_str}"') class Distance(MeasureBase): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/ptr.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/ptr.py index 67547016..c41bd7f0 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/ptr.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/ptr.py @@ -19,7 +19,7 @@ def ptr(self): if self._ptr: return self._ptr raise self.null_ptr_exception_class( - "NULL %s pointer encountered." % self.__class__.__name__ + f"NULL {self.__class__.__name__} pointer encountered." ) @ptr.setter @@ -27,7 +27,7 @@ def ptr(self, ptr): # Only allow the pointer to be set with pointers of the compatible # type or None (NULL). if not (ptr is None or isinstance(ptr, self.ptr_type)): - raise TypeError("Incompatible pointer type: %s." % type(ptr)) + raise TypeError(f"Incompatible pointer type: {type(ptr)}.") self._ptr = ptr def __del__(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/kml.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/kml.py index a84b5aef..f9cf617a 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/kml.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/kml.py @@ -30,15 +30,11 @@ def _build_kml_sources(self, sources): sources = apps.get_models() for source in sources: if isinstance(source, models.base.ModelBase): - for field in source._meta.fields: - if isinstance(field, GeometryField): - kml_sources.append( - ( - source._meta.app_label, - source._meta.model_name, - field.name, - ) - ) + kml_sources.extend( + (source._meta.app_label, source._meta.model_name, field.name) + for field in source._meta.fields + if isinstance(field, GeometryField) + ) elif isinstance(source, (list, tuple)): if len(source) != 3: raise ValueError( @@ -65,7 +61,7 @@ def items(self): def location(self, obj): return reverse( - "django.contrib.gis.sitemaps.views.%s" % self.geo_format, + f"django.contrib.gis.sitemaps.views.{self.geo_format}", kwargs={ "label": obj[0], "model": obj[1], diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/views.py index 17eb54e6..44e47db9 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/sitemaps/views.py @@ -18,8 +18,7 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB klass = apps.get_model(label, model) except LookupError: raise Http404( - 'You must supply a valid app label and module name. Got "%s.%s"' - % (label, model) + f'You must supply a valid app label and module name. Got "{label}.{model}"' ) if field_name: @@ -41,7 +40,7 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB placemarks = [] if connection.features.has_Transform_function: qs = klass._default_manager.using(using).annotate( - **{"%s_4326" % field_name: Transform(field_name, 4326)} + **{f"{field_name}_4326": Transform(field_name, 4326)} ) field_name += "_4326" else: @@ -51,10 +50,7 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB placemarks.append(mod) # Getting the render function and rendering to the correct. - if compress: - render = render_to_kmz - else: - render = render_to_kml + render = render_to_kmz if compress else render_to_kml return render("gis/kml/placemarks.kml", {"places": placemarks}) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/layermapping.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/layermapping.py index 922deee1..fef9da50 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/layermapping.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/layermapping.py @@ -172,20 +172,19 @@ def __init__( elif transaction_mode == "commit_on_success": self.transaction_decorator = transaction.atomic else: - raise LayerMapError("Unrecognized transaction mode: %s" % transaction_mode) + raise LayerMapError(f"Unrecognized transaction mode: {transaction_mode}") # #### Checking routines used during initialization #### def check_fid_range(self, fid_range): "Check the `fid_range` keyword." - if fid_range: - if isinstance(fid_range, (tuple, list)): - return slice(*fid_range) - elif isinstance(fid_range, slice): - return fid_range - else: - raise TypeError - else: + if not fid_range: return None + if isinstance(fid_range, (tuple, list)): + return slice(*fid_range) + elif isinstance(fid_range, slice): + return fid_range + else: + raise TypeError def check_layer(self): """ @@ -210,7 +209,7 @@ def check_ogr_fld(ogr_map_fld): idx = ogr_fields.index(ogr_map_fld) except ValueError: raise LayerMapError( - 'Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld + f'Given mapping OGR field "{ogr_map_fld}" not found in OGR Layer.' ) return idx @@ -223,7 +222,7 @@ def check_ogr_fld(ogr_map_fld): model_field = self.model._meta.get_field(field_name) except FieldDoesNotExist: raise LayerMapError( - 'Given mapping field "%s" not in given Model fields.' % field_name + f'Given mapping field "{field_name}" not in given Model fields.' ) # Getting the string name for the Django field class (e.g., 'PointField'). @@ -241,13 +240,11 @@ def check_ogr_fld(ogr_map_fld): try: if coord_dim == 3: - gtype = OGRGeomType(ogr_name + "25D") + gtype = OGRGeomType(f"{ogr_name}25D") else: gtype = OGRGeomType(ogr_name) except GDALException: - raise LayerMapError( - 'Invalid mapping for GeometryField "%s".' % field_name - ) + raise LayerMapError(f'Invalid mapping for GeometryField "{field_name}".') # Making sure that the OGR Layer's Geometry is compatible. ltype = self.layer.geom_type @@ -277,8 +274,7 @@ def check_ogr_fld(ogr_map_fld): rel_model._meta.get_field(rel_name) except FieldDoesNotExist: raise LayerMapError( - 'ForeignKey mapping field "%s" not in %s fields.' - % (rel_name, rel_model.__class__.__name__) + f'ForeignKey mapping field "{rel_name}" not in {rel_model.__class__.__name__} fields.' ) fields_val = rel_model else: @@ -287,7 +283,7 @@ def check_ogr_fld(ogr_map_fld): # Is the model field type supported by LayerMapping? if model_field.__class__ not in self.FIELD_TYPES: raise LayerMapError( - 'Django field type "%s" has no OGR mapping (yet).' % fld_name + f'Django field type "{fld_name}" has no OGR mapping (yet).' ) # Is the OGR field in the Layer? @@ -297,8 +293,7 @@ def check_ogr_fld(ogr_map_fld): # Can the OGR field type be mapped to the Django field type? if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]): raise LayerMapError( - 'OGR field "%s" (of type %s) cannot be mapped to Django %s.' - % (ogr_field, ogr_field.__name__, fld_name) + f'OGR field "{ogr_field}" (of type {ogr_field.__name__}) cannot be mapped to Django {fld_name}.' ) fields_val = model_field @@ -404,8 +399,7 @@ def verify_ogr_field(self, ogr_field, model_field): and len(val) > model_field.max_length ): raise InvalidString( - "%s model field maximum string length is %s, given %s characters." - % (model_field.name, model_field.max_length, len(val)) + f"{model_field.name} model field maximum string length is {model_field.max_length}, given {len(val)} characters." ) elif isinstance(ogr_field, OFTReal) and isinstance( model_field, models.DecimalField @@ -414,9 +408,7 @@ def verify_ogr_field(self, ogr_field, model_field): # Creating an instance of the Decimal value to use. d = Decimal(str(ogr_field.value)) except DecimalInvalidOperation: - raise InvalidDecimal( - "Could not construct decimal from: %s" % ogr_field.value - ) + raise InvalidDecimal(f"Could not construct decimal from: {ogr_field.value}") # Getting the decimal value as a tuple. dtup = d.as_tuple() @@ -428,11 +420,7 @@ def verify_ogr_field(self, ogr_field, model_field): # Getting the digits to the left of the decimal place for the # given decimal. - if d_idx < 0: - n_prec = len(digits[:d_idx]) - else: - n_prec = len(digits) + d_idx - + n_prec = len(digits[:d_idx]) if d_idx < 0 else len(digits) + d_idx # If we have more than the maximum digits allowed, then throw an # InvalidDecimal exception. if n_prec > max_prec: @@ -449,9 +437,7 @@ def verify_ogr_field(self, ogr_field, model_field): try: val = int(ogr_field.value) except ValueError: - raise InvalidInteger( - "Could not construct integer from: %s" % ogr_field.value - ) + raise InvalidInteger(f"Could not construct integer from: {ogr_field.value}") else: val = ogr_field.value return val @@ -461,24 +447,18 @@ def verify_fk(self, feat, rel_model, rel_mapping): Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping. """ - # TODO: It is expensive to retrieve a model for every record -- - # explore if an efficient mechanism exists for caching related - # ForeignKey models. - - # Constructing and verifying the related model keyword arguments. - fk_kwargs = {} - for field_name, ogr_name in rel_mapping.items(): - fk_kwargs[field_name] = self.verify_ogr_field( + fk_kwargs = { + field_name: self.verify_ogr_field( feat[ogr_name], rel_model._meta.get_field(field_name) ) - + for field_name, ogr_name in rel_mapping.items() + } # Attempting to retrieve and return the related model. try: return rel_model.objects.using(self.using).get(**fk_kwargs) except ObjectDoesNotExist: raise MissingForeignKey( - "No ForeignKey %s model found with keyword arguments: %s" - % (rel_model.__name__, fk_kwargs) + f"No ForeignKey {rel_model.__name__} model found with keyword arguments: {fk_kwargs}" ) def verify_geom(self, geom, model_field): @@ -541,7 +521,7 @@ def make_multi(self, geom_type, model_field): """ return ( geom_type.num in self.MULTI_TYPES - and model_field.__class__.__name__ == "Multi%s" % geom_type.django + and model_field.__class__.__name__ == f"Multi{geom_type.django}" ) def save( @@ -604,11 +584,7 @@ def save( progress_interval = progress def _save(feat_range=default_range, num_feat=0, num_saved=0): - if feat_range: - layer_iter = self.layer[feat_range] - else: - layer_iter = self.layer - + layer_iter = self.layer[feat_range] if feat_range else self.layer for feat in layer_iter: num_feat += 1 # Getting the keyword arguments @@ -705,11 +681,7 @@ def _save(feat_range=default_range, num_feat=0, num_saved=0): for i, end in enumerate(indices): # Constructing the slice to use for this step; the last slice is # special (e.g, [100:] instead of [90:100]). - if i + 1 == n_i: - step_slice = slice(beg, None) - else: - step_slice = slice(beg, end) - + step_slice = slice(beg, None) if i + 1 == n_i else slice(beg, end) try: num_feat, num_saved = _save(step_slice, num_feat, num_saved) beg = end diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinfo.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinfo.py index eafa23cc..d1e2704b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinfo.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinfo.py @@ -17,36 +17,30 @@ def ogrinfo(data_source, num_features=10): # Checking the parameters. if isinstance(data_source, str): data_source = DataSource(data_source) - elif isinstance(data_source, DataSource): - pass - else: + elif not isinstance(data_source, DataSource): raise Exception( "Data source parameter must be a string or a DataSource object." ) for i, layer in enumerate(data_source): - print("data source : %s" % data_source.name) - print("==== layer %s" % i) - print(" shape type: %s" % GEO_CLASSES[layer.geom_type.num].__name__) - print(" # features: %s" % len(layer)) - print(" srs: %s" % layer.srs) + print(f"data source : {data_source.name}") + print(f"==== layer {i}") + print(f" shape type: {GEO_CLASSES[layer.geom_type.num].__name__}") + print(f" # features: {len(layer)}") + print(f" srs: {layer.srs}") extent_tup = layer.extent.tuple - print(" extent: %s - %s" % (extent_tup[0:2], extent_tup[2:4])) - print("Displaying the first %s features ====" % num_features) + print(f" extent: {extent_tup[:2]} - {extent_tup[2:4]}") + print(f"Displaying the first {num_features} features ====") width = max(*map(len, layer.fields)) fmt = " %%%ss: %%s" % width for j, feature in enumerate(layer[:num_features]): - print("=== Feature %s" % j) + print(f"=== Feature {j}") for fld_name in layer.fields: type_name = feature[fld_name].type_name output = fmt % (fld_name, type_name) - val = feature.get(fld_name) - if val: - if isinstance(val, str): - val_fmt = ' ("%s")' - else: - val_fmt = " (%s)" + if val := feature.get(fld_name): + val_fmt = ' ("%s")' if isinstance(val, str) else " (%s)" output += val_fmt % val else: output += " (None)" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinspect.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinspect.py index 40ca0cb4..95668e1c 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinspect.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/utils/ogrinspect.py @@ -32,9 +32,7 @@ def mapping(data_source, geom_name="geom", layer_key=0, multi_geom=False): if isinstance(data_source, str): # Instantiating the DataSource from the string. data_source = DataSource(data_source) - elif isinstance(data_source, DataSource): - pass - else: + elif not isinstance(data_source, DataSource): raise TypeError( "Data source parameter must be a string or a DataSource object." ) @@ -179,10 +177,7 @@ def get_kwargs_str(field_name): kwlist.append("null=True") if field_name.lower() in blank_fields: kwlist.append("blank=True") - if kwlist: - return ", " + ", ".join(kwlist) - else: - return "" + return ", " + ", ".join(kwlist) if kwlist else "" # For those wishing to disable the imports. if imports: @@ -191,7 +186,7 @@ def get_kwargs_str(field_name): yield "" yield "" - yield "class %s(models.Model):" % model_name + yield f"class {model_name}(models.Model):" for field_name, width, precision, field_type in zip( ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types @@ -218,25 +213,21 @@ def get_kwargs_str(field_name): kwargs_str, ) else: - yield " %s = models.FloatField(%s)" % (mfield, kwargs_str[2:]) + yield f" {mfield} = models.FloatField({kwargs_str[2:]})" elif field_type is OFTInteger: - yield " %s = models.IntegerField(%s)" % (mfield, kwargs_str[2:]) + yield f" {mfield} = models.IntegerField({kwargs_str[2:]})" elif field_type is OFTInteger64: - yield " %s = models.BigIntegerField(%s)" % (mfield, kwargs_str[2:]) + yield f" {mfield} = models.BigIntegerField({kwargs_str[2:]})" elif field_type is OFTString: - yield " %s = models.CharField(max_length=%s%s)" % ( - mfield, - width, - kwargs_str, - ) + yield f" {mfield} = models.CharField(max_length={width}{kwargs_str})" elif field_type is OFTDate: - yield " %s = models.DateField(%s)" % (mfield, kwargs_str[2:]) + yield f" {mfield} = models.DateField({kwargs_str[2:]})" elif field_type is OFTDateTime: - yield " %s = models.DateTimeField(%s)" % (mfield, kwargs_str[2:]) + yield f" {mfield} = models.DateTimeField({kwargs_str[2:]})" elif field_type is OFTTime: - yield " %s = models.TimeField(%s)" % (mfield, kwargs_str[2:]) + yield f" {mfield} = models.TimeField({kwargs_str[2:]})" else: - raise TypeError("Unknown field type %s in %s" % (field_type, mfield)) + raise TypeError(f"Unknown field type {field_type} in {mfield}") # TODO: Autodetection of multigeometry types (see #7218). gtype = layer.geom_type @@ -256,12 +247,12 @@ def get_kwargs_str(field_name): # WGS84 is already the default. srid_str = "" else: - srid_str = "srid=%s" % srid + srid_str = f"srid={srid}" else: - srid_str = "srid=%s" % srid + srid_str = f"srid={srid}" - yield " %s = models.%s(%s)" % (geom_name, geom_field, srid_str) + yield f" {geom_name} = models.{geom_field}({srid_str})" if name_field: yield "" - yield " def __str__(self): return self.%s" % name_field + yield f" def __str__(self): return self.{name_field}" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/views.py index 346fb5b0..59b4418b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/gis/views.py @@ -15,8 +15,8 @@ def feed(request, url, feed_dict=None): instance = f() instance.feed_url = getattr(f, "feed_url", None) or request.path - instance.title_template = f.title_template or ("feeds/%s_title.html" % slug) - instance.description_template = f.description_template or ( - "feeds/%s_description.html" % slug + instance.title_template = f.title_template or f"feeds/{slug}_title.html" + instance.description_template = ( + f.description_template or f"feeds/{slug}_description.html" ) return instance(request) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/humanize/templatetags/humanize.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/humanize/templatetags/humanize.py index 07bb70b1..2c0cb923 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/humanize/templatetags/humanize.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/humanize/templatetags/humanize.py @@ -77,10 +77,7 @@ def intcomma(value, use_l10n=True): return number_format(value, use_l10n=True, force_grouping=True) orig = str(value) new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1>,\g<2>", orig) - if orig == new: - return new - else: - return intcomma(new, use_l10n) + return new if orig == new else intcomma(new, use_l10n) # A tuple of standard large number to their converters @@ -152,19 +149,21 @@ def apnumber(value): value = int(value) except (TypeError, ValueError): return value - if not 0 < value < 10: - return value return ( - _("one"), - _("two"), - _("three"), - _("four"), - _("five"), - _("six"), - _("seven"), - _("eight"), - _("nine"), - )[value - 1] + ( + _("one"), + _("two"), + _("three"), + _("four"), + _("five"), + _("six"), + _("seven"), + _("eight"), + _("nine"), + )[value - 1] + if 0 < value < 10 + else value + ) # Perform the comparison in the default time zone when USE_TZ = True diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/storage/base.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/storage/base.py index 61c5758a..ff96ab5f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/storage/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/storage/base.py @@ -25,9 +25,11 @@ def _prepare(self): self.extra_tags = str(self.extra_tags) if self.extra_tags is not None else None def __eq__(self, other): - if not isinstance(other, Message): - return NotImplemented - return self.level == other.level and self.message == other.message + return ( + self.level == other.level and self.message == other.message + if isinstance(other, Message) + else NotImplemented + ) def __str__(self): return str(self.message) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/views.py index 38dee9be..abe99f54 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/messages/views.py @@ -10,8 +10,7 @@ class SuccessMessageMixin: def form_valid(self, form): response = super().form_valid(form) - success_message = self.get_success_message(form.cleaned_data) - if success_message: + if success_message := self.get_success_message(form.cleaned_data): messages.success(self.request, success_message) return response diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/aggregates/mixins.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/aggregates/mixins.py index ca0f7c9c..0082fd61 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/aggregates/mixins.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/aggregates/mixins.py @@ -25,20 +25,20 @@ def resolve_expression(self, *args, **kwargs): return super().resolve_expression(*args, **kwargs) def as_sql(self, compiler, connection): - if self.ordering: - ordering_params = [] - ordering_expr_sql = [] - for expr in self.ordering: - expr_sql, expr_params = compiler.compile(expr) - ordering_expr_sql.append(expr_sql) - ordering_params.extend(expr_params) - sql, sql_params = super().as_sql( - compiler, - connection, - ordering=("ORDER BY " + ", ".join(ordering_expr_sql)), - ) - return sql, sql_params + ordering_params - return super().as_sql(compiler, connection, ordering="") + if not self.ordering: + return super().as_sql(compiler, connection, ordering="") + ordering_params = [] + ordering_expr_sql = [] + for expr in self.ordering: + expr_sql, expr_params = compiler.compile(expr) + ordering_expr_sql.append(expr_sql) + ordering_params.extend(expr_params) + sql, sql_params = super().as_sql( + compiler, + connection, + ordering=("ORDER BY " + ", ".join(ordering_expr_sql)), + ) + return sql, sql_params + ordering_params def set_source_expressions(self, exprs): # Extract the ordering expressions because ORDER BY clause is handled diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/constraints.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/constraints.py index c136de4c..09d6581e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/constraints.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/constraints.py @@ -78,13 +78,12 @@ def _get_expression_sql(self, compiler, schema_editor, query): if not isinstance(expression, Col): sql = f"({sql})" try: - opclass = self.opclasses[idx] - if opclass: - sql = "%s %s" % (sql, opclass) + if opclass := self.opclasses[idx]: + sql = f"{sql} {opclass}" except IndexError: pass sql = sql % tuple(schema_editor.quote_value(p) for p in params) - expressions.append("%s WITH %s" % (sql, operator)) + expressions.append(f"{sql} WITH {operator}") return expressions def _get_condition_sql(self, compiler, schema_editor, query): @@ -107,8 +106,10 @@ def constraint_sql(self, model, schema_editor): "index_type": self.index_type, "expressions": ", ".join(expressions), "include": schema_editor._index_include_sql(model, include), - "where": " WHERE (%s)" % condition if condition else "", - "deferrable": schema_editor._deferrable_constraint_sql(self.deferrable), + "where": f" WHERE ({condition})" if condition else "", + "deferrable": schema_editor._deferrable_constraint_sql( + self.deferrable + ), } def create_sql(self, model, schema_editor): @@ -164,13 +165,4 @@ def __eq__(self, other): return super().__eq__(other) def __repr__(self): - return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s>" % ( - self.__class__.__qualname__, - repr(self.index_type), - repr(self.expressions), - repr(self.name), - "" if self.condition is None else " condition=%s" % self.condition, - "" if self.deferrable is None else " deferrable=%r" % self.deferrable, - "" if not self.include else " include=%s" % repr(self.include), - "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses), - ) + return f'<{self.__class__.__qualname__}: index_type={repr(self.index_type)} expressions={repr(self.expressions)} name={repr(self.name)}{"" if self.condition is None else f" condition={self.condition}"}{"" if self.deferrable is None else " deferrable=%r" % self.deferrable}{f" include={repr(self.include)}" if self.include else ""}{f" opclasses={repr(self.opclasses)}" if self.opclasses else ""}>' diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/array.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/array.py index 72691986..86776f9a 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/array.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/array.py @@ -43,7 +43,7 @@ def model(self): return self.__dict__["model"] except KeyError: raise AttributeError( - "'%s' object has no attribute 'model'" % self.__class__.__name__ + f"'{self.__class__.__name__}' object has no attribute 'model'" ) @model.setter @@ -65,20 +65,15 @@ def check(self, **kwargs): id="postgres.E002", ) ) - else: - # Remove the field name checks as they are not needed here. - base_errors = self.base_field.check() - if base_errors: - messages = "\n ".join( - "%s (%s)" % (error.msg, error.id) for error in base_errors - ) - errors.append( - checks.Error( - "Base field for array has errors:\n %s" % messages, - obj=self, - id="postgres.E001", - ) + elif base_errors := self.base_field.check(): + messages = "\n ".join(f"{error.msg} ({error.id})" for error in base_errors) + errors.append( + checks.Error( + "Base field for array has errors:\n %s" % messages, + obj=self, + id="postgres.E001", ) + ) return errors def set_attributes_from_name(self, name): @@ -87,18 +82,18 @@ def set_attributes_from_name(self, name): @property def description(self): - return "Array of %s" % self.base_field.description + return f"Array of {self.base_field.description}" def db_type(self, connection): size = self.size or "" - return "%s[%s]" % (self.base_field.db_type(connection), size) + return f"{self.base_field.db_type(connection)}[{size}]" def cast_db_type(self, connection): size = self.size or "" - return "%s[%s]" % (self.base_field.cast_db_type(connection), size) + return f"{self.base_field.cast_db_type(connection)}[{size}]" def get_placeholder(self, value, compiler, connection): - return "%s::{}".format(self.db_type(connection)) + return f"%s::{self.db_type(connection)}" def get_db_prep_value(self, value, connection, prepared=False): if isinstance(value, (list, tuple)): @@ -149,8 +144,7 @@ def value_to_string(self, obj): return json.dumps(values) def get_transform(self, name): - transform = super().get_transform(name) - if transform: + if transform := super().get_transform(name): return transform if "_" not in name: try: @@ -181,12 +175,14 @@ def validate(self, value, model_instance): code="item_invalid", params={"nth": index + 1}, ) - if isinstance(self.base_field, ArrayField): - if len({len(i) for i in value}) > 1: - raise exceptions.ValidationError( - self.error_messages["nested_array_mismatch"], - code="nested_array_mismatch", - ) + if ( + isinstance(self.base_field, ArrayField) + and len({len(i) for i in value}) > 1 + ): + raise exceptions.ValidationError( + self.error_messages["nested_array_mismatch"], + code="nested_array_mismatch", + ) def run_validators(self, value): super().run_validators(value) @@ -231,7 +227,7 @@ def __init__(self, lhs, rhs): def process_rhs(self, compiler, connection): rhs, rhs_params = super().process_rhs(compiler, connection) cast_type = self.lhs.output_field.cast_db_type(connection) - return "%s::%s" % (rhs, cast_type), rhs_params + return f"{rhs}::{cast_type}", rhs_params @ArrayField.register_lookup diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/citext.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/citext.py index 2b943614..21e9a93a 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/citext.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/citext.py @@ -5,7 +5,7 @@ class CIText: def get_internal_type(self): - return "CI" + super().get_internal_type() + return f"CI{super().get_internal_type()}" def db_type(self, connection): return "citext" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/hstore.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/hstore.py index cfc156ab..6f8f76e5 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/hstore.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/hstore.py @@ -22,8 +22,7 @@ def db_type(self, connection): return "hstore" def get_transform(self, name): - transform = super().get_transform(name) - if transform: + if transform := super().get_transform(name): return transform return KeyTransformFactory(name) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/ranges.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/ranges.py index db3ca321..49afa5a5 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/ranges.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/fields/ranges.py @@ -29,7 +29,7 @@ def __init__(self, inclusive_lower=True, inclusive_upper=False): self.upper = "]" if inclusive_upper else ")" def as_sql(self, compiler, connection): - return "'%s%s'" % (self.lower, self.upper), [] + return f"'{self.lower}{self.upper}'", [] class RangeOperators: @@ -62,7 +62,7 @@ def model(self): return self.__dict__["model"] except KeyError: raise AttributeError( - "'%s' object has no attribute 'model'" % self.__class__.__name__ + f"'{self.__class__.__name__}' object has no attribute 'model'" ) @model.setter @@ -201,8 +201,8 @@ def as_postgresql(self, compiler, connection): ) ): cast_internal_type = self.lhs.output_field.base_field.get_internal_type() - cast_sql = "::{}".format(connection.data_types.get(cast_internal_type)) - return "%s%s" % (sql, cast_sql), params + cast_sql = f"::{connection.data_types.get(cast_internal_type)}" + return f"{sql}{cast_sql}", params DateRangeField.register_lookup(DateTimeRangeContains) @@ -227,14 +227,14 @@ def process_rhs(self, compiler, connection): # Ignore precision for DecimalFields. db_type = self.lhs.output_field.cast_db_type(connection).split("(")[0] cast_type = self.type_mapping[db_type] - return "%s::%s" % (rhs, cast_type), rhs_params + return f"{rhs}::{cast_type}", rhs_params def process_lhs(self, compiler, connection): lhs, lhs_params = super().process_lhs(compiler, connection) if isinstance(self.lhs.output_field, models.FloatField): - lhs = "%s::numeric" % lhs + lhs = f"{lhs}::numeric" elif isinstance(self.lhs.output_field, models.SmallIntegerField): - lhs = "%s::integer" % lhs + lhs = f"{lhs}::integer" return lhs, lhs_params def get_prep_lookup(self): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/array.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/array.py index ddb022af..968eac6a 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/array.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/array.py @@ -127,13 +127,13 @@ def is_hidden(self): def value_from_datadict(self, data, files, name): return [ - self.widget.value_from_datadict(data, files, "%s_%s" % (name, index)) + self.widget.value_from_datadict(data, files, f"{name}_{index}") for index in range(self.size) ] def value_omitted_from_data(self, data, files, name): return all( - self.widget.value_omitted_from_data(data, files, "%s_%s" % (name, index)) + self.widget.value_omitted_from_data(data, files, f"{name}_{index}") for index in range(self.size) ) @@ -158,9 +158,9 @@ def get_context(self, name, value, attrs=None): except IndexError: widget_value = None if id_: - final_attrs = {**final_attrs, "id": "%s_%s" % (id_, i)} + final_attrs = {**final_attrs, "id": f"{id_}_{i}"} context["widget"]["subwidgets"].append( - self.widget.get_context(name + "_%s" % i, widget_value, final_attrs)[ + self.widget.get_context(f"{name}_{i}", widget_value, final_attrs)[ "widget" ] ) @@ -234,8 +234,7 @@ def clean(self, value): cleaned_data, null_index = self._remove_trailing_nulls(cleaned_data) if null_index is not None: errors = errors[:null_index] - errors = list(filter(None, errors)) - if errors: + if errors := list(filter(None, errors)): raise ValidationError(list(chain.from_iterable(errors))) return cleaned_data diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/hstore.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/hstore.py index 6a20f7b7..882ee5dd 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/hstore.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/hstore.py @@ -19,9 +19,7 @@ class HStoreField(forms.CharField): } def prepare_value(self, value): - if isinstance(value, dict): - return json.dumps(value) - return value + return json.dumps(value) if isinstance(value, dict) else value def to_python(self, value): if not value: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/ranges.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/ranges.py index 915c0b5a..f631e115 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/ranges.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/forms/ranges.py @@ -22,9 +22,7 @@ def __init__(self, base_widget, attrs=None): super().__init__(widgets, attrs) def decompress(self, value): - if value: - return (value.lower, value.upper) - return (None, None) + return (value.lower, value.upper) if value else (None, None) class HiddenRangeWidget(RangeWidget): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/indexes.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/indexes.py index 524cdadc..36a42c7b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/indexes.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/indexes.py @@ -25,14 +25,12 @@ def max_name_length(self): def create_sql(self, model, schema_editor, using="", **kwargs): self.check_supported(schema_editor) statement = super().create_sql( - model, schema_editor, using=" USING %s" % self.suffix, **kwargs + model, schema_editor, using=f" USING {self.suffix}", **kwargs ) - with_params = self.get_with_params() - if with_params: - statement.parts["extra"] = "WITH (%s) %s" % ( - ", ".join(with_params), - statement.parts["extra"], - ) + if with_params := self.get_with_params(): + statement.parts[ + "extra" + ] = f'WITH ({", ".join(with_params)}) {statement.parts["extra"]}' return statement def check_supported(self, schema_editor): @@ -106,9 +104,7 @@ def deconstruct(self): def get_with_params(self): with_params = [] if self.autosummarize is not None: - with_params.append( - "autosummarize = %s" % ("on" if self.autosummarize else "off") - ) + with_params.append(f'autosummarize = {"on" if self.autosummarize else "off"}') if self.pages_per_range is not None: with_params.append("pages_per_range = %d" % self.pages_per_range) return with_params @@ -159,7 +155,7 @@ def get_with_params(self): "gin_pending_list_limit = %d" % self.gin_pending_list_limit ) if self.fastupdate is not None: - with_params.append("fastupdate = %s" % ("on" if self.fastupdate else "off")) + with_params.append(f'fastupdate = {"on" if self.fastupdate else "off"}') return with_params @@ -182,7 +178,7 @@ def deconstruct(self): def get_with_params(self): with_params = [] if self.buffering is not None: - with_params.append("buffering = %s" % ("on" if self.buffering else "off")) + with_params.append(f'buffering = {"on" if self.buffering else "off"}') if self.fillfactor is not None: with_params.append("fillfactor = %d" % self.fillfactor) return with_params diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/operations.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/operations.py index b2d6d9f9..00402690 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/operations.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/operations.py @@ -25,8 +25,7 @@ def database_forwards(self, app_label, schema_editor, from_state, to_state): return if not self.extension_exists(schema_editor, self.name): schema_editor.execute( - "CREATE EXTENSION IF NOT EXISTS %s" - % schema_editor.quote_name(self.name) + f"CREATE EXTENSION IF NOT EXISTS {schema_editor.quote_name(self.name)}" ) # Clear cached, stale oids. get_hstore_oids.cache_clear() @@ -41,7 +40,7 @@ def database_backwards(self, app_label, schema_editor, from_state, to_state): return if self.extension_exists(schema_editor, self.name): schema_editor.execute( - "DROP EXTENSION IF EXISTS %s" % schema_editor.quote_name(self.name) + f"DROP EXTENSION IF EXISTS {schema_editor.quote_name(self.name)}" ) # Clear cached, stale oids. get_hstore_oids.cache_clear() @@ -56,11 +55,11 @@ def extension_exists(self, schema_editor, extension): return bool(cursor.fetchone()) def describe(self): - return "Creates extension %s" % self.name + return f"Creates extension {self.name}" @property def migration_name_fragment(self): - return "create_extension_%s" % self.name + return f"create_extension_{self.name}" class BloomExtension(CreateExtension): @@ -118,11 +117,7 @@ class AddIndexConcurrently(NotInTransactionMixin, AddIndex): atomic = False def describe(self): - return "Concurrently create index %s on field(s) %s of model %s" % ( - self.index.name, - ", ".join(self.index.fields), - self.model_name, - ) + return f'Concurrently create index {self.index.name} on field(s) {", ".join(self.index.fields)} of model {self.model_name}' def database_forwards(self, app_label, schema_editor, from_state, to_state): self._ensure_not_in_transaction(schema_editor) @@ -143,7 +138,7 @@ class RemoveIndexConcurrently(NotInTransactionMixin, RemoveIndex): atomic = False def describe(self): - return "Concurrently remove index %s from %s" % (self.name, self.model_name) + return f"Concurrently remove index {self.name} from {self.model_name}" def database_forwards(self, app_label, schema_editor, from_state, to_state): self._ensure_not_in_transaction(schema_editor) @@ -207,9 +202,7 @@ def create_collation(self, schema_editor): ) def remove_collation(self, schema_editor): - schema_editor.execute( - "DROP COLLATION %s" % schema_editor.quote_name(self.name), - ) + schema_editor.execute(f"DROP COLLATION {schema_editor.quote_name(self.name)}") class CreateCollation(CollationOperation): @@ -232,7 +225,7 @@ def describe(self): @property def migration_name_fragment(self): - return "create_collation_%s" % self.name.lower() + return f"create_collation_{self.name.lower()}" class RemoveCollation(CollationOperation): @@ -255,7 +248,7 @@ def describe(self): @property def migration_name_fragment(self): - return "remove_collation_%s" % self.name.lower() + return f"remove_collation_{self.name.lower()}" class AddConstraintNotValid(AddConstraint): @@ -272,24 +265,20 @@ def __init__(self, model_name, constraint): super().__init__(model_name, constraint) def describe(self): - return "Create not valid constraint %s on model %s" % ( - self.constraint.name, - self.model_name, - ) + return f"Create not valid constraint {self.constraint.name} on model {self.model_name}" def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): - constraint_sql = self.constraint.create_sql(model, schema_editor) - if constraint_sql: + if constraint_sql := self.constraint.create_sql(model, schema_editor): # Constraint.create_sql returns interpolated SQL which makes # params=None a necessity to avoid escaping attempts on # execution. - schema_editor.execute(str(constraint_sql) + " NOT VALID", params=None) + schema_editor.execute(f"{str(constraint_sql)} NOT VALID", params=None) @property def migration_name_fragment(self): - return super().migration_name_fragment + "_not_valid" + return f"{super().migration_name_fragment}_not_valid" class ValidateConstraint(Operation): @@ -300,17 +289,13 @@ def __init__(self, model_name, name): self.name = name def describe(self): - return "Validate constraint %s on model %s" % (self.name, self.model_name) + return f"Validate constraint {self.name} on model {self.model_name}" def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.execute( - "ALTER TABLE %s VALIDATE CONSTRAINT %s" - % ( - schema_editor.quote_name(model._meta.db_table), - schema_editor.quote_name(self.name), - ) + f"ALTER TABLE {schema_editor.quote_name(model._meta.db_table)} VALIDATE CONSTRAINT {schema_editor.quote_name(self.name)}" ) def database_backwards(self, app_label, schema_editor, from_state, to_state): @@ -322,7 +307,7 @@ def state_forwards(self, app_label, state): @property def migration_name_fragment(self): - return "%s_validate_%s" % (self.model_name.lower(), self.name.lower()) + return f"{self.model_name.lower()}_validate_{self.name.lower()}" def deconstruct(self): return ( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/search.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/search.py index f652c1d3..a6e00c1f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/search.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/search.py @@ -28,7 +28,7 @@ def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params - return "%s @@ %s" % (lhs, rhs), params + return f"{lhs} @@ {rhs}", params class SearchVectorField(Field): @@ -50,9 +50,7 @@ def __init__(self, config): @classmethod def from_parameter(cls, config): - if config is None or isinstance(config, cls): - return config - return cls(config) + return config if config is None or isinstance(config, cls) else cls(config) def get_source_expressions(self): return [self.config] @@ -62,7 +60,7 @@ def set_source_expressions(self, exprs): def as_sql(self, compiler, connection): sql, params = compiler.compile(self.config) - return "%s::regconfig" % sql, params + return f"{sql}::regconfig", params class SearchVectorCombinable: @@ -134,7 +132,7 @@ def as_sql(self, compiler, connection, function=None, template=None): extra_params = [] if clone.weight: weight_sql, extra_params = compiler.compile(clone.weight) - sql = "setweight({}, {})".format(sql, weight_sql) + sql = f"setweight({sql}, {weight_sql})" return sql, config_params + params + extra_params @@ -194,7 +192,7 @@ def __init__( ): self.function = self.SEARCH_TYPES.get(search_type) if self.function is None: - raise ValueError("Unknown search_type argument '%s'." % search_type) + raise ValueError(f"Unknown search_type argument '{search_type}'.") if not hasattr(value, "resolve_expression"): value = Value(value) expressions = (value,) @@ -207,7 +205,7 @@ def __init__( def as_sql(self, compiler, connection, function=None, template=None): sql, params = super().as_sql(compiler, connection, function, template) if self.invert: - sql = "!!(%s)" % sql + sql = f"!!({sql})" return sql, params def __invert__(self): @@ -217,7 +215,7 @@ def __invert__(self): def __str__(self): result = super().__str__() - return ("~%s" % result) if self.invert else result + return f"~{result}" if self.invert else result class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression): @@ -226,7 +224,7 @@ def __init__(self, lhs, connector, rhs, config, output_field=None): super().__init__(lhs, connector, rhs, output_field) def __str__(self): - return "(%s)" % super().__str__() + return f"({super().__str__()})" class SearchRank(Func): @@ -307,11 +305,7 @@ def as_sql(self, compiler, connection, function=None, template=None): # getquoted() returns a quoted bytestring of the adapted value. options_params.append( ", ".join( - "%s=%s" - % ( - option, - psycopg2.extensions.adapt(value).getquoted().decode(), - ) + f"{option}={psycopg2.extensions.adapt(value).getquoted().decode()}" for option, value in self.options.items() ) ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/serializers.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/serializers.py index d04bfdbc..28fe808e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/serializers.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/serializers.py @@ -7,4 +7,4 @@ def serialize(self): # Ranges are implemented in psycopg2._range but the public import # location is psycopg2.extras. module = "psycopg2.extras" if module == "psycopg2._range" else module - return "%s.%r" % (module, self.value), {"import %s" % module} + return "%s.%r" % (module, self.value), {f"import {module}"} diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/validators.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/validators.py index 47bb7bc7..b07f9bc0 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/validators.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/postgres/validators.py @@ -48,16 +48,14 @@ def __init__(self, keys, strict=False, messages=None): def __call__(self, value): keys = set(value) - missing_keys = self.keys - keys - if missing_keys: + if missing_keys := self.keys - keys: raise ValidationError( self.messages["missing_keys"], code="missing_keys", params={"keys": ", ".join(missing_keys)}, ) if self.strict: - extra_keys = keys - self.keys - if extra_keys: + if extra_keys := keys - self.keys: raise ValidationError( self.messages["extra_keys"], code="extra_keys", diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/redirects/models.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/redirects/models.py index 15524149..cee41fdd 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/redirects/models.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/redirects/models.py @@ -32,4 +32,4 @@ class Meta: ordering = ["old_path"] def __str__(self): - return "%s ---> %s" % (self.old_path, self.new_path) + return f"{self.old_path} ---> {self.new_path}" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/base.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/base.py index 4b179326..48d6199f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/base.py @@ -62,7 +62,7 @@ def __delitem__(self, key): @property def key_salt(self): - return "django.contrib.sessions." + self.__class__.__qualname__ + return f"django.contrib.sessions.{self.__class__.__qualname__}" def get(self, key, default=None): return self._session.get(key, default) @@ -75,10 +75,9 @@ def pop(self, key, default=__not_given): def setdefault(self, key, value): if key in self._session: return self._session[key] - else: - self.modified = True - self._session[key] = value - return value + self.modified = True + self._session[key] = value + return value def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE @@ -169,10 +168,7 @@ def _set_session_key(self, value): """ Validate session key on assignment. Invalid values will set to None. """ - if self._validate_session_key(value): - self.__session_key = value - else: - self.__session_key = None + self.__session_key = value if self._validate_session_key(value) else None session_key = property(_get_session_key) _session_key = property(_get_session_key, _set_session_key) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cache.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cache.py index 0c9d244f..976857cd 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cache.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cache.py @@ -38,7 +38,7 @@ def create(self): # because the cache is missing. So we try for a (large) number of times # and then raise an exception. That's the risk you shoulder if using # cache backing. - for i in range(10000): + for _ in range(10000): self._session_key = self._get_new_session_key() try: self.save(must_create=True) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cached_db.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cached_db.py index 3125a71c..5ebcbb43 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cached_db.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/cached_db.py @@ -33,8 +33,7 @@ def load(self): data = None if data is None: - s = self._get_session_from_db() - if s: + if s := self._get_session_from_db(): data = self.decode(s.session_data) self._cache.set( self.cache_key, data, self.get_expiry_age(expiry=s.expire_date) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py index e1f6b69c..781d04f7 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py @@ -34,7 +34,7 @@ def _get_session_from_db(self): ) except (self.model.DoesNotExist, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): - logger = logging.getLogger("django.security.%s" % e.__class__.__name__) + logger = logging.getLogger(f"django.security.{e.__class__.__name__}") logger.warning(str(e)) self._session_key = None diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/file.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/file.py index 94738833..f763235a 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/file.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sessions/backends/file.py @@ -89,9 +89,7 @@ def load(self): session_data = self.decode(file_data) except (EOFError, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): - logger = logging.getLogger( - "django.security.%s" % e.__class__.__name__ - ) + logger = logging.getLogger(f"django.security.{e.__class__.__name__}") logger.warning(str(e)) self.create() @@ -158,7 +156,7 @@ def save(self, must_create=False): try: output_file_fd, output_file_name = tempfile.mkstemp( - dir=dir, prefix=prefix + "_out_" + dir=dir, prefix=f"{prefix}_out_" ) renamed = False try: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/__init__.py index 8dc6b589..5b3525c1 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/__init__.py @@ -26,7 +26,7 @@ def ping_google(sitemap_url=None, ping_url=PING_URL, sitemap_uses_https=True): """ sitemap_full_url = _get_sitemap_full_url(sitemap_url, sitemap_uses_https) params = urlencode({"sitemap": sitemap_full_url}) - urlopen("%s?%s" % (ping_url, params)) + urlopen(f"{ping_url}?{params}") def _get_sitemap_full_url(sitemap_url, sitemap_uses_https=True): @@ -55,7 +55,7 @@ def _get_sitemap_full_url(sitemap_url, sitemap_uses_https=True): Site = django_apps.get_model("sites.Site") current_site = Site.objects.get_current() scheme = "https" if sitemap_uses_https else "http" - return "%s://%s%s" % (scheme, current_site.domain, sitemap_url) + return f"{scheme}://{current_site.domain}{sitemap_url}" class Sitemap: @@ -99,14 +99,11 @@ def _languages(self): def _items(self): if self.i18n: - # Create (item, lang_code) tuples for all items and languages. - # This is necessary to paginate with all languages already considered. - items = [ + return [ (item, lang_code) for lang_code in self._languages() for item in self.items() ] - return items return self.items() def _location(self, item, force_lang_code=None): @@ -143,18 +140,17 @@ def get_protocol(self, protocol=None): def get_domain(self, site=None): # Determine domain + if site is None and django_apps.is_installed("django.contrib.sites"): + Site = django_apps.get_model("sites.Site") + try: + site = Site.objects.get_current() + except Site.DoesNotExist: + pass if site is None: - if django_apps.is_installed("django.contrib.sites"): - Site = django_apps.get_model("sites.Site") - try: - site = Site.objects.get_current() - except Site.DoesNotExist: - pass - if site is None: - raise ImproperlyConfigured( - "To use sitemaps, either enable the sites framework or pass " - "a Site/RequestSite object in your view." - ) + raise ImproperlyConfigured( + "To use sitemaps, either enable the sites framework or pass " + "a Site/RequestSite object in your view." + ) return site.domain def get_urls(self, page=1, site=None, protocol=None): @@ -175,10 +171,10 @@ def _urls(self, page, protocol, domain): if all_items_lastmod: all_items_lastmod = lastmod is not None - if all_items_lastmod and ( - latest_lastmod is None or lastmod > latest_lastmod - ): - latest_lastmod = lastmod + if all_items_lastmod and ( + latest_lastmod is None or lastmod > latest_lastmod + ): + latest_lastmod = lastmod url_info = { "item": item, @@ -233,6 +229,4 @@ def items(self): return self.queryset.filter() def lastmod(self, item): - if self.date_field is not None: - return getattr(item, self.date_field) - return None + return getattr(item, self.date_field) if self.date_field is not None else None diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/views.py index cd315fa0..ea9dde6b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sitemaps/views.py @@ -40,12 +40,13 @@ def index( site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = reverse(sitemap_url_name, kwargs={"section": section}) - absolute_url = "%s://%s%s" % (protocol, req_site.domain, sitemap_url) + absolute_url = f"{protocol}://{req_site.domain}{sitemap_url}" sites.append(absolute_url) # Add links to all pages of the sitemap. - for page in range(2, site.paginator.num_pages + 1): - sites.append("%s?p=%s" % (absolute_url, page)) - + sites.extend( + f"{absolute_url}?p={page}" + for page in range(2, site.paginator.num_pages + 1) + ) return TemplateResponse( request, template_name, {"sitemaps": sites}, content_type=content_type ) @@ -63,12 +64,12 @@ def sitemap( req_protocol = request.scheme req_site = get_current_site(request) - if section is not None: - if section not in sitemaps: - raise Http404("No sitemap available for section: %r" % section) - maps = [sitemaps[section]] - else: + if section is None: maps = sitemaps.values() + elif section not in sitemaps: + raise Http404("No sitemap available for section: %r" % section) + else: + maps = [sitemaps[section]] page = request.GET.get("p", 1) lastmod = None @@ -94,9 +95,9 @@ def sitemap( else: all_sites_lastmod = False except EmptyPage: - raise Http404("Page %s empty" % page) + raise Http404(f"Page {page} empty") except PageNotAnInteger: - raise Http404("No page '%s'" % page) + raise Http404(f"No page '{page}'") response = TemplateResponse( request, template_name, {"urlset": urls}, content_type=content_type ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/management.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/management.py index dd75bc1b..7b82eacf 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/management.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/management.py @@ -36,10 +36,9 @@ def create_default_site( pk=getattr(settings, "SITE_ID", 1), domain="example.com", name="example.com" ).save(using=using) - # We set an explicit pk instead of relying on auto-incrementation, - # so we need to reset the database sequence. See #17415. - sequence_sql = connections[using].ops.sequence_reset_sql(no_style(), [Site]) - if sequence_sql: + if sequence_sql := connections[using].ops.sequence_reset_sql( + no_style(), [Site] + ): if verbosity >= 2: print("Resetting sequence") with connections[using].cursor() as cursor: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/managers.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/managers.py index ec288265..fd4b64eb 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/managers.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/sites/managers.py @@ -25,25 +25,24 @@ def _check_field_name(self): except FieldDoesNotExist: return [ checks.Error( - "CurrentSiteManager could not find a field named '%s'." - % field_name, + f"CurrentSiteManager could not find a field named '{field_name}'.", obj=self, id="sites.E001", ) ] - if not field.many_to_many and not isinstance(field, (models.ForeignKey)): - return [ + return ( + [ checks.Error( - "CurrentSiteManager cannot use '%s.%s' as it is not a foreign key " - "or a many-to-many field." - % (self.model._meta.object_name, field_name), + f"CurrentSiteManager cannot use '{self.model._meta.object_name}.{field_name}' as it is not a foreign key or a many-to-many field.", obj=self, id="sites.E002", ) ] - - return [] + if not field.many_to_many + and not isinstance(field, (models.ForeignKey)) + else [] + ) def _get_field_name(self): """Return self.__field_name or 'site' or 'sites'.""" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py index 184d2975..2a315e97 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py @@ -121,8 +121,7 @@ def find(self, path, all=False): for prefix, root in self.locations: if root not in searched_locations: searched_locations.append(root) - matched_path = self.find_location(root, path, prefix) - if matched_path: + if matched_path := self.find_location(root, path, prefix): if not all: return matched_path matches.append(matched_path) @@ -134,7 +133,7 @@ def find_location(self, root, path, prefix=None): absolute path (or ``None`` if no match). """ if prefix: - prefix = "%s%s" % (prefix, os.sep) + prefix = f"{prefix}{os.sep}" if not path.startswith(prefix): return None path = path[len(prefix) :] @@ -200,8 +199,7 @@ def find(self, path, all=False): app_location = self.storages[app].location if app_location not in searched_locations: searched_locations.append(app_location) - match = self.find_in_app(app, path) - if match: + if match := self.find_in_app(app, path): if not all: return match matches.append(match) @@ -214,8 +212,7 @@ def find_in_app(self, app, path): storage = self.storages.get(app) # Only try to find a file if the source dir actually exists. if storage and storage.exists(path): - matched_path = storage.path(path) - if matched_path: + if matched_path := storage.path(path): return matched_path @@ -321,6 +318,6 @@ def get_finder(import_path): Finder = import_string(import_path) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured( - 'Finder "%s" is not a subclass of "%s"' % (Finder, BaseFinder) + f'Finder "{Finder}" is not a subclass of "{BaseFinder}"' ) return Finder() diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py index da53149e..082001d5 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py @@ -76,9 +76,11 @@ def __init__(self, application): super().__init__() def __call__(self, environ, start_response): - if not self._should_handle(get_path_info(environ)): - return self.application(environ, start_response) - return super().__call__(environ, start_response) + return ( + super().__call__(environ, start_response) + if self._should_handle(get_path_info(environ)) + else self.application(environ, start_response) + ) class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py index c346038d..8ac5b26e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py @@ -116,12 +116,8 @@ def collect(self): if self.clear: self.clear_dir("") - if self.symlink: - handler = self.link_file - else: - handler = self.copy_file - found_files = {} + handler = self.link_file if self.symlink else self.copy_file for finder in get_finders(): for path, storage in finder.list(self.ignore_patterns): # Prefix the relative path if the source storage contains it @@ -135,10 +131,7 @@ def collect(self): handler(path, prefixed_path, storage) else: self.log( - "Found another file with the destination path '%s'. It " - "will be ignored since only the first encountered file " - "is collected. If this is not what you want, make sure " - "every static file has a unique path." % prefixed_path, + f"Found another file with the destination path '{prefixed_path}'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.", level=1, ) @@ -147,19 +140,16 @@ def collect(self): processor = self.storage.post_process(found_files, dry_run=self.dry_run) for original_path, processed_path, processed in processor: if isinstance(processed, Exception): - self.stderr.write("Post-processing '%s' failed!" % original_path) + self.stderr.write(f"Post-processing '{original_path}' failed!") # Add a blank line before the traceback, otherwise it's # too easy to miss the relevant part of the error message. self.stderr.write() raise processed if processed: - self.log( - "Post-processed '%s' as '%s'" % (original_path, processed_path), - level=2, - ) + self.log(f"Post-processed '{original_path}' as '{processed_path}'", level=2) self.post_processed_files.append(original_path) else: - self.log("Skipped post-processing '%s'" % original_path) + self.log(f"Skipped post-processing '{original_path}'") return { "modified": self.copied_files + self.symlinked_files, @@ -215,24 +205,22 @@ def handle(self, **options): return ( "\n%(modified_count)s %(identifier)s %(action)s" "%(destination)s%(unmodified)s%(post_processed)s." - ) % { - "modified_count": modified_count, - "identifier": "static file" + ("" if modified_count == 1 else "s"), - "action": "symlinked" if self.symlink else "copied", - "destination": ( - " to '%s'" % destination_path if destination_path else "" - ), - "unmodified": ( - ", %s unmodified" % unmodified_count + % { + "modified_count": modified_count, + "identifier": "static file" + + ("" if modified_count == 1 else "s"), + "action": "symlinked" if self.symlink else "copied", + "destination": f" to '{destination_path}'" + if destination_path + else "", + "unmodified": f", {unmodified_count} unmodified" if collected["unmodified"] - else "" - ), - "post_processed": ( - collected["post_processed"] - and ", %s post-processed" % post_processed_count - or "" - ), - } + else "", + "post_processed": collected["post_processed"] + and f", {post_processed_count} post-processed" + or "", + } + ) def log(self, msg, level=2): """ @@ -255,9 +243,9 @@ def clear_dir(self, path): for f in files: fpath = os.path.join(path, f) if self.dry_run: - self.log("Pretending to delete '%s'" % fpath, level=1) + self.log(f"Pretending to delete '{fpath}'", level=1) else: - self.log("Deleting '%s'" % fpath, level=1) + self.log(f"Deleting '{fpath}'", level=1) try: full_path = self.storage.path(fpath) except NotImplementedError: @@ -312,13 +300,13 @@ def delete_file(self, path, prefixed_path, source_storage): if file_is_unmodified and can_skip_unmodified_files: if prefixed_path not in self.unmodified_files: self.unmodified_files.append(prefixed_path) - self.log("Skipping '%s' (not modified)" % path) + self.log(f"Skipping '{path}' (not modified)") return False # Then delete the existing file if really needed if self.dry_run: - self.log("Pretending to delete '%s'" % path) + self.log(f"Pretending to delete '{path}'") else: - self.log("Deleting '%s'" % path) + self.log(f"Deleting '{path}'") self.storage.delete(prefixed_path) return True @@ -328,7 +316,7 @@ def link_file(self, path, prefixed_path, source_storage): """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: - return self.log("Skipping '%s' (already linked earlier)" % path) + return self.log(f"Skipping '{path}' (already linked earlier)") # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return @@ -336,9 +324,9 @@ def link_file(self, path, prefixed_path, source_storage): source_path = source_storage.path(path) # Finally link the file if self.dry_run: - self.log("Pretending to link '%s'" % source_path, level=1) + self.log(f"Pretending to link '{source_path}'", level=1) else: - self.log("Linking '%s'" % source_path, level=2) + self.log(f"Linking '{source_path}'", level=2) full_path = self.storage.path(prefixed_path) os.makedirs(os.path.dirname(full_path), exist_ok=True) try: @@ -363,7 +351,7 @@ def copy_file(self, path, prefixed_path, source_storage): """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: - return self.log("Skipping '%s' (already copied earlier)" % path) + return self.log(f"Skipping '{path}' (already copied earlier)") # Delete the target file if needed or break if not self.delete_file(path, prefixed_path, source_storage): return @@ -371,9 +359,9 @@ def copy_file(self, path, prefixed_path, source_storage): source_path = source_storage.path(path) # Finally start copying if self.dry_run: - self.log("Pretending to copy '%s'" % source_path, level=1) + self.log(f"Pretending to copy '{source_path}'", level=1) else: - self.log("Copying '%s'" % source_path, level=2) + self.log(f"Copying '{source_path}'", level=2) with source_storage.open(path) as source_file: self.storage.save(prefixed_path, source_file) self.copied_files.append(prefixed_path) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/findstatic.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/findstatic.py index 97413a64..f39eaa49 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/findstatic.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/findstatic.py @@ -31,17 +31,16 @@ def handle_label(self, path, **options): if not isinstance(result, (list, tuple)): result = [result] result = (os.path.realpath(path) for path in result) - if verbosity >= 1: - file_list = "\n ".join(result) - return "Found '%s' here:\n %s%s" % ( - path, - file_list, - searched_locations, - ) - else: + if verbosity < 1: return "\n".join(result) + file_list = "\n ".join(result) + return "Found '%s' here:\n %s%s" % ( + path, + file_list, + searched_locations, + ) else: - message = ["No matching file found for '%s'." % path] + message = [f"No matching file found for '{path}'."] if verbosity >= 2: message.append(searched_locations) if verbosity >= 1: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py index 38d2dfb2..07b0e142 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/storage.py @@ -118,8 +118,8 @@ def hashed_name(self, name, content=None, filename=None): content.close() path, filename = os.path.split(clean_name) root, ext = os.path.splitext(filename) - file_hash = (".%s" % file_hash) if file_hash else "" - hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext)) + file_hash = f".{file_hash}" if file_hash else "" + hashed_name = os.path.join(path, f"{root}{file_hash}{ext}") unparsed_name = list(parsed_name) unparsed_name[2] = hashed_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") @@ -268,7 +268,7 @@ def post_process(self, paths, dry_run=False, **options): paths = {path: paths[path] for path in adjustable_paths} substitutions = False - for i in range(self.max_post_process_passes): + for _ in range(self.max_post_process_passes): substitutions = False for name, hashed_name, processed, subst in self._post_process( paths, adjustable_paths, hashed_files @@ -350,13 +350,10 @@ def path_level(name): substitutions = False processed = True - if not processed: - # or handle the case in which neither processing nor - # a change to the original file happened - if not hashed_file_exists: - processed = True - saved_name = self._save(hashed_name, original_file) - hashed_name = self.clean_name(saved_name) + if not processed and not hashed_file_exists: + processed = True + saved_name = self._save(hashed_name, original_file) + hashed_name = self.clean_name(saved_name) # and then set the cache accordingly hashed_files[hash_key] = hashed_name @@ -384,12 +381,11 @@ def _stored_name(self, name, hashed_files): def stored_name(self, name): cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) - cache_name = self.hashed_files.get(hash_key) - if cache_name: + if cache_name := self.hashed_files.get(hash_key): return cache_name # No cached name found, recalculate it from the files. intermediate_name = name - for i in range(self.max_post_process_passes + 1): + for _ in range(self.max_post_process_passes + 1): cache_name = self.clean_name( self.hashed_name(name, content=None, filename=intermediate_name) ) @@ -438,8 +434,7 @@ def load_manifest(self): if version == "1.0": return stored.get("paths", {}) raise ValueError( - "Couldn't load manifest '%s' (version %s)" - % (self.manifest_name, self.manifest_version) + f"Couldn't load manifest '{self.manifest_name}' (version {self.manifest_version})" ) def post_process(self, *args, **kwargs): @@ -462,9 +457,7 @@ def stored_name(self, name): cache_name = self.hashed_files.get(hash_key) if cache_name is None: if self.manifest_strict: - raise ValueError( - "Missing staticfiles manifest entry for '%s'" % clean_name - ) + raise ValueError(f"Missing staticfiles manifest entry for '{clean_name}'") cache_name = self.clean_name(self.hashed_name(name)) unparsed_name = list(parsed_name) unparsed_name[2] = cache_name diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/views.py index 83d04d4c..3f199d0e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/staticfiles/views.py @@ -34,6 +34,6 @@ def serve(request, path, insecure=False, **kwargs): if not absolute_path: if path.endswith("/") or path == "": raise Http404("Directory indexes are not allowed here.") - raise Http404("'%s' could not be found" % path) + raise Http404(f"'{path}' could not be found") document_root, path = os.path.split(absolute_path) return static.serve(request, path, document_root=document_root, **kwargs) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/contrib/syndication/views.py b/unicoding_venv/lib/python3.9/site-packages/django/contrib/syndication/views.py index a9d1bff5..772fd41b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/contrib/syndication/views.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/contrib/syndication/views.py @@ -14,9 +14,9 @@ def add_domain(domain, url, secure=False): protocol = "https" if secure else "http" if url.startswith("//"): # Support network-path reference (see #16753) - RSS requires a protocol - url = "%s:%s" % (protocol, url) + url = f"{protocol}:{url}" elif not url.startswith(("http://", "https://", "mailto:")): - url = iri_to_uri("%s://%s%s" % (protocol, domain, url)) + url = iri_to_uri(f"{protocol}://{domain}{url}") return url @@ -63,8 +63,7 @@ def item_link(self, item): ) def item_enclosures(self, item): - enc_url = self._get_dynamic_attr("item_enclosure_url", item) - if enc_url: + if enc_url := self._get_dynamic_attr("item_enclosure_url", item): enc = feedgenerator.Enclosure( url=str(enc_url), length=str(self._get_dynamic_attr("item_enclosure_length", item)), @@ -86,10 +85,7 @@ def _get_dynamic_attr(self, attname, obj, default=None): code = attr.__code__ except AttributeError: code = attr.__call__.__code__ - if code.co_argcount == 2: # one argument is 'self' - return attr(obj) - else: - return attr() + return attr(obj) if code.co_argcount == 2 else attr() return attr def feed_extra_kwargs(self, obj): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/__init__.py index f09c9ecc..76e2abdf 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/__init__.py @@ -47,7 +47,7 @@ def create_connection(self, alias): backend_cls = import_string(backend) except ImportError as e: raise InvalidCacheBackendError( - "Could not find backend '%s': %s" % (backend, e) + f"Could not find backend '{backend}': {e}" ) from e return backend_cls(location, params) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/base.py b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/base.py index eb4b3eac..1dcc90a2 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/base.py @@ -36,7 +36,7 @@ def default_key_func(key, key_prefix, version): the `key_prefix`. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ - return "%s:%s:%s" % (key_prefix, version, key) + return f"{key_prefix}:{version}:{key}" def get_key_func(key_func): @@ -46,10 +46,7 @@ def get_key_func(key_func): Default to ``default_key_func``. """ if key_func is not None: - if callable(key_func): - return key_func - else: - return import_string(key_func) + return key_func if callable(key_func) else import_string(key_func) return default_key_func @@ -265,7 +262,7 @@ def incr(self, key, delta=1, version=None): """ value = self.get(key, self._missing_key, version=version) if value is self._missing_key: - raise ValueError("Key '%s' not found" % key) + raise ValueError(f"Key '{key}' not found") new_value = value + delta self.set(key, new_value, version=version) return new_value @@ -274,7 +271,7 @@ async def aincr(self, key, delta=1, version=None): """See incr().""" value = await self.aget(key, self._missing_key, version=version) if value is self._missing_key: - raise ValueError("Key '%s' not found" % key) + raise ValueError(f"Key '{key}' not found") new_value = value + delta await self.aset(key, new_value, version=version) return new_value @@ -351,7 +348,7 @@ def incr_version(self, key, delta=1, version=None): value = self.get(key, self._missing_key, version=version) if value is self._missing_key: - raise ValueError("Key '%s' not found" % key) + raise ValueError(f"Key '{key}' not found") self.set(key, value, version=version + delta) self.delete(key, version=version) @@ -364,7 +361,7 @@ async def aincr_version(self, key, delta=1, version=None): value = await self.aget(key, self._missing_key, version=version) if value is self._missing_key: - raise ValueError("Key '%s' not found" % key) + raise ValueError(f"Key '{key}' not found") await self.aset(key, value, version=version + delta) await self.adelete(key, version=version) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/db.py b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/db.py index c6bdb457..2b4fd73c 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/db.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/db.py @@ -67,15 +67,7 @@ def get_many(self, keys, version=None): with connection.cursor() as cursor: cursor.execute( - "SELECT %s, %s, %s FROM %s WHERE %s IN (%s)" - % ( - quote_name("cache_key"), - quote_name("value"), - quote_name("expires"), - table, - quote_name("cache_key"), - ", ".join(["%s"] * len(key_map)), - ), + f'SELECT {quote_name("cache_key")}, {quote_name("value")}, {quote_name("expires")} FROM {table} WHERE {quote_name("cache_key")} IN ({", ".join(["%s"] * len(key_map))})', list(key_map), ) rows = cursor.fetchall() @@ -118,7 +110,7 @@ def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT): table = quote_name(self._table) with connection.cursor() as cursor: - cursor.execute("SELECT COUNT(*) FROM %s" % table) + cursor.execute(f"SELECT COUNT(*) FROM {table}") num = cursor.fetchone()[0] now = timezone.now() now = now.replace(microsecond=0) @@ -222,12 +214,7 @@ def _base_delete_many(self, keys): with connection.cursor() as cursor: cursor.execute( - "DELETE FROM %s WHERE %s IN (%s)" - % ( - table, - quote_name("cache_key"), - ", ".join(["%s"] * len(keys)), - ), + f'DELETE FROM {table} WHERE {quote_name("cache_key")} IN ({", ".join(["%s"] * len(keys))})', keys, ) return bool(cursor.rowcount) @@ -270,8 +257,7 @@ def _cull(self, db, cursor, now, num): cursor.execute( connection.ops.cache_key_culling_sql() % table, [cull_num] ) - last_cache_key = cursor.fetchone() - if last_cache_key: + if last_cache_key := cursor.fetchone(): cursor.execute( "DELETE FROM %s WHERE cache_key < %%s" % table, [last_cache_key[0]], @@ -282,4 +268,4 @@ def clear(self): connection = connections[db] table = connection.ops.quote_name(self._table) with connection.cursor() as cursor: - cursor.execute("DELETE FROM %s" % table) + cursor.execute(f"DELETE FROM {table}") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/filebased.py b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/filebased.py index 6484b44f..25c6142b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/filebased.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/filebased.py @@ -65,11 +65,10 @@ def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): locks.lock(f, locks.LOCK_EX) if self._is_expired(f): return False - else: - previous_value = pickle.loads(zlib.decompress(f.read())) - f.seek(0) - self._write_content(f, timeout, previous_value) - return True + previous_value = pickle.loads(zlib.decompress(f.read())) + f.seek(0) + self._write_content(f, timeout, previous_value) + return True finally: locks.unlock(f) except FileNotFoundError: @@ -160,5 +159,5 @@ def _list_cache_files(self): """ return [ os.path.join(self._dir, fname) - for fname in glob.glob1(self._dir, "*%s" % self.cache_suffix) + for fname in glob.glob1(self._dir, f"*{self.cache_suffix}") ] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/locmem.py b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/locmem.py index cbc8dba5..9db5cd41 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/locmem.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/locmem.py @@ -67,7 +67,7 @@ def incr(self, key, delta=1, version=None): with self._lock: if self._has_expired(key): self._delete(key) - raise ValueError("Key '%s' not found" % key) + raise ValueError(f"Key '{key}' not found") pickled = self._cache[key] value = pickle.loads(pickled) new_value = value + delta @@ -94,7 +94,7 @@ def _cull(self): self._expire_info.clear() else: count = len(self._cache) // self._cull_frequency - for i in range(count): + for _ in range(count): key, _ = self._cache.popitem() del self._expire_info[key] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/memcached.py b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/memcached.py index 25753806..075fd53e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/memcached.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/memcached.py @@ -18,11 +18,7 @@ class BaseMemcachedCache(BaseCache): def __init__(self, server, params, library, value_not_found_exception): super().__init__(params) - if isinstance(server, str): - self._servers = re.split("[;,]", server) - else: - self._servers = server - + self._servers = re.split("[;,]", server) if isinstance(server, str) else server # Exception type raised by the underlying client library for a # nonexistent key. self.LibraryValueNotFoundException = value_not_found_exception @@ -117,7 +113,7 @@ def incr(self, key, delta=1, version=None): except self.LibraryValueNotFoundException: val = None if val is None: - raise ValueError("Key '%s' not found" % key) + raise ValueError(f"Key '{key}' not found") return val def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): @@ -173,9 +169,7 @@ def get(self, key, default=None, version=None): # python-memcached doesn't support default values in get(). # https://github.com/linsomniac/python-memcached/issues/159 # Remove this method if that issue is fixed. - if val is None: - return default - return val + return default if val is None else val def delete(self, key, version=None): # python-memcached's delete() returns True when key doesn't exist. @@ -197,10 +191,10 @@ def __init__(self, server, params): @property def client_servers(self): - output = [] - for server in self._servers: - output.append(server[5:] if server.startswith("unix:") else server) - return output + return [ + server[5:] if server.startswith("unix:") else server + for server in self._servers + ] def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/redis.py b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/redis.py index fac6a7c2..040828c1 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/redis.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/cache/backends/redis.py @@ -18,9 +18,7 @@ class RedisSerializer(PickleSerializer): def dumps(self, obj): # Only skip pickling for integers, a int subclasses as bool should be # pickled. - if type(obj) is int: - return obj - return super().dumps(obj) + return obj if type(obj) is int else super().dumps(obj) def loads(self, data): try: @@ -89,12 +87,11 @@ def add(self, key, value, timeout): client = self.get_client(key, write=True) value = self._serializer.dumps(value) - if timeout == 0: - if ret := bool(client.set(key, value, nx=True)): - client.delete(key) - return ret - else: + if timeout != 0: return bool(client.set(key, value, ex=timeout, nx=True)) + if ret := bool(client.set(key, value, nx=True)): + client.delete(key) + return ret def get(self, key, default): client = self.get_client(key) @@ -134,7 +131,7 @@ def has_key(self, key): def incr(self, key, delta): client = self.get_client(key) if not client.exists(key): - raise ValueError("Key '%s' not found." % key) + raise ValueError(f"Key '{key}' not found.") return client.incr(key, delta) def set_many(self, data, timeout): @@ -161,11 +158,7 @@ def clear(self): class RedisCache(BaseCache): def __init__(self, server, params): super().__init__(params) - if isinstance(server, str): - self._servers = re.split("[;,]", server) - else: - self._servers = server - + self._servers = re.split("[;,]", server) if isinstance(server, str) else server self._class = RedisCacheClient self._options = params.get("OPTIONS", {}) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/async_checks.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/async_checks.py index a0e01867..290385bc 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/async_checks.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/async_checks.py @@ -11,6 +11,4 @@ @register(Tags.async_support, deploy=True) def check_async_unsafe(app_configs, **kwargs): - if os.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE"): - return [E001] - return [] + return [E001] if os.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE") else [] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/caches.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/caches.py index c288a6ff..c66e851d 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/caches.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/caches.py @@ -7,16 +7,14 @@ from . import Error, Tags, Warning, register E001 = Error( - "You must define a '%s' cache in your CACHES setting." % DEFAULT_CACHE_ALIAS, + f"You must define a '{DEFAULT_CACHE_ALIAS}' cache in your CACHES setting.", id="caches.E001", ) @register(Tags.caches) def check_default_cache_is_configured(app_configs, **kwargs): - if DEFAULT_CACHE_ALIAS not in settings.CACHES: - return [E001] - return [] + return [E001] if DEFAULT_CACHE_ALIAS not in settings.CACHES else [] @register(Tags.caches, deploy=True) @@ -39,7 +37,7 @@ def check_cache_location_not_exposed(app_configs, **kwargs): if not isinstance(cache, FileBasedCache): continue cache_path = pathlib.Path(cache._dir).resolve() - if any(path == cache_path for path in paths): + if cache_path in paths: relation = "matches" elif any(path in cache_path.parents for path in paths): relation = "is inside" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/compatibility/django_4_0.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/compatibility/django_4_0.py index 79ee5fa6..0b8a979b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/compatibility/django_4_0.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/compatibility/django_4_0.py @@ -5,16 +5,11 @@ @register(Tags.compatibility) def check_csrf_trusted_origins(app_configs, **kwargs): - errors = [] - for origin in settings.CSRF_TRUSTED_ORIGINS: - if "://" not in origin: - errors.append( - Error( - "As of Django 4.0, the values in the CSRF_TRUSTED_ORIGINS " - "setting must start with a scheme (usually http:// or " - "https://) but found %s. See the release notes for details." - % origin, - id="4_0.E001", - ) - ) - return errors + return [ + Error( + f"As of Django 4.0, the values in the CSRF_TRUSTED_ORIGINS setting must start with a scheme (usually http:// or https://) but found {origin}. See the release notes for details.", + id="4_0.E001", + ) + for origin in settings.CSRF_TRUSTED_ORIGINS + if "://" not in origin + ] diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/messages.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/messages.py index db7aa551..e472fb3b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/messages.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/messages.py @@ -33,9 +33,9 @@ def __str__(self): obj = self.obj._meta.label else: obj = str(self.obj) - id = "(%s) " % self.id if self.id else "" + id = f"({self.id}) " if self.id else "" hint = "\n\tHINT: %s" % self.hint if self.hint else "" - return "%s: %s%s%s" % (obj, id, self.msg, hint) + return f"{obj}: {id}{self.msg}{hint}" def __repr__(self): return "<%s: level=%r, msg=%r, hint=%r, obj=%r, id=%r>" % ( diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/model_checks.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/model_checks.py index 7a5bef9b..c379fd50 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/model_checks.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/model_checks.py @@ -52,10 +52,11 @@ def check_all_models(app_configs=None, **kwargs): model_labels_str = ", ".join(model_labels) errors.append( error_class( - "db_table '%s' is used by multiple models: %s." - % (db_table, model_labels_str), + f"db_table '{db_table}' is used by multiple models: {model_labels_str}.", obj=db_table, - hint=(error_hint % model_labels_str) if error_hint else None, + hint=(error_hint % model_labels_str) + if error_hint + else None, id=error_id, ) ) @@ -64,28 +65,22 @@ def check_all_models(app_configs=None, **kwargs): model_labels = set(model_labels) errors.append( Error( - "index name '%s' is not unique %s %s." - % ( - index_name, - "for model" if len(model_labels) == 1 else "among models:", - ", ".join(sorted(model_labels)), - ), - id="models.E029" if len(model_labels) == 1 else "models.E030", - ), + f"""index name '{index_name}' is not unique {"for model" if len(model_labels) == 1 else "among models:"} {", ".join(sorted(model_labels))}.""", + id="models.E029" + if len(model_labels) == 1 + else "models.E030", + ) ) for constraint_name, model_labels in constraints.items(): if len(model_labels) > 1: model_labels = set(model_labels) errors.append( Error( - "constraint name '%s' is not unique %s %s." - % ( - constraint_name, - "for model" if len(model_labels) == 1 else "among models:", - ", ".join(sorted(model_labels)), - ), - id="models.E031" if len(model_labels) == 1 else "models.E032", - ), + f"""constraint name '{constraint_name}' is not unique {"for model" if len(model_labels) == 1 else "among models:"} {", ".join(sorted(model_labels))}.""", + id="models.E031" + if len(model_labels) == 1 + else "models.E032", + ) ) return errors @@ -137,7 +132,7 @@ def app_model_error(model_key): apps.get_app_config(model_key[0]) model_error = "app '%s' doesn't provide model '%s'" % model_key except LookupError: - model_error = "app '%s' isn't installed" % model_key[0] + model_error = f"app '{model_key[0]}' isn't installed" return model_error # Here are several functions which return CheckMessage instances for the @@ -167,14 +162,11 @@ def signal_connect_error(model_key, func, args, keywords): # The receiver is either a function or an instance of class # defining a `__call__` method. if isinstance(receiver, types.FunctionType): - description = "The function '%s'" % receiver.__name__ + description = f"The function '{receiver.__name__}'" elif isinstance(receiver, types.MethodType): - description = "Bound method '%s.%s'" % ( - receiver.__self__.__class__.__name__, - receiver.__name__, - ) + description = f"Bound method '{receiver.__self__.__class__.__name__}.{receiver.__name__}'" else: - description = "An instance of class '%s'" % receiver.__class__.__name__ + description = f"An instance of class '{receiver.__class__.__name__}'" signal_name = model_signals.get(func.__self__, "unknown") params = { "model": ".".join(model_key), diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/registry.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/registry.py index f4bdea86..dcdee52e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/registry.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/registry.py @@ -63,10 +63,9 @@ def inner(check): if callable(check): return inner(check) - else: - if check: - tags += (check,) - return inner + if check: + tags += (check,) + return inner def run_checks( self, diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/base.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/base.py index 3e3de6e4..836b7423 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/base.py @@ -126,16 +126,14 @@ E023 = Error( "You have set the SECURE_REFERRER_POLICY setting to an invalid value.", - hint="Valid values are: {}.".format(", ".join(sorted(REFERRER_POLICY_VALUES))), + hint=f'Valid values are: {", ".join(sorted(REFERRER_POLICY_VALUES))}.', id="security.E023", ) E024 = Error( "You have set the SECURE_CROSS_ORIGIN_OPENER_POLICY setting to an invalid " "value.", - hint="Valid values are: {}.".format( - ", ".join(sorted(CROSS_ORIGIN_OPENER_POLICY_VALUES)), - ), + hint=f'Valid values are: {", ".join(sorted(CROSS_ORIGIN_OPENER_POLICY_VALUES))}.', id="security.E024", ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/csrf.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/csrf.py index af59589a..6b4fe345 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/csrf.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/security/csrf.py @@ -50,10 +50,7 @@ def check_csrf_failure_view(app_configs, **kwargs): try: view = _get_failure_view() except ImportError: - msg = ( - "The CSRF failure view '%s' could not be imported." - % settings.CSRF_FAILURE_VIEW - ) + msg = f"The CSRF failure view '{settings.CSRF_FAILURE_VIEW}' could not be imported." errors.append(Error(msg, id="security.E102")) else: try: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/urls.py b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/urls.py index 34eff967..93e5059e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/checks/urls.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/checks/urls.py @@ -42,16 +42,13 @@ def check_url_namespaces_unique(app_configs, **kwargs): all_namespaces = _load_all_namespaces(resolver) counter = Counter(all_namespaces) non_unique_namespaces = [n for n, count in counter.items() if count > 1] - errors = [] - for namespace in non_unique_namespaces: - errors.append( - Warning( - "URL namespace '{}' isn't unique. You may not be able to reverse " - "all URLs in this namespace".format(namespace), - id="urls.W005", - ) + return [ + Warning( + f"URL namespace '{namespace}' isn't unique. You may not be able to reverse all URLs in this namespace", + id="urls.W005", ) - return errors + for namespace in non_unique_namespaces + ] def _load_all_namespaces(resolver, parents=()): @@ -81,10 +78,7 @@ def get_warning_for_invalid_pattern(pattern): urlpattern having regex or name attributes. """ if isinstance(pattern, str): - hint = ( - "Try removing the string '{}'. The list of urlpatterns should not " - "have a prefix string as the first element.".format(pattern) - ) + hint = f"Try removing the string '{pattern}'. The list of urlpatterns should not have a prefix string as the first element." elif isinstance(pattern, tuple): hint = "Try using path() instead of a tuple." else: @@ -111,7 +105,4 @@ def check_url_settings(app_configs, **kwargs): def E006(name): - return Error( - "The {} setting must end with a slash.".format(name), - id="urls.E006", - ) + return Error(f"The {name} setting must end with a slash.", id="urls.E006") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/exceptions.py b/unicoding_venv/lib/python3.9/site-packages/django/core/exceptions.py index 7be4e16b..0c017d2b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/exceptions.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/exceptions.py @@ -201,17 +201,17 @@ def __iter__(self): yield str(message) def __str__(self): - if hasattr(self, "error_dict"): - return repr(dict(self)) - return repr(list(self)) + return repr(dict(self)) if hasattr(self, "error_dict") else repr(list(self)) def __repr__(self): - return "ValidationError(%s)" % self + return f"ValidationError({self})" def __eq__(self, other): - if not isinstance(other, ValidationError): - return NotImplemented - return hash(self) == hash(other) + return ( + hash(self) == hash(other) + if isinstance(other, ValidationError) + else NotImplemented + ) def __hash__(self): if hasattr(self, "message"): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/files/base.py b/unicoding_venv/lib/python3.9/site-packages/django/core/files/base.py index 3ca43ec2..ca475ea9 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/files/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/files/base.py @@ -20,7 +20,7 @@ def __str__(self): return self.name or "" def __repr__(self): - return "<%s: %s>" % (self.__class__.__name__, self or "None") + return f'<{self.__class__.__name__}: {self or "None"}>' def __bool__(self): return bool(self.name) @@ -57,10 +57,10 @@ def chunks(self, chunk_size=None): pass while True: - data = self.read(chunk_size) - if not data: + if data := self.read(chunk_size): + yield data + else: break - yield data def multiple_chunks(self, chunk_size=None): """ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/files/images.py b/unicoding_venv/lib/python3.9/site-packages/django/core/files/images.py index 6a603f24..03685378 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/files/images.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/files/images.py @@ -64,9 +64,7 @@ def get_image_dimensions(file_or_path, close=False): except zlib.error as e: # ignore zlib complaining on truncated stream, just feed more # data to parser (ticket #19457). - if e.args[0].startswith("Error -5"): - pass - else: + if not e.args[0].startswith("Error -5"): raise except struct.error: # Ignore PIL failing on a too short buffer when reads return diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/files/move.py b/unicoding_venv/lib/python3.9/site-packages/django/core/files/move.py index 2d71e118..37f79e93 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/files/move.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/files/move.py @@ -47,8 +47,7 @@ def file_move_safe( try: if not allow_overwrite and os.access(new_file_name, os.F_OK): raise FileExistsError( - "Destination file %s exists and allow_overwrite is False." - % new_file_name + f"Destination file {new_file_name} exists and allow_overwrite is False." ) os.rename(old_file_name, new_file_name) @@ -67,7 +66,7 @@ def file_move_safe( os.O_WRONLY | os.O_CREAT | getattr(os, "O_BINARY", 0) - | (os.O_EXCL if not allow_overwrite else 0) + | (0 if allow_overwrite else os.O_EXCL) ), ) try: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/files/storage.py b/unicoding_venv/lib/python3.9/site-packages/django/core/files/storage.py index 714f9c12..2dcd3a96 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/files/storage.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/files/storage.py @@ -74,7 +74,7 @@ def get_alternative_name(self, file_root, file_ext): character alphanumeric string (before the file extension, if one exists) to the filename. """ - return "%s_%s%s" % (file_root, get_random_string(7), file_ext) + return f"{file_root}_{get_random_string(7)}{file_ext}" def get_available_name(self, name, max_length=None): """ @@ -85,7 +85,7 @@ def get_available_name(self, name, max_length=None): dir_name, file_name = os.path.split(name) if ".." in pathlib.PurePath(dir_name).parts: raise SuspiciousFileOperation( - "Detected path traversal attempt in '%s'" % dir_name + f"Detected path traversal attempt in '{dir_name}'" ) validate_file_name(file_name) file_root, file_ext = os.path.splitext(file_name) @@ -127,7 +127,7 @@ def generate_filename(self, filename): dirname, filename = os.path.split(filename) if ".." in pathlib.PurePath(dirname).parts: raise SuspiciousFileOperation( - "Detected path traversal attempt in '%s'" % dirname + f"Detected path traversal attempt in '{dirname}'" ) return os.path.normpath(os.path.join(dirname, self.get_valid_name(filename))) @@ -295,7 +295,7 @@ def _save(self, name, content): else: os.makedirs(directory, exist_ok=True) except FileExistsError: - raise FileExistsError("%s exists and is not a directory." % directory) + raise FileExistsError(f"{directory} exists and is not a directory.") # There's a potential race condition between get_available_name and # saving the file; it's possible that two threads might return the diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/files/uploadedfile.py b/unicoding_venv/lib/python3.9/site-packages/django/core/files/uploadedfile.py index efbfcac4..9ba68cb0 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/files/uploadedfile.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/files/uploadedfile.py @@ -43,7 +43,7 @@ def __init__( self.content_type_extra = content_type_extra def __repr__(self): - return "<%s: %s (%s)>" % (self.__class__.__name__, self.name, self.content_type) + return f"<{self.__class__.__name__}: {self.name} ({self.content_type})>" def _get_name(self): return self._name @@ -75,7 +75,7 @@ class TemporaryUploadedFile(UploadedFile): def __init__(self, name, content_type, size, charset, content_type_extra=None): _, ext = os.path.splitext(name) file = tempfile.NamedTemporaryFile( - suffix=".upload" + ext, dir=settings.FILE_UPLOAD_TEMP_DIR + suffix=f".upload{ext}", dir=settings.FILE_UPLOAD_TEMP_DIR ) super().__init__(file, name, content_type, size, charset, content_type_extra) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/files/utils.py b/unicoding_venv/lib/python3.9/site-packages/django/core/files/utils.py index 85342b2f..32d04264 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/files/utils.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/files/utils.py @@ -7,7 +7,7 @@ def validate_file_name(name, allow_relative_path=False): # Remove potentially dangerous names if os.path.basename(name) in {"", ".", ".."}: - raise SuspiciousFileOperation("Could not derive file name from '%s'" % name) + raise SuspiciousFileOperation(f"Could not derive file name from '{name}'") if allow_relative_path: # Use PurePosixPath() because this branch is checked only in @@ -15,11 +15,9 @@ def validate_file_name(name, allow_relative_path=False): # Unix style (with forward slashes). path = pathlib.PurePosixPath(name) if path.is_absolute() or ".." in path.parts: - raise SuspiciousFileOperation( - "Detected path traversal attempt in '%s'" % name - ) + raise SuspiciousFileOperation(f"Detected path traversal attempt in '{name}'") elif name != os.path.basename(name): - raise SuspiciousFileOperation("File name '%s' includes path elements" % name) + raise SuspiciousFileOperation(f"File name '{name}' includes path elements") return name @@ -56,9 +54,7 @@ def closed(self): def readable(self): if self.closed: return False - if hasattr(self.file, "readable"): - return self.file.readable() - return True + return self.file.readable() if hasattr(self.file, "readable") else True def writable(self): if self.closed: @@ -70,9 +66,7 @@ def writable(self): def seekable(self): if self.closed: return False - if hasattr(self.file, "seekable"): - return self.file.seekable() - return True + return self.file.seekable() if hasattr(self.file, "seekable") else True def __iter__(self): return iter(self.file) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/asgi.py b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/asgi.py index 7b17c581..815348ec 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/asgi.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/asgi.py @@ -48,10 +48,7 @@ def __init__(self, scope, body_file): # The Django path is different from ASGI scope path args, it should # combine with script name. if self.script_name: - self.path = "%s/%s" % ( - self.script_name.rstrip("/"), - self.path_info.replace("/", "", 1), - ) + self.path = f'{self.script_name.rstrip("/")}/{self.path_info.replace("/", "", 1)}' else: self.path = scope["path"] # HTTP basics. @@ -87,12 +84,12 @@ def __init__(self, scope, body_file): elif name == "content-type": corrected_name = "CONTENT_TYPE" else: - corrected_name = "HTTP_%s" % name.upper().replace("-", "_") + corrected_name = f'HTTP_{name.upper().replace("-", "_")}' # HTTP/2 say only ASCII chars are allowed in headers, but decode # latin1 just in case. value = value.decode("latin1") if corrected_name in self.META: - value = self.META[corrected_name] + "," + value + value = f"{self.META[corrected_name]},{value}" self.META[corrected_name] = value # Pull out request encoding, if provided. self._set_content_type_params(self.META) @@ -148,7 +145,7 @@ async def __call__(self, scope, receive, send): # FIXME: Allow to override this. if scope["type"] != "http": raise ValueError( - "Django can only handle ASGI/HTTP connections, not %s." % scope["type"] + f'Django can only handle ASGI/HTTP connections, not {scope["type"]}.' ) async with ThreadSensitiveContext(): @@ -243,10 +240,10 @@ async def send_response(self, response, send): if isinstance(value, str): value = value.encode("latin1") response_headers.append((bytes(header), bytes(value))) - for c in response.cookies.values(): - response_headers.append( - (b"Set-Cookie", c.output(header="").encode("ascii").strip()) - ) + response_headers.extend( + (b"Set-Cookie", c.output(header="").encode("ascii").strip()) + for c in response.cookies.values() + ) # Initial response message. await send( { @@ -306,6 +303,4 @@ def get_script_prefix(self, scope): """ Return the script prefix to use from either the scope or a setting. """ - if settings.FORCE_SCRIPT_NAME: - return settings.FORCE_SCRIPT_NAME - return scope.get("root_path", "") or "" + return settings.FORCE_SCRIPT_NAME or scope.get("root_path", "") or "" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/base.py b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/base.py index 0f341a53..d14bf284 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/base.py @@ -29,10 +29,10 @@ def load_middleware(self, is_async=False): Must be called after the environment is fixed (see __call__ in subclasses). """ - self._view_middleware = [] self._template_response_middleware = [] self._exception_middleware = [] + self._view_middleware = [] get_response = self._get_response_async if is_async else self._get_response handler = convert_exception_to_response(get_response) handler_is_async = is_async @@ -42,8 +42,7 @@ def load_middleware(self, is_async=False): middleware_can_async = getattr(middleware, "async_capable", False) if not middleware_can_sync and not middleware_can_async: raise RuntimeError( - "Middleware %s must have at least one of " - "sync_capable/async_capable set to True." % middleware_path + f"Middleware {middleware_path} must have at least one of sync_capable/async_capable set to True." ) elif not handler_is_async and middleware_can_sync: middleware_is_async = False @@ -56,7 +55,7 @@ def load_middleware(self, is_async=False): handler, handler_is_async, debug=settings.DEBUG, - name="middleware %s" % middleware_path, + name=f"middleware {middleware_path}", ) mw_instance = middleware(adapted_handler) except MiddlewareNotUsed as exc: @@ -71,7 +70,7 @@ def load_middleware(self, is_async=False): if mw_instance is None: raise ImproperlyConfigured( - "Middleware factory %s returned None." % middleware_path + f"Middleware factory {middleware_path} returned None." ) if hasattr(mw_instance, "process_view"): @@ -121,7 +120,7 @@ def adapt_method_mode( if method_is_async is None: method_is_async = asyncio.iscoroutinefunction(method) if debug and not name: - name = name or "method %s()" % method.__qualname__ + name = name or f"method {method.__qualname__}()" if is_async: if not method_is_async: if debug: @@ -213,8 +212,7 @@ def _get_response(self, request): self.check_response( response, middleware_method, - name="%s.process_template_response" - % (middleware_method.__self__.__class__.__name__,), + name=f"{middleware_method.__self__.__class__.__name__}.process_template_response", ) try: response = response.render() @@ -274,8 +272,7 @@ async def _get_response_async(self, request): self.check_response( response, middleware_method, - name="%s.process_template_response" - % (middleware_method.__self__.__class__.__name__,), + name=f"{middleware_method.__self__.__class__.__name__}.process_template_response", ) try: if asyncio.iscoroutinefunction(response.render): @@ -322,12 +319,9 @@ def check_response(self, response, callback, name=None): return if not name: if isinstance(callback, types.FunctionType): # FBV - name = "The view %s.%s" % (callback.__module__, callback.__name__) + name = f"The view {callback.__module__}.{callback.__name__}" else: # CBV - name = "The view %s.%s.__call__" % ( - callback.__module__, - callback.__class__.__name__, - ) + name = f"The view {callback.__module__}.{callback.__class__.__name__}.__call__" if response is None: raise ValueError( "%s didn't return an HttpResponse object. It returned None " @@ -362,8 +356,7 @@ def process_exception_by_middleware(self, exception, request): return a response for this exception, return None. """ for middleware_method in self._exception_middleware: - response = middleware_method(request, exception) - if response: + if response := middleware_method(request, exception): return response return None diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/exception.py b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/exception.py index 622c5313..b9879254 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/exception.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/exception.py @@ -119,7 +119,7 @@ def response_for_exception(request, exc): # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger( - "django.security.%s" % exc.__class__.__name__ + f"django.security.{exc.__class__.__name__}" ) security_logger.error( str(exc), diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py index 621130b6..24b3e49b 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py @@ -53,10 +53,7 @@ def readline(self, size=None): break self.buffer += chunk sio = BytesIO(self.buffer) - if size: - line = sio.readline(size) - else: - line = sio.readline() + line = sio.readline(size) if size else sio.readline() self.buffer = sio.read() return line @@ -72,7 +69,7 @@ def __init__(self, environ): # be careful to only replace the first slash in the path because of # http://test/something and http://test//something being different as # stated in https://www.ietf.org/rfc/rfc2396.txt - self.path = "%s/%s" % (script_name.rstrip("/"), path_info.replace("/", "", 1)) + self.path = f'{script_name.rstrip("/")}/{path_info.replace("/", "", 1)}' self.META = environ self.META["PATH_INFO"] = path_info self.META["SCRIPT_NAME"] = script_name @@ -170,16 +167,9 @@ def get_script_name(environ): if settings.FORCE_SCRIPT_NAME is not None: return settings.FORCE_SCRIPT_NAME - # If Apache's mod_rewrite had a whack at the URL, Apache set either - # SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any - # rewrites. Unfortunately not every web server (lighttpd!) passes this - # information through all the time, so FORCE_SCRIPT_NAME, above, is still - # needed. - script_url = get_bytes_from_wsgi(environ, "SCRIPT_URL", "") or get_bytes_from_wsgi( - environ, "REDIRECT_URL", "" - ) - - if script_url: + if script_url := get_bytes_from_wsgi( + environ, "SCRIPT_URL", "" + ) or get_bytes_from_wsgi(environ, "REDIRECT_URL", ""): if b"//" in script_url: # mod_wsgi squashes multiple successive slashes in PATH_INFO, # do the same with script_url before manipulating paths (#17133). diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/__init__.py index dc63e870..ddea5645 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/__init__.py @@ -123,7 +123,7 @@ def mail_admins( if not all(isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.ADMINS): raise ValueError("The ADMINS setting must be a list of 2-tuples.") mail = EmailMultiAlternatives( - "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), + f"{settings.EMAIL_SUBJECT_PREFIX}{subject}", message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], @@ -143,7 +143,7 @@ def mail_managers( if not all(isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.MANAGERS): raise ValueError("The MANAGERS setting must be a list of 2-tuples.") mail = EmailMultiAlternatives( - "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), + f"{settings.EMAIL_SUBJECT_PREFIX}{subject}", message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/filebased.py b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/filebased.py index 3b2b0371..e4183df7 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/filebased.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/filebased.py @@ -20,19 +20,15 @@ def __init__(self, *args, file_path=None, **kwargs): os.makedirs(self.file_path, exist_ok=True) except FileExistsError: raise ImproperlyConfigured( - "Path for saving email messages exists, but is not a directory: %s" - % self.file_path + f"Path for saving email messages exists, but is not a directory: {self.file_path}" ) except OSError as err: raise ImproperlyConfigured( - "Could not create directory for saving email messages: %s (%s)" - % (self.file_path, err) + f"Could not create directory for saving email messages: {self.file_path} ({err})" ) # Make sure that self.file_path is writable. if not os.access(self.file_path, os.W_OK): - raise ImproperlyConfigured( - "Could not write to directory: %s" % self.file_path - ) + raise ImproperlyConfigured(f"Could not write to directory: {self.file_path}") # Finally, call super(). # Since we're using the console-based backend as a base, # force the stream to be None, so we don't default to stdout @@ -48,7 +44,7 @@ def _get_filename(self): """Return a unique file name.""" if self._fname is None: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") - fname = "%s-%s.log" % (timestamp, abs(id(self))) + fname = f"{timestamp}-{abs(id(self))}.log" self._fname = os.path.join(self.file_path, fname) return self._fname diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py index 5df7c20a..80a1fc5f 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py @@ -70,12 +70,10 @@ def open(self): if self.timeout is not None: connection_params["timeout"] = self.timeout if self.use_ssl: - connection_params.update( - { - "keyfile": self.ssl_keyfile, - "certfile": self.ssl_certfile, - } - ) + connection_params |= { + "keyfile": self.ssl_keyfile, + "certfile": self.ssl_certfile, + } try: self.connection = self.connection_class( self.host, self.port, **connection_params @@ -99,17 +97,16 @@ def close(self): if self.connection is None: return try: - try: - self.connection.quit() - except (ssl.SSLError, smtplib.SMTPServerDisconnected): - # This happens when calling quit() on a TLS connection - # sometimes, or when the connection was already disconnected - # by the server. - self.connection.close() - except smtplib.SMTPException: - if self.fail_silently: - return - raise + self.connection.quit() + except (ssl.SSLError, smtplib.SMTPServerDisconnected): + # This happens when calling quit() on a TLS connection + # sometimes, or when the connection was already disconnected + # by the server. + self.connection.close() + except smtplib.SMTPException: + if self.fail_silently: + return + raise finally: self.connection = None diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/message.py b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/message.py index cd5b71ad..f8a902ab 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/mail/message.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/mail/message.py @@ -85,12 +85,12 @@ def sanitize_address(addr, encoding): try: token, rest = parser.get_mailbox(addr) except (HeaderParseError, ValueError, IndexError): - raise ValueError('Invalid address "%s"' % addr) + raise ValueError(f'Invalid address "{addr}"') else: if rest: # The entire email address must be parsed. raise ValueError( - 'Invalid address; only %s could be parsed from "%s"' % (token, addr) + f'Invalid address; only {token} could be parsed from "{addr}"' ) nm = token.display_name or "" localpart = token.local_part @@ -291,11 +291,11 @@ def recipients(self): def send(self, fail_silently=False): """Send the email message.""" - if not self.recipients(): - # Don't bother creating the network connection if there's nobody to - # send to. - return 0 - return self.get_connection(fail_silently).send_messages([self]) + return ( + self.get_connection(fail_silently).send_messages([self]) + if self.recipients() + else 0 + ) def attach(self, filename=None, content=None, mimetype=None): """ @@ -326,14 +326,13 @@ def attach(self, filename=None, content=None, mimetype=None): ) basetype, subtype = mimetype.split("/", 1) - if basetype == "text": - if isinstance(content, bytes): - try: - content = content.decode() - except UnicodeDecodeError: - # If mimetype suggests the file is text but it's - # actually binary, read() raises a UnicodeDecodeError. - mimetype = DEFAULT_ATTACHMENT_MIME_TYPE + if basetype == "text" and isinstance(content, bytes): + try: + content = content.decode() + except UnicodeDecodeError: + # If mimetype suggests the file is text but it's + # actually binary, read() raises a UnicodeDecodeError. + mimetype = DEFAULT_ATTACHMENT_MIME_TYPE self.attachments.append((filename, content, mimetype)) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/__init__.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/__init__.py index 64af1b80..49270745 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/__init__.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/__init__.py @@ -45,7 +45,7 @@ def load_command_class(app_name, name): class instance. Allow all errors raised by the import process (ImportError, AttributeError) to propagate. """ - module = import_module("%s.management.commands.%s" % (app_name, name)) + module = import_module(f"{app_name}.management.commands.{name}") return module.Command() @@ -79,7 +79,7 @@ def get_commands(): for app_config in reversed(list(apps.get_app_configs())): path = os.path.join(app_config.path, "management") - commands.update({name: app_config.name for name in find_commands(path)}) + commands |= {name: app_config.name for name in find_commands(path)} return commands @@ -217,24 +217,18 @@ def main_help_text(self, commands_only=False): else: usage = [ "", - "Type '%s help ' for help on a specific subcommand." - % self.prog_name, + f"Type '{self.prog_name} help ' for help on a specific subcommand.", "", "Available subcommands:", ] commands_dict = defaultdict(lambda: []) for name, app in get_commands().items(): - if app == "django.core": - app = "django" - else: - app = app.rpartition(".")[-1] + app = "django" if app == "django.core" else app.rpartition(".")[-1] commands_dict[app].append(name) style = color_style() for app in sorted(commands_dict): - usage.append("") - usage.append(style.NOTICE("[%s]" % app)) - for name in sorted(commands_dict[app]): - usage.append(" %s" % name) + usage.extend(("", style.NOTICE(f"[{app}]"))) + usage.extend(f" {name}" for name in sorted(commands_dict[app])) # Output an extra note if settings are not properly configured if self.settings_exception is not None: usage.append( @@ -269,15 +263,14 @@ def fetch_command(self, subcommand): possible_matches = get_close_matches(subcommand, commands) sys.stderr.write("Unknown command: %r" % subcommand) if possible_matches: - sys.stderr.write(". Did you mean %s?" % possible_matches[0]) + sys.stderr.write(f". Did you mean {possible_matches[0]}?") sys.stderr.write("\nType '%s help' for usage.\n" % self.prog_name) sys.exit(1) - if isinstance(app_name, BaseCommand): - # If the command is already loaded, use it directly. - klass = app_name - else: - klass = load_command_class(app_name, subcommand) - return klass + return ( + app_name + if isinstance(app_name, BaseCommand) + else load_command_class(app_name, subcommand) + ) def autocomplete(self): """ diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/base.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/base.py index 834d1b28..693b483e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/base.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/base.py @@ -71,7 +71,7 @@ def error(self, message): if self.called_from_command_line: super().error(message) else: - raise CommandError("Error: %s" % message) + raise CommandError(f"Error: {message}") def handle_default_options(options): @@ -299,11 +299,13 @@ def create_parser(self, prog_name, subcommand, **kwargs): parse the arguments to this command. """ parser = CommandParser( - prog="%s %s" % (os.path.basename(prog_name), subcommand), + prog=f"{os.path.basename(prog_name)} {subcommand}", description=self.help or None, formatter_class=DjangoHelpFormatter, missing_args_message=getattr(self, "missing_args_message", None), - called_from_command_line=getattr(self, "_called_from_command_line", None), + called_from_command_line=getattr( + self, "_called_from_command_line", None + ), **kwargs, ) self.add_base_argument( @@ -420,7 +422,7 @@ def run_from_argv(self, argv): if isinstance(e, SystemCheckError): self.stderr.write(str(e), lambda x: x) else: - self.stderr.write("%s: %s" % (e.__class__.__name__, e)) + self.stderr.write(f"{e.__class__.__name__}: {e}") sys.exit(e.returncode) finally: try: @@ -549,12 +551,12 @@ def check( if visible_issue_count == 0 else "1 issue" if visible_issue_count == 1 - else "%s issues" % visible_issue_count, + else f"{visible_issue_count} issues", len(all_issues) - visible_issue_count, ) if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues): - msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer + msg = self.style.ERROR(f"SystemCheckError: {header}") + body + footer raise SystemCheckError(msg) else: msg = header + body + footer @@ -578,8 +580,7 @@ def check_migrations(self): # No databases are configured (or the dummy one) return - plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) - if plan: + if plan := executor.migration_plan(executor.loader.graph.leaf_nodes()): apps_waiting_migration = sorted( {migration.app_label for migration, backwards in plan} ) @@ -634,12 +635,11 @@ def handle(self, *app_labels, **options): app_configs = [apps.get_app_config(app_label) for app_label in app_labels] except (LookupError, ImportError) as e: raise CommandError( - "%s. Are you sure your INSTALLED_APPS setting is correct?" % e + f"{e}. Are you sure your INSTALLED_APPS setting is correct?" ) output = [] for app_config in app_configs: - app_output = self.handle_app_config(app_config, **options) - if app_output: + if app_output := self.handle_app_config(app_config, **options): output.append(app_output) return "\n".join(output) @@ -675,8 +675,7 @@ def add_arguments(self, parser): def handle(self, *labels, **options): output = [] for label in labels: - label_output = self.handle_label(label, **options) - if label_output: + if label_output := self.handle_label(label, **options): output.append(label_output) return "\n".join(output) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/check.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/check.py index 7624b853..6bcb22fc 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/check.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/check.py @@ -69,9 +69,7 @@ def handle(self, *app_labels, **options): # no invalid tags pass else: - raise CommandError( - 'There is no system check with the "%s" tag.' % invalid_tag - ) + raise CommandError(f'There is no system check with the "{invalid_tag}" tag.') self.check( app_configs=app_configs, diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/compilemessages.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/compilemessages.py index 9ed3ef7c..687dbf99 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/compilemessages.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/compilemessages.py @@ -112,7 +112,7 @@ def handle(self, **options): # Build locale list all_locales = [] for basedir in basedirs: - locale_dirs = filter(os.path.isdir, glob.glob("%s/*" % basedir)) + locale_dirs = filter(os.path.isdir, glob.glob(f"{basedir}/*")) all_locales.extend(map(os.path.basename, locale_dirs)) # Account for excluded locales @@ -151,15 +151,12 @@ def compile_messages(self, locations): try: if mo_path.stat().st_mtime >= po_path.stat().st_mtime: if self.verbosity > 0: - self.stdout.write( - "File “%s” is already compiled and up to date." - % po_path - ) + self.stdout.write(f"File “{po_path}” is already compiled and up to date.") continue except FileNotFoundError: pass if self.verbosity > 0: - self.stdout.write("processing file %s in %s" % (f, dirpath)) + self.stdout.write(f"processing file {f} in {dirpath}") if has_bom(po_path): self.stderr.write( @@ -187,9 +184,7 @@ def compile_messages(self, locations): if status: if self.verbosity > 0: if errors: - self.stderr.write( - "Execution of %s failed: %s" % (self.program, errors) - ) + self.stderr.write(f"Execution of {self.program} failed: {errors}") else: - self.stderr.write("Execution of %s failed" % self.program) + self.stderr.write(f"Execution of {self.program} failed") self.has_errors = True diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/createcachetable.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/createcachetable.py index 65ed1686..7b5c54fe 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/createcachetable.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/createcachetable.py @@ -61,7 +61,7 @@ def create_table(self, database, tablename, dry_run): if tablename in connection.introspection.table_names(): if self.verbosity > 0: - self.stdout.write("Cache table '%s' already exists." % tablename) + self.stdout.write(f"Cache table '{tablename}' already exists.") return fields = ( @@ -79,7 +79,7 @@ def create_table(self, database, tablename, dry_run): field_output = [ qn(f.name), f.db_type(connection=connection), - "%sNULL" % ("NOT " if not f.null else ""), + f'{"" if f.null else "NOT "}NULL', ] if f.primary_key: field_output.append("PRIMARY KEY") @@ -88,20 +88,14 @@ def create_table(self, database, tablename, dry_run): if f.db_index: unique = "UNIQUE " if f.unique else "" index_output.append( - "CREATE %sINDEX %s ON %s (%s);" - % ( - unique, - qn("%s_%s" % (tablename, f.name)), - qn(tablename), - qn(f.name), - ) + f'CREATE {unique}INDEX {qn(f"{tablename}_{f.name}")} ON {qn(tablename)} ({qn(f.name)});' ) table_output.append(" ".join(field_output)) - full_statement = ["CREATE TABLE %s (" % qn(tablename)] - for i, line in enumerate(table_output): - full_statement.append( - " %s%s" % (line, "," if i < len(table_output) - 1 else "") - ) + full_statement = [f"CREATE TABLE {qn(tablename)} ("] + full_statement.extend( + f' {line}{"," if i < len(table_output) - 1 else ""}' + for i, line in enumerate(table_output) + ) full_statement.append(");") full_statement = "\n".join(full_statement) @@ -127,4 +121,4 @@ def create_table(self, database, tablename, dry_run): curs.execute(statement) if self.verbosity > 1: - self.stdout.write("Cache table '%s' created." % tablename) + self.stdout.write(f"Cache table '{tablename}' created.") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dbshell.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dbshell.py index 30d2765a..2c0ffafb 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dbshell.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dbshell.py @@ -39,10 +39,6 @@ def handle(self, **options): ) except subprocess.CalledProcessError as e: raise CommandError( - '"%s" returned non-zero exit status %s.' - % ( - " ".join(e.cmd), - e.returncode, - ), + f'"{" ".join(e.cmd)}" returned non-zero exit status {e.returncode}.', returncode=e.returncode, ) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/diffsettings.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/diffsettings.py index 047e4764..064f67d2 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/diffsettings.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/diffsettings.py @@ -65,27 +65,25 @@ def output_hash(self, user_settings, default_settings, **options): output = [] for key in sorted(user_settings): if key not in default_settings: - output.append("%s = %s ###" % (key, user_settings[key])) + output.append(f"{key} = {user_settings[key]} ###") elif user_settings[key] != default_settings[key]: - output.append("%s = %s" % (key, user_settings[key])) + output.append(f"{key} = {user_settings[key]}") elif options["all"]: - output.append("### %s = %s" % (key, user_settings[key])) + output.append(f"### {key} = {user_settings[key]}") return output def output_unified(self, user_settings, default_settings, **options): output = [] for key in sorted(user_settings): if key not in default_settings: - output.append( - self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])) - ) + output.append(self.style.SUCCESS(f"+ {key} = {user_settings[key]}")) elif user_settings[key] != default_settings[key]: - output.append( - self.style.ERROR("- %s = %s" % (key, default_settings[key])) - ) - output.append( - self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])) + output.extend( + ( + self.style.ERROR(f"- {key} = {default_settings[key]}"), + self.style.SUCCESS(f"+ {key} = {user_settings[key]}"), + ) ) elif options["all"]: - output.append(" %s = %s" % (key, user_settings[key])) + output.append(f" {key} = {user_settings[key]}") return output diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dumpdata.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dumpdata.py index 038b8269..55c3c774 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dumpdata.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/dumpdata.py @@ -112,11 +112,7 @@ def handle(self, *app_labels, **options): use_base_manager = options["use_base_manager"] pks = options["primary_keys"] - if pks: - primary_keys = [pk.strip() for pk in pks.split(",")] - else: - primary_keys = [] - + primary_keys = [pk.strip() for pk in pks.split(",")] if pks else [] excluded_models, excluded_apps = parse_apps_and_model_labels(excludes) if not app_labels: @@ -144,9 +140,7 @@ def handle(self, *app_labels, **options): try: model = app_config.get_model(model_label) except LookupError: - raise CommandError( - "Unknown model: %s.%s" % (app_label, model_label) - ) + raise CommandError(f"Unknown model: {app_label}.{model_label}") app_list_value = app_list.setdefault(app_config, []) @@ -178,7 +172,7 @@ def handle(self, *app_labels, **options): except serializers.SerializerDoesNotExist: pass - raise CommandError("Unknown serialization format: %s" % format) + raise CommandError(f"Unknown serialization format: {format}") def get_objects(count_only=False): """ @@ -203,16 +197,11 @@ def get_objects(count_only=False): continue if model._meta.proxy and model._meta.proxy_for_model not in models: warnings.warn( - "%s is a proxy model and won't be serialized." - % model._meta.label, + f"{model._meta.label} is a proxy model and won't be serialized.", category=ProxyModelWarning, ) if not model._meta.proxy and router.allow_migrate_model(using, model): - if use_base_manager: - objects = model._base_manager - else: - objects = model._default_manager - + objects = model._base_manager if use_base_manager else model._default_manager queryset = objects.using(using).order_by(model._meta.pk.name) if primary_keys: queryset = queryset.filter(pk__in=primary_keys) @@ -278,4 +267,4 @@ def get_objects(count_only=False): except Exception as e: if show_traceback: raise - raise CommandError("Unable to serialize database: %s" % e) + raise CommandError(f"Unable to serialize database: {e}") diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/inspectdb.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/inspectdb.py index 8f1a3100..8a8e5307 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/inspectdb.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/inspectdb.py @@ -76,7 +76,7 @@ def table2model(table_name): "# Feel free to rename the models, but don't rename db_table values or " "field names." ) - yield "from %s import models" % self.db_module + yield f"from {self.db_module} import models" known_models = [] table_info = connection.introspection.get_table_list(cursor) @@ -90,9 +90,12 @@ def table2model(table_name): for table_name in options["table"] or sorted( info.name for info in table_info if info.type in types ): - if table_name_filter is not None and callable(table_name_filter): - if not table_name_filter(table_name): - continue + if ( + table_name_filter is not None + and callable(table_name_filter) + and not table_name_filter(table_name) + ): + continue try: try: relations = connection.introspection.get_relations( @@ -120,13 +123,13 @@ def table2model(table_name): cursor, table_name ) except Exception as e: - yield "# Unable to inspect table '%s'" % table_name - yield "# The error was: %s" % e + yield f"# Unable to inspect table '{table_name}'" + yield f"# The error was: {e}" continue yield "" yield "" - yield "class %s(models.Model):" % table2model(table_name) + yield f"class {table2model(table_name)}(models.Model):" known_models.append(table2model(table_name)) used_column_names = [] # Holds column names used in the table so far column_to_field_name = {} # Maps column names to names of model fields @@ -166,9 +169,9 @@ def table2model(table_name): else table2model(relations[column_name][1]) ) if rel_to in known_models: - field_type = "%s(%s" % (rel_type, rel_to) + field_type = f"{rel_type}({rel_to}" else: - field_type = "%s('%s'" % (rel_type, rel_to) + field_type = f"{rel_type}('{rel_to}'" else: # Calling `get_field_type` to get the field type string and any # additional parameters and notes. @@ -198,12 +201,7 @@ def table2model(table_name): extra_params["blank"] = True extra_params["null"] = True - field_desc = "%s = %s%s" % ( - att_name, - # Custom fields will have a dotted path - "" if "." in field_type else "models.", - field_type, - ) + field_desc = f'{att_name} = {"" if "." in field_type else "models."}{field_type}' if field_type.startswith(("ForeignKey(", "OneToOneField(")): field_desc += ", models.DO_NOTHING" @@ -216,7 +214,7 @@ def table2model(table_name): field_desc += ")" if comment_notes: field_desc += " # " + " ".join(comment_notes) - yield " %s" % field_desc + yield f" {field_desc}" is_view = any( info.name == table_name and info.type == "v" for info in table_info ) @@ -258,11 +256,11 @@ def normalize_col_name(self, col_name, used_column_names, is_relation): ) if new_name.startswith("_"): - new_name = "field%s" % new_name + new_name = f"field{new_name}" field_notes.append("Field renamed because it started with '_'.") if new_name.endswith("_"): - new_name = "%sfield" % new_name + new_name = f"{new_name}field" field_notes.append("Field renamed because it ended with '_'.") if keyword.iskeyword(new_name): @@ -270,7 +268,7 @@ def normalize_col_name(self, col_name, used_column_names, is_relation): field_notes.append("Field renamed because it was a Python reserved word.") if new_name[0].isdigit(): - new_name = "number_%s" % new_name + new_name = f"number_{new_name}" field_notes.append( "Field renamed because it wasn't a valid Python identifier." ) @@ -358,10 +356,10 @@ def get_meta( meta.append(" # A unique constraint could not be introspected.") meta += [ " class Meta:", - " managed = False%s" % managed_comment, + f" managed = False{managed_comment}", " db_table = %r" % table_name, ] if unique_together: tup = "(" + ", ".join(unique_together) + ",)" - meta += [" unique_together = %s" % tup] + meta += [f" unique_together = {tup}"] return meta diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/loaddata.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/loaddata.py index ac97f131..8d057343 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/loaddata.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/loaddata.py @@ -128,8 +128,7 @@ def compression_formats(self): def reset_sequences(self, connection, models): """Reset database sequences for the given connection and models.""" - sequence_sql = connection.ops.sequence_reset_sql(no_style(), models) - if sequence_sql: + if sequence_sql := connection.ops.sequence_reset_sql(no_style(), models): if self.verbosity >= 2: self.stdout.write("Resetting sequences") with connection.cursor() as cursor: @@ -170,7 +169,7 @@ def loaddata(self, fixture_labels): try: connection.check_constraints(table_names=table_names) except Exception as e: - e.args = ("Problem installing fixtures: %s" % e,) + e.args = (f"Problem installing fixtures: {e}", ) raise # If we found even one object in a fixture, we need to reset the @@ -232,13 +231,12 @@ def load_label(self, fixture_label): open_method, mode = self.compression_formats[cmp_fmt] fixture = open_method(fixture_file, mode) self.fixture_count += 1 - objects_in_fixture = 0 loaded_objects_in_fixture = 0 if self.verbosity >= 2: self.stdout.write( - "Installing %s fixture '%s' from %s." - % (ser_fmt, fixture_name, humanize(fixture_dir)) + f"Installing {ser_fmt} fixture '{fixture_name}' from {humanize(fixture_dir)}." ) + objects_in_fixture = 0 try: objects = serializers.deserialize( ser_fmt, @@ -259,9 +257,7 @@ def load_label(self, fixture_label): ) except Exception as e: if not isinstance(e, CommandError): - e.args = ( - "Problem installing fixture '%s': %s" % (fixture_file, e), - ) + e.args = (f"Problem installing fixture '{fixture_file}': {e}", ) raise finally: fixture.close() @@ -273,8 +269,7 @@ def load_label(self, fixture_label): # Warn if the fixture we loaded contains 0 objects. if objects_in_fixture == 0: warnings.warn( - "No fixture data found for '%s'. (File format may be " - "invalid.)" % fixture_name, + f"No fixture data found for '{fixture_name}'. (File format may be invalid.)", RuntimeWarning, ) @@ -293,23 +288,17 @@ def get_targets(self, fixture_name, ser_fmt, cmp_fmt): cmp_fmts = self.compression_formats if cmp_fmt is None else [cmp_fmt] ser_fmts = self.serialization_formats if ser_fmt is None else [ser_fmt] return { - "%s.%s" - % ( - fixture_name, - ".".join([ext for ext in combo if ext]), - ) + f'{fixture_name}.{".".join([ext for ext in combo if ext])}' for combo in product(databases, ser_fmts, cmp_fmts) } def find_fixture_files_in_dir(self, fixture_dir, fixture_name, targets): - fixture_files_in_dir = [] path = os.path.join(fixture_dir, fixture_name) - for candidate in glob.iglob(glob.escape(path) + "*"): - if os.path.basename(candidate) in targets: - # Save the fixture_dir and fixture_name for future error - # messages. - fixture_files_in_dir.append((candidate, fixture_dir, fixture_name)) - return fixture_files_in_dir + return [ + (candidate, fixture_dir, fixture_name) + for candidate in glob.iglob(f"{glob.escape(path)}*") + if os.path.basename(candidate) in targets + ] @functools.lru_cache(maxsize=None) def find_fixtures(self, fixture_label): @@ -319,35 +308,32 @@ def find_fixtures(self, fixture_label): fixture_name, ser_fmt, cmp_fmt = self.parse_name(fixture_label) if self.verbosity >= 2: - self.stdout.write("Loading '%s' fixtures..." % fixture_name) + self.stdout.write(f"Loading '{fixture_name}' fixtures...") fixture_name, fixture_dirs = self.get_fixture_name_and_dirs(fixture_name) targets = self.get_targets(fixture_name, ser_fmt, cmp_fmt) fixture_files = [] for fixture_dir in fixture_dirs: if self.verbosity >= 2: - self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir)) + self.stdout.write(f"Checking {humanize(fixture_dir)} for fixtures...") fixture_files_in_dir = self.find_fixture_files_in_dir( fixture_dir, fixture_name, targets, ) if self.verbosity >= 2 and not fixture_files_in_dir: - self.stdout.write( - "No fixture '%s' in %s." % (fixture_name, humanize(fixture_dir)) - ) + self.stdout.write(f"No fixture '{fixture_name}' in {humanize(fixture_dir)}.") # Check kept for backwards-compatibility; it isn't clear why # duplicates are only allowed in different directories. if len(fixture_files_in_dir) > 1: raise CommandError( - "Multiple fixtures named '%s' in %s. Aborting." - % (fixture_name, humanize(fixture_dir)) + f"Multiple fixtures named '{fixture_name}' in {humanize(fixture_dir)}. Aborting." ) fixture_files.extend(fixture_files_in_dir) if not fixture_files: - raise CommandError("No fixture named '%s' found." % fixture_name) + raise CommandError(f"No fixture named '{fixture_name}' found.") return fixture_files @@ -360,18 +346,16 @@ def fixture_dirs(self): application, if it exists, the directories in FIXTURE_DIRS, and the current directory. """ - dirs = [] fixture_dirs = settings.FIXTURE_DIRS if len(fixture_dirs) != len(set(fixture_dirs)): raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.") + dirs = [] for app_config in apps.get_app_configs(): app_label = app_config.label app_dir = os.path.join(app_config.path, "fixtures") if app_dir in fixture_dirs: raise ImproperlyConfigured( - "'%s' is a default fixture directory for the '%s' app " - "and cannot be listed in settings.FIXTURE_DIRS." - % (app_dir, app_label) + f"'{app_dir}' is a default fixture directory for the '{app_label}' app and cannot be listed in settings.FIXTURE_DIRS." ) if self.app_label and app_label != self.app_label: @@ -402,14 +386,12 @@ def parse_name(self, fixture_name): cmp_fmt = None if len(parts) > 1: - if parts[-1] in self.serialization_formats: - ser_fmt = parts[-1] - parts = parts[:-1] - else: + if parts[-1] not in self.serialization_formats: raise CommandError( - "Problem installing fixture '%s': %s is not a known " - "serialization format." % (".".join(parts[:-1]), parts[-1]) + f"""Problem installing fixture '{".".join(parts[:-1])}': {parts[-1]} is not a known serialization format.""" ) + ser_fmt = parts[-1] + parts = parts[:-1] else: ser_fmt = None @@ -429,4 +411,4 @@ def read(self): def humanize(dirname): - return "'%s'" % dirname if dirname else "absolute path" + return f"'{dirname}'" if dirname else "absolute path" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemessages.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemessages.py index 77c84cb9..b953b9f2 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemessages.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemessages.py @@ -47,10 +47,7 @@ def __init__(self, dirpath, file_name, locale_dir): self.locale_dir = locale_dir def __repr__(self): - return "<%s: %s>" % ( - self.__class__.__name__, - os.sep.join([self.dirpath, self.file]), - ) + return f"<{self.__class__.__name__}: {os.sep.join([self.dirpath, self.file])}>" def __eq__(self, other): return self.path == other.path @@ -98,7 +95,7 @@ def work_path(self): "djangojs": "c", "django": "py", }.get(self.domain) - filename = "%s.%s" % (self.translatable.file, extension) + filename = f"{self.translatable.file}.{extension}" return os.path.join(self.translatable.dirpath, filename) def preprocess(self): @@ -140,7 +137,7 @@ def postprocess_messages(self, msgs): new_path = self.path[2:] return re.sub( - r"^(#: .*)(" + re.escape(old_path) + r")", + f"^(#: .*)({re.escape(old_path)})", lambda match: match[0].replace(old_path, new_path), msgs, flags=re.MULTILINE, @@ -150,12 +147,8 @@ def cleanup(self): """ Remove a preprocessed copy of a translatable file (if any). """ - if self.is_templatized: - # This check is needed for the case of a symlinked file and its - # source being processed inside a single group (locale dir); - # removing either of those two removes both. - if os.path.exists(self.work_path): - os.unlink(self.work_path) + if self.is_templatized and os.path.exists(self.work_path): + os.unlink(self.work_path) def normalize_eols(raw_contents): @@ -186,10 +179,9 @@ def write_pot_file(potfile, msgs): lines = [] found, header_read = False, False for line in pot_lines: - if not found and not header_read: - if "charset=CHARSET" in line: - found = True - line = line.replace("charset=CHARSET", "charset=UTF-8") + if not found and not header_read and "charset=CHARSET" in line: + found = True + line = line.replace("charset=CHARSET", "charset=UTF-8") if not line and not found: header_read = True lines.append(line) @@ -346,10 +338,9 @@ def handle(self, *args, **options): if options["add_location"]: if self.gettext_version < (0, 19): raise CommandError( - "The --add-location option requires gettext 0.19 or later. " - "You have %s." % ".".join(str(x) for x in self.gettext_version) + f'The --add-location option requires gettext 0.19 or later. You have {".".join(str(x) for x in self.gettext_version)}.' ) - arg_add_location = "--add-location=%s" % options["add_location"] + arg_add_location = f'--add-location={options["add_location"]}' self.msgmerge_options = self.msgmerge_options[:] + [arg_add_location] self.msguniq_options = self.msguniq_options[:] + [arg_add_location] self.msgattrib_options = self.msgattrib_options[:] + [arg_add_location] @@ -371,19 +362,17 @@ def handle(self, *args, **options): if (not locale and not exclude and not process_all) or self.domain is None: raise CommandError( - "Type '%s help %s' for usage information." - % (os.path.basename(sys.argv[0]), sys.argv[1]) + f"Type '{os.path.basename(sys.argv[0])} help {sys.argv[1]}' for usage information." ) if self.verbosity > 1: self.stdout.write( - "examining files with the extensions: %s" - % get_text_list(list(self.extensions), "and") + f'examining files with the extensions: {get_text_list(list(self.extensions), "and")}' ) - self.invoked_for_django = False self.locale_paths = [] self.default_locale_path = None + self.invoked_for_django = False if os.path.isdir(os.path.join("conf", "locale")): self.locale_paths = [os.path.abspath(os.path.join("conf", "locale"))] self.default_locale_path = self.locale_paths[0] @@ -400,9 +389,7 @@ def handle(self, *args, **options): # Build locale list looks_like_locale = re.compile(r"[a-z]{2}") - locale_dirs = filter( - os.path.isdir, glob.glob("%s/*" % self.default_locale_path) - ) + locale_dirs = filter(os.path.isdir, glob.glob(f"{self.default_locale_path}/*")) all_locales = [ lang_code for lang_code in map(os.path.basename, locale_dirs) @@ -428,15 +415,11 @@ def handle(self, *args, **options): for locale in locales: if "-" in locale: self.stdout.write( - "invalid locale %s, did you mean %s?" - % ( - locale, - locale.replace("-", "_"), - ), + f'invalid locale {locale}, did you mean {locale.replace("-", "_")}?' ) continue if self.verbosity > 0: - self.stdout.write("processing locale %s" % locale) + self.stdout.write(f"processing locale {locale}") for potfile in potfiles: self.write_po_file(potfile, locale) finally: @@ -451,8 +434,7 @@ def gettext_version(self): ["xgettext", "--version"], stdout_encoding=DEFAULT_LOCALE_ENCODING, ) - m = re.search(r"(\d+)\.(\d+)\.?(\d+)?", out) - if m: + if m := re.search(r"(\d+)\.(\d+)\.?(\d+)?", out): return tuple(int(d) for d in m.groups() if d is not None) else: raise CommandError("Unable to get gettext version. Is it installed?") @@ -476,7 +458,7 @@ def build_potfiles(self): self.process_files(file_list) potfiles = [] for path in self.locale_paths: - potfile = os.path.join(path, "%s.pot" % self.domain) + potfile = os.path.join(path, f"{self.domain}.pot") if not os.path.exists(potfile): continue args = ["msguniq"] + self.msguniq_options + [potfile] @@ -496,7 +478,7 @@ def build_potfiles(self): def remove_potfiles(self): for path in self.locale_paths: - pot_path = os.path.join(path, "%s.pot" % self.domain) + pot_path = os.path.join(path, f"{self.domain}.pot") if os.path.exists(pot_path): os.unlink(pot_path) @@ -526,7 +508,7 @@ def find_files(self, root): ): dirnames.remove(dirname) if self.verbosity > 1: - self.stdout.write("ignoring directory %s" % dirname) + self.stdout.write(f"ignoring directory {dirname}") elif dirname == "locale": dirnames.remove(dirname) self.locale_paths.insert( @@ -539,15 +521,18 @@ def find_files(self, root): file_path, self.ignore_patterns ): if self.verbosity > 1: - self.stdout.write( - "ignoring file %s in %s" % (filename, dirpath) - ) + self.stdout.write(f"ignoring file {filename} in {dirpath}") else: - locale_dir = None - for path in self.locale_paths: - if os.path.abspath(dirpath).startswith(os.path.dirname(path)): - locale_dir = path - break + locale_dir = next( + ( + path + for path in self.locale_paths + if os.path.abspath(dirpath).startswith( + os.path.dirname(path) + ) + ), + None, + ) locale_dir = locale_dir or self.default_locale_path or NO_LOCALE_DIR all_files.append( self.translatable_file_class(dirpath, filename, locale_dir) @@ -577,8 +562,7 @@ def process_locale_dir(self, locale_dir, files): for translatable in files: if self.verbosity > 1: self.stdout.write( - "processing file %s in %s" - % (translatable.file, translatable.dirpath) + f"processing file {translatable.file} in {translatable.dirpath}" ) if self.domain not in ("djangojs", "django"): continue @@ -587,12 +571,7 @@ def process_locale_dir(self, locale_dir, files): build_file.preprocess() except UnicodeDecodeError as e: self.stdout.write( - "UnicodeDecodeError: skipped file %s in %s (reason: %s)" - % ( - translatable.file, - translatable.dirpath, - e, - ) + f"UnicodeDecodeError: skipped file {translatable.file} in {translatable.dirpath} (reason: {e})" ) continue except BaseException: @@ -602,33 +581,33 @@ def process_locale_dir(self, locale_dir, files): raise build_files.append(build_file) - if self.domain == "djangojs": - is_templatized = build_file.is_templatized + if self.domain == "django": args = [ "xgettext", "-d", self.domain, - "--language=%s" % ("C" if is_templatized else "JavaScript",), + "--language=Python", "--keyword=gettext_noop", "--keyword=gettext_lazy", "--keyword=ngettext_lazy:1,2", "--keyword=pgettext:1c,2", "--keyword=npgettext:1c,2,3", + "--keyword=pgettext_lazy:1c,2", + "--keyword=npgettext_lazy:1c,2,3", "--output=-", ] - elif self.domain == "django": + elif self.domain == "djangojs": + is_templatized = build_file.is_templatized args = [ "xgettext", "-d", self.domain, - "--language=Python", + f'--language={"C" if is_templatized else "JavaScript"}', "--keyword=gettext_noop", "--keyword=gettext_lazy", "--keyword=ngettext_lazy:1,2", "--keyword=pgettext:1c,2", "--keyword=npgettext:1c,2,3", - "--keyword=pgettext_lazy:1c,2", - "--keyword=npgettext_lazy:1c,2,3", "--output=-", ] else: @@ -666,7 +645,7 @@ def process_locale_dir(self, locale_dir, files): ) for build_file in build_files: msgs = build_file.postprocess_messages(msgs) - potfile = os.path.join(locale_dir, "%s.pot" % self.domain) + potfile = os.path.join(locale_dir, f"{self.domain}.pot") write_pot_file(potfile, msgs) for build_file in build_files: @@ -681,7 +660,7 @@ def write_po_file(self, potfile, locale): """ basedir = os.path.join(os.path.dirname(potfile), locale, "LC_MESSAGES") os.makedirs(basedir, exist_ok=True) - pofile = os.path.join(basedir, "%s.po" % self.domain) + pofile = os.path.join(basedir, f"{self.domain}.po") if os.path.exists(pofile): args = ["msgmerge"] + self.msgmerge_options + [pofile, potfile] @@ -723,13 +702,10 @@ def copy_plural_forms(self, msgs, locale): contents of a newly created .po file. """ django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__))) - if self.domain == "djangojs": - domains = ("djangojs", "django") - else: - domains = ("django",) + domains = ("djangojs", "django") if self.domain == "djangojs" else ("django", ) for domain in domains: django_po = os.path.join( - django_dir, "conf", "locale", locale, "LC_MESSAGES", "%s.po" % domain + django_dir, "conf", "locale", locale, "LC_MESSAGES", f"{domain}.po" ) if os.path.exists(django_po): with open(django_po, encoding="utf-8") as fp: @@ -737,7 +713,7 @@ def copy_plural_forms(self, msgs, locale): if m: plural_form_line = m["value"] if self.verbosity > 1: - self.stdout.write("copying plural forms: %s" % plural_form_line) + self.stdout.write(f"copying plural forms: {plural_form_line}") lines = [] found = False for line in msgs.splitlines(): diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py index 12352e52..a0b20142 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py @@ -119,8 +119,7 @@ def handle(self, *app_labels, **options): loader.check_consistent_history(connection) except OperationalError as error: warnings.warn( - "Got an error checking a consistent migration history " - "performed for database connection '%s': %s" % (alias, error), + f"Got an error checking a consistent migration history performed for database connection '{alias}': {error}", RuntimeWarning, ) # Before anything else, see if there's conflicting apps and drop out @@ -138,7 +137,7 @@ def handle(self, *app_labels, **options): if conflicts and not self.merge: name_str = "; ".join( - "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() + f'{", ".join(names)} in {app}' for app, names in conflicts.items() ) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " @@ -153,7 +152,7 @@ def handle(self, *app_labels, **options): # If they want to merge and there is something to merge, then # divert into the merge code - if self.merge and conflicts: + if self.merge: return self.handle_merge(loader, conflicts) if self.interactive: @@ -187,34 +186,27 @@ def handle(self, *app_labels, **options): self.write_migration_files(changes) return - # Detect changes - changes = autodetector.changes( + if changes := autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name=self.migration_name, - ) - - if not changes: - # No changes? Tell them. - if self.verbosity >= 1: - if app_labels: - if len(app_labels) == 1: - self.stdout.write( - "No changes detected in app '%s'" % app_labels.pop() - ) - else: - self.stdout.write( - "No changes detected in apps '%s'" - % ("', '".join(app_labels)) - ) - else: - self.stdout.write("No changes detected") - else: + ): self.write_migration_files(changes) if check_changes: sys.exit(1) + elif self.verbosity >= 1: + if app_labels: + if len(app_labels) == 1: + self.stdout.write(f"No changes detected in app '{app_labels.pop()}'") + else: + self.stdout.write( + f"""No changes detected in apps '{"', '".join(app_labels)}'""" + ) + else: + self.stdout.write("No changes detected") + def write_migration_files(self, changes): """ Take a changes dict and write them out as migration files. @@ -222,9 +214,7 @@ def write_migration_files(self, changes): directory_created = {} for app_label, app_migrations in changes.items(): if self.verbosity >= 1: - self.stdout.write( - self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) - ) + self.stdout.write(self.style.MIGRATE_HEADING(f"Migrations for '{app_label}':")) for migration in app_migrations: # Describe the migration writer = MigrationWriter(migration, self.include_header) @@ -241,7 +231,7 @@ def write_migration_files(self, changes): " %s\n" % self.style.MIGRATE_LABEL(migration_string) ) for operation in migration.operations: - self.stdout.write(" - %s" % operation.describe()) + self.stdout.write(f" - {operation.describe()}") if not self.dry_run: # Write the migrations file to the disk. migrations_directory = os.path.dirname(writer.path) @@ -261,7 +251,7 @@ def write_migration_files(self, changes): # the file to the disk. self.stdout.write( self.style.MIGRATE_HEADING( - "Full migrations file '%s':" % writer.filename + f"Full migrations file '{writer.filename}':" ) ) self.stdout.write(writer.as_string()) @@ -300,9 +290,7 @@ def all_items_equal(seq): ) ) if not common_ancestor_count: - raise ValueError( - "Could not find common ancestor of %s" % migration_names - ) + raise ValueError(f"Could not find common ancestor of {migration_names}") # Now work out the operations along each divergent branch for migration in merge_migrations: migration.branch = migration.ancestry[common_ancestor_count:] @@ -315,13 +303,11 @@ def all_items_equal(seq): # (can_optimize_through) to automatically see if they're # mergeable. For now, we always just prompt the user. if self.verbosity > 0: - self.stdout.write(self.style.MIGRATE_HEADING("Merging %s" % app_label)) + self.stdout.write(self.style.MIGRATE_HEADING(f"Merging {app_label}")) for migration in merge_migrations: - self.stdout.write( - self.style.MIGRATE_LABEL(" Branch %s" % migration.name) - ) + self.stdout.write(self.style.MIGRATE_LABEL(f" Branch {migration.name}")) for operation in migration.merged_operations: - self.stdout.write(" - %s" % operation.describe()) + self.stdout.write(f" - {operation.describe()}") if questioner.ask_merge(app_label): # If they still want to merge it, then write out an empty # file depending on the migrations needing merging. @@ -373,7 +359,7 @@ def all_items_equal(seq): # the file to the disk. self.stdout.write( self.style.MIGRATE_HEADING( - "Full merge migrations file '%s':" % writer.filename + f"Full merge migrations file '{writer.filename}':" ) ) self.stdout.write(writer.as_string()) diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/sql.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/sql.py index 2375cc23..a6dff489 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/sql.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/sql.py @@ -27,7 +27,7 @@ def emit_pre_migrate_signal(verbosity, interactive, db, **kwargs): if verbosity >= 2: stdout = kwargs.get("stdout", sys.stdout) stdout.write( - "Running pre-migrate handlers for application %s" % app_config.label + f"Running pre-migrate handlers for application {app_config.label}" ) models.signals.pre_migrate.send( sender=app_config, @@ -47,7 +47,7 @@ def emit_post_migrate_signal(verbosity, interactive, db, **kwargs): if verbosity >= 2: stdout = kwargs.get("stdout", sys.stdout) stdout.write( - "Running post-migrate handlers for application %s" % app_config.label + f"Running post-migrate handlers for application {app_config.label}" ) models.signals.post_migrate.send( sender=app_config, diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/templates.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/templates.py index 32ceee89..6bd04b0d 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/templates.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/templates.py @@ -81,8 +81,8 @@ def add_arguments(self, parser): def handle(self, app_or_project, name, target=None, **options): self.app_or_project = app_or_project - self.a_or_an = "an" if app_or_project == "app" else "a" self.paths_to_remove = [] + self.a_or_an = "an" if app_or_project == "app" else "a" self.verbosity = options["verbosity"] self.validate_name(name) @@ -93,7 +93,7 @@ def handle(self, app_or_project, name, target=None, **options): try: os.makedirs(top_dir) except FileExistsError: - raise CommandError("'%s' already exists" % top_dir) + raise CommandError(f"'{top_dir}' already exists") except OSError as e: raise CommandError(e) else: @@ -102,8 +102,7 @@ def handle(self, app_or_project, name, target=None, **options): self.validate_name(os.path.basename(top_dir), "directory") if not os.path.exists(top_dir): raise CommandError( - "Destination directory '%s' does not " - "exist, please create it first." % top_dir + f"Destination directory '{top_dir}' does not exist, please create it first." ) extensions = tuple(handle_extensions(options["extensions"])) @@ -112,21 +111,18 @@ def handle(self, app_or_project, name, target=None, **options): for file in options["files"]: extra_files.extend(map(lambda x: x.strip(), file.split(","))) if exclude := options.get("exclude"): - for directory in exclude: - excluded_directories.append(directory.strip()) + excluded_directories.extend(directory.strip() for directory in exclude) if self.verbosity >= 2: self.stdout.write( - "Rendering %s template files with extensions: %s" - % (app_or_project, ", ".join(extensions)) + f'Rendering {app_or_project} template files with extensions: {", ".join(extensions)}' ) self.stdout.write( - "Rendering %s template files with filenames: %s" - % (app_or_project, ", ".join(extra_files)) + f'Rendering {app_or_project} template files with filenames: {", ".join(extra_files)}' ) - base_name = "%s_name" % app_or_project - base_subdir = "%s_template" % app_or_project - base_directory = "%s_directory" % app_or_project - camel_case_name = "camel_case_%s_name" % app_or_project + base_name = f"{app_or_project}_name" + base_subdir = f"{app_or_project}_template" + base_directory = f"{app_or_project}_directory" + camel_case_name = f"camel_case_{app_or_project}_name" camel_case_value = "".join(x for x in name.title() if x != "_") context = Context( @@ -179,13 +175,7 @@ def handle(self, app_or_project, name, target=None, **options): if os.path.exists(new_path): raise CommandError( - "%s already exists. Overlaying %s %s into an existing " - "directory won't replace conflicting files." - % ( - new_path, - self.a_or_an, - app_or_project, - ) + f"{new_path} already exists. Overlaying {self.a_or_an} {app_or_project} into an existing directory won't replace conflicting files." ) # Only render the Python files, as we don't want to @@ -201,15 +191,13 @@ def handle(self, app_or_project, name, target=None, **options): shutil.copyfile(old_path, new_path) if self.verbosity >= 2: - self.stdout.write("Creating %s" % new_path) + self.stdout.write(f"Creating {new_path}") try: shutil.copymode(old_path, new_path) self.make_writeable(new_path) except OSError: self.stderr.write( - "Notice: Couldn't set permission bits on %s. You're " - "probably using an uncommon filesystem setup. No " - "problem." % new_path, + f"Notice: Couldn't set permission bits on {new_path}. You're probably using an uncommon filesystem setup. No problem.", self.style.NOTICE, ) @@ -230,23 +218,22 @@ def handle_template(self, template, subdir): """ if template is None: return os.path.join(django.__path__[0], "conf", subdir) - else: - if template.startswith("file://"): - template = template[7:] - expanded_template = os.path.expanduser(template) - expanded_template = os.path.normpath(expanded_template) - if os.path.isdir(expanded_template): - return expanded_template - if self.is_url(template): - # downloads the file and returns the path - absolute_path = self.download(template) - else: - absolute_path = os.path.abspath(expanded_template) - if os.path.exists(absolute_path): - return self.extract(absolute_path) + if template.startswith("file://"): + template = template[7:] + expanded_template = os.path.expanduser(template) + expanded_template = os.path.normpath(expanded_template) + if os.path.isdir(expanded_template): + return expanded_template + absolute_path = ( + self.download(template) + if self.is_url(template) + else os.path.abspath(expanded_template) + ) + if os.path.exists(absolute_path): + return self.extract(absolute_path) raise CommandError( - "couldn't handle %s template %s." % (self.app_or_project, template) + f"couldn't handle {self.app_or_project} template {template}." ) def validate_name(self, name, name_or_dir="name"): @@ -292,25 +279,20 @@ def download(self, url): def cleanup_url(url): tmp = url.rstrip("/") filename = tmp.split("/")[-1] - if url.endswith("/"): - display_url = tmp + "/" - else: - display_url = url + display_url = f"{tmp}/" if url.endswith("/") else url return filename, display_url - prefix = "django_%s_template_" % self.app_or_project + prefix = f"django_{self.app_or_project}_template_" tempdir = tempfile.mkdtemp(prefix=prefix, suffix="_download") self.paths_to_remove.append(tempdir) filename, display_url = cleanup_url(url) if self.verbosity >= 2: - self.stdout.write("Downloading %s" % display_url) + self.stdout.write(f"Downloading {display_url}") try: the_path, info = urlretrieve(url, os.path.join(tempdir, filename)) except OSError as e: - raise CommandError( - "couldn't download URL %s to %s: %s" % (url, filename, e) - ) + raise CommandError(f"couldn't download URL {url} to {filename}: {e}") used_name = the_path.split("/")[-1] @@ -355,18 +337,16 @@ def extract(self, filename): Extract the given file to a temporary directory and return the path of the directory with the extracted content. """ - prefix = "django_%s_template_" % self.app_or_project + prefix = f"django_{self.app_or_project}_template_" tempdir = tempfile.mkdtemp(prefix=prefix, suffix="_extract") self.paths_to_remove.append(tempdir) if self.verbosity >= 2: - self.stdout.write("Extracting %s" % filename) + self.stdout.write(f"Extracting {filename}") try: archive.extract(filename, tempdir) return tempdir except (archive.ArchiveException, OSError) as e: - raise CommandError( - "couldn't extract file %s to %s: %s" % (filename, tempdir, e) - ) + raise CommandError(f"couldn't extract file {filename} to {tempdir}: {e}") def is_url(self, template): """Return True if the name looks like a URL.""" diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/management/utils.py b/unicoding_venv/lib/python3.9/site-packages/django/core/management/utils.py index d71f4df9..52de6d9e 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/management/utils.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/management/utils.py @@ -19,7 +19,7 @@ def popen_wrapper(args, stdout_encoding="utf-8"): try: p = run(args, stdout=PIPE, stderr=PIPE, close_fds=os.name != "nt") except OSError as err: - raise CommandError("Error executing %s" % args[0]) from err + raise CommandError(f"Error executing {args[0]}") from err return ( p.stdout.decode(stdout_encoding), p.stderr.decode(DEFAULT_LOCALE_ENCODING, errors="replace"), @@ -45,7 +45,7 @@ def handle_extensions(extensions): ext_list.extend(ext.replace(" ", "").split(",")) for i, ext in enumerate(ext_list): if not ext.startswith("."): - ext_list[i] = ".%s" % ext_list[i] + ext_list[i] = f".{ext_list[i]}" return set(ext_list) @@ -97,7 +97,7 @@ def parse_apps_and_model_labels(labels): try: model = installed_apps.get_model(label) except LookupError: - raise CommandError("Unknown model: %s" % label) + raise CommandError(f"Unknown model: {label}") models.add(model) else: try: @@ -128,7 +128,7 @@ def get_command_line_option(argv, option): def normalize_path_patterns(patterns): """Normalize an iterable of glob style patterns based on OS.""" patterns = [os.path.normcase(p) for p in patterns] - dir_suffixes = {"%s*" % path_sep for path_sep in {"/", os.sep}} + dir_suffixes = {f"{path_sep}*" for path_sep in {"/", os.sep}} norm_patterns = [] for pattern in patterns: for dir_suffix in dir_suffixes: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/paginator.py b/unicoding_venv/lib/python3.9/site-packages/django/core/paginator.py index 56844560..48371501 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/paginator.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/paginator.py @@ -50,11 +50,10 @@ def validate_number(self, number): raise PageNotAnInteger(_("That page number is not an integer")) if number < 1: raise EmptyPage(_("That page number is less than 1")) - if number > self.num_pages: - if number == 1 and self.allow_empty_first_page: - pass - else: - raise EmptyPage(_("That page contains no results")) + if number > self.num_pages and ( + number != 1 or not self.allow_empty_first_page + ): + raise EmptyPage(_("That page contains no results")) return number def get_page(self, number): @@ -119,15 +118,12 @@ def _check_object_list_is_ordered(self): ordered = getattr(self.object_list, "ordered", None) if ordered is not None and not ordered: obj_list_repr = ( - "{} {}".format( - self.object_list.model, self.object_list.__class__.__name__ - ) + f"{self.object_list.model} {self.object_list.__class__.__name__}" if hasattr(self.object_list, "model") else "{!r}".format(self.object_list) ) warnings.warn( - "Pagination may yield inconsistent results with an unordered " - "object_list: {}.".format(obj_list_repr), + f"Pagination may yield inconsistent results with an unordered object_list: {obj_list_repr}.", UnorderedObjectListWarning, stacklevel=3, ) @@ -171,7 +167,7 @@ def __init__(self, object_list, number, paginator): self.paginator = paginator def __repr__(self): - return "" % (self.number, self.paginator.num_pages) + return f"" def __len__(self): return len(self.object_list) @@ -179,8 +175,7 @@ def __len__(self): def __getitem__(self, index): if not isinstance(index, (int, slice)): raise TypeError( - "Page indices must be integers or slices, not %s." - % type(index).__name__ + f"Page indices must be integers or slices, not {type(index).__name__}." ) # The object_list is converted to a list so that if it was a QuerySet # it won't be a database hit per __getitem__. diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/signing.py b/unicoding_venv/lib/python3.9/site-packages/django/core/signing.py index 633d6cc7..62995285 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/signing.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/signing.py @@ -166,27 +166,24 @@ def __init__(self, key=None, sep=":", salt=None, algorithm=None): "Unsafe Signer separator: %r (cannot be empty or consist of " "only A-z0-9-_=)" % sep, ) - self.salt = salt or "%s.%s" % ( - self.__class__.__module__, - self.__class__.__name__, - ) + self.salt = salt or f"{self.__class__.__module__}.{self.__class__.__name__}" self.algorithm = algorithm or "sha256" def signature(self, value): return base64_hmac( - self.salt + "signer", value, self.key, algorithm=self.algorithm + f"{self.salt}signer", value, self.key, algorithm=self.algorithm ) def sign(self, value): - return "%s%s%s" % (value, self.sep, self.signature(value)) + return f"{value}{self.sep}{self.signature(value)}" def unsign(self, signed_value): if self.sep not in signed_value: - raise BadSignature('No "%s" found in value' % self.sep) + raise BadSignature(f'No "{self.sep}" found in value') value, sig = signed_value.rsplit(self.sep, 1) if constant_time_compare(sig, self.signature(value)): return value - raise BadSignature('Signature "%s" does not match' % sig) + raise BadSignature(f'Signature "{sig}" does not match') def sign_object(self, obj, serializer=JSONSerializer, compress=False): """ @@ -210,7 +207,7 @@ def sign_object(self, obj, serializer=JSONSerializer, compress=False): is_compressed = True base64d = b64_encode(data).decode() if is_compressed: - base64d = "." + base64d + base64d = f".{base64d}" return self.sign(base64d) def unsign_object(self, signed_obj, serializer=JSONSerializer, **kwargs): @@ -232,7 +229,7 @@ def timestamp(self): return b62_encode(int(time.time())) def sign(self, value): - value = "%s%s%s" % (value, self.sep, self.timestamp()) + value = f"{value}{self.sep}{self.timestamp()}" return super().sign(value) def unsign(self, value, max_age=None): @@ -249,5 +246,5 @@ def unsign(self, value, max_age=None): # Check timestamp is not older than max_age age = time.time() - timestamp if age > max_age: - raise SignatureExpired("Signature age %s > %s seconds" % (age, max_age)) + raise SignatureExpired(f"Signature age {age} > {max_age} seconds") return value diff --git a/unicoding_venv/lib/python3.9/site-packages/django/core/validators.py b/unicoding_venv/lib/python3.9/site-packages/django/core/validators.py index 4879c862..388ed098 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/core/validators.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/core/validators.py @@ -125,26 +125,24 @@ def __call__(self, value): try: super().__call__(value) except ValidationError as e: - # Trivial case failed. Try for possible IDN domain - if value: - try: - scheme, netloc, path, query, fragment = urlsplit(value) - except ValueError: # for example, "Invalid IPv6 URL" - raise ValidationError( - self.message, code=self.code, params={"value": value} - ) - try: - netloc = punycode(netloc) # IDN -> ACE - except UnicodeError: # invalid domain part - raise e - url = urlunsplit((scheme, netloc, path, query, fragment)) - super().__call__(url) - else: + if not value: raise + try: + scheme, netloc, path, query, fragment = urlsplit(value) + except ValueError: # for example, "Invalid IPv6 URL" + raise ValidationError( + self.message, code=self.code, params={"value": value} + ) + try: + netloc = punycode(netloc) # IDN -> ACE + except UnicodeError: # invalid domain part + raise e + url = urlunsplit((scheme, netloc, path, query, fragment)) + super().__call__(url) else: - # Now verify IPv6 in the netloc part - host_match = re.search(r"^\[(.+)\](?::\d{1,5})?$", urlsplit(value).netloc) - if host_match: + if host_match := re.search( + r"^\[(.+)\](?::\d{1,5})?$", urlsplit(value).netloc + ): potential_ip = host_match[1] try: validate_ipv6_address(potential_ip) @@ -257,8 +255,7 @@ def validate_domain_part(self, domain_part): if self.domain_regex.match(domain_part): return True - literal_match = self.literal_regex.match(domain_part) - if literal_match: + if literal_match := self.literal_regex.match(domain_part): ip_address = literal_match[1] try: validate_ipv46_address(ip_address) @@ -357,8 +354,7 @@ def ip_address_validators(protocol, unpack_ipv4): return ip_address_validator_map[protocol.lower()] except KeyError: raise ValueError( - "The protocol '%s' is unknown. Supported: %s" - % (protocol, list(ip_address_validator_map)) + f"The protocol '{protocol}' is unknown. Supported: {list(ip_address_validator_map)}" ) @@ -398,12 +394,14 @@ def __call__(self, value): raise ValidationError(self.message, code=self.code, params=params) def __eq__(self, other): - if not isinstance(other, self.__class__): - return NotImplemented return ( - self.limit_value == other.limit_value - and self.message == other.message - and self.code == other.code + ( + self.limit_value == other.limit_value + and self.message == other.message + and self.code == other.code + ) + if isinstance(other, self.__class__) + else NotImplemented ) def compare(self, a, b): @@ -509,17 +507,11 @@ def __call__(self, value): # A positive exponent adds that many trailing zeros. digits = len(digit_tuple) + exponent decimals = 0 + elif abs(exponent) > len(digit_tuple): + digits = decimals = abs(exponent) else: - # If the absolute value of the negative exponent is larger than the - # number of digits, then it's the same as the number of digits, - # because it'll consume all of the digits in digit_tuple and then - # add abs(exponent) - len(digit_tuple) leading zeros after the - # decimal point. - if abs(exponent) > len(digit_tuple): - digits = decimals = abs(exponent) - else: - digits = len(digit_tuple) - decimals = abs(exponent) + digits = len(digit_tuple) + decimals = abs(exponent) whole_digits = digits - decimals if self.max_digits is not None and digits > self.max_digits: diff --git a/unicoding_venv/lib/python3.9/site-packages/django/shortcuts.py b/unicoding_venv/lib/python3.9/site-packages/django/shortcuts.py index 90ec1bed..4633dd07 100644 --- a/unicoding_venv/lib/python3.9/site-packages/django/shortcuts.py +++ b/unicoding_venv/lib/python3.9/site-packages/django/shortcuts.py @@ -85,7 +85,7 @@ def get_object_or_404(klass, *args, **kwargs): return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: raise Http404( - "No %s matches the given query." % queryset.model._meta.object_name + f"No {queryset.model._meta.object_name} matches the given query." ) @@ -103,15 +103,14 @@ def get_list_or_404(klass, *args, **kwargs): klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ ) raise ValueError( - "First argument to get_list_or_404() must be a Model, Manager, or " - "QuerySet, not '%s'." % klass__name + f"First argument to get_list_or_404() must be a Model, Manager, or QuerySet, not '{klass__name}'." ) - obj_list = list(queryset.filter(*args, **kwargs)) - if not obj_list: + if obj_list := list(queryset.filter(*args, **kwargs)): + return obj_list + else: raise Http404( - "No %s matches the given query." % queryset.model._meta.object_name + f"No {queryset.model._meta.object_name} matches the given query." ) - return obj_list def resolve_url(to, *args, **kwargs): diff --git a/unicoding_venv/lib/python3.9/site-packages/typing_extensions.py b/unicoding_venv/lib/python3.9/site-packages/typing_extensions.py index 31d3564e..eb7cd1fa 100644 --- a/unicoding_venv/lib/python3.9/site-packages/typing_extensions.py +++ b/unicoding_venv/lib/python3.9/site-packages/typing_extensions.py @@ -160,7 +160,7 @@ def _collect_type_vars(types, typevar_types=None): class _FinalForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' def __getitem__(self, parameters): item = typing._type_check(parameters, @@ -232,7 +232,7 @@ def IntVar(name): class _LiteralForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' def __getitem__(self, parameters): return typing._GenericAlias(self, parameters) @@ -441,12 +441,15 @@ def __instancecheck__(cls, instance): _is_callable_members_only(cls)) and issubclass(instance.__class__, cls)): return True - if cls._is_protocol: - if all(hasattr(instance, attr) and - (not callable(getattr(cls, attr, None)) or - getattr(instance, attr) is not None) - for attr in _get_protocol_attrs(cls)): - return True + if cls._is_protocol and all( + hasattr(instance, attr) + and ( + not callable(getattr(cls, attr, None)) + or getattr(instance, attr) is not None + ) + for attr in _get_protocol_attrs(cls) + ): + return True return super().__instancecheck__(instance) class Protocol(metaclass=_ProtocolMeta): @@ -727,7 +730,7 @@ def __new__(cls, name, bases, ns, total=True): optional_keys = set() for base in bases: - annotations.update(base.__dict__.get('__annotations__', {})) + annotations |= base.__dict__.get('__annotations__', {}) required_keys.update(base.__dict__.get('__required_keys__', ())) optional_keys.update(base.__dict__.get('__optional_keys__', ())) @@ -735,20 +738,18 @@ def __new__(cls, name, bases, ns, total=True): for annotation_key, annotation_type in own_annotations.items(): annotation_origin = get_origin(annotation_type) if annotation_origin is Annotated: - annotation_args = get_args(annotation_type) - if annotation_args: + if annotation_args := get_args(annotation_type): annotation_type = annotation_args[0] annotation_origin = get_origin(annotation_type) - if annotation_origin is Required: - required_keys.add(annotation_key) - elif annotation_origin is NotRequired: - optional_keys.add(annotation_key) - elif total: + if ( + annotation_origin is Required + or annotation_origin is not NotRequired + and total + ): required_keys.add(annotation_key) else: optional_keys.add(annotation_key) - tp_dict.__annotations__ = annotations tp_dict.__required_keys__ = frozenset(required_keys) tp_dict.__optional_keys__ = frozenset(optional_keys) @@ -844,9 +845,7 @@ def _strip_extras(t): return _strip_extras(t.__args__[0]) if isinstance(t, typing._GenericAlias): stripped_args = tuple(_strip_extras(a) for a in t.__args__) - if stripped_args == t.__args__: - return t - return t.copy_with(stripped_args) + return t if stripped_args == t.__args__ else t.copy_with(stripped_args) if hasattr(types, "GenericAlias") and isinstance(t, types.GenericAlias): stripped_args = tuple(_strip_extras(a) for a in t.__args__) if stripped_args == t.__args__: @@ -1047,9 +1046,7 @@ def get_origin(tp): if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias, ParamSpecArgs, ParamSpecKwargs)): return tp.__origin__ - if tp is typing.Generic: - return typing.Generic - return None + return typing.Generic if tp is typing.Generic else None def get_args(tp): """Get type arguments with all substitutions performed. @@ -1081,7 +1078,7 @@ def get_args(tp): elif sys.version_info[:2] >= (3, 9): class _TypeAliasForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' @_TypeAliasForm def TypeAlias(self, parameters): @@ -1100,7 +1097,7 @@ def TypeAlias(self, parameters): else: class _TypeAliasForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' TypeAlias = _TypeAliasForm('TypeAlias', doc="""Special marker indicating that an assignment should @@ -1150,9 +1147,11 @@ def __repr__(self): return f"{self.__origin__.__name__}.args" def __eq__(self, other): - if not isinstance(other, ParamSpecArgs): - return NotImplemented - return self.__origin__ == other.__origin__ + return ( + self.__origin__ == other.__origin__ + if isinstance(other, ParamSpecArgs) + else NotImplemented + ) class ParamSpecKwargs(_Immutable): """The kwargs for a ParamSpec object. @@ -1173,9 +1172,11 @@ def __repr__(self): return f"{self.__origin__.__name__}.kwargs" def __eq__(self, other): - if not isinstance(other, ParamSpecKwargs): - return NotImplemented - return self.__origin__ == other.__origin__ + return ( + self.__origin__ == other.__origin__ + if isinstance(other, ParamSpecKwargs) + else NotImplemented + ) # 3.10+ if hasattr(typing, 'ParamSpec'): @@ -1356,7 +1357,7 @@ def Concatenate(self, parameters): else: class _ConcatenateForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' def __getitem__(self, parameters): return _concatenate_getitem(self, parameters) @@ -1381,7 +1382,7 @@ def __getitem__(self, parameters): elif sys.version_info[:2] >= (3, 9): class _TypeGuardForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' @_TypeGuardForm def TypeGuard(self, parameters): @@ -1434,7 +1435,7 @@ def is_str(val: Union[str, float]): class _TypeGuardForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' def __getitem__(self, parameters): item = typing._type_check(parameters, @@ -1611,7 +1612,7 @@ def int_or_str(arg: int | str) -> None: elif sys.version_info[:2] >= (3, 9): class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' @_ExtensionsSpecialForm def Required(self, parameters): @@ -1653,7 +1654,7 @@ class Movie(TypedDict): else: class _RequiredForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' def __getitem__(self, parameters): item = typing._type_check(parameters, @@ -1698,7 +1699,7 @@ class Movie(TypedDict): elif sys.version_info[:2] >= (3, 9): class _UnpackSpecialForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' class _UnpackAlias(typing._GenericAlias, _root=True): __class__ = typing.TypeVar @@ -1727,7 +1728,7 @@ class _UnpackAlias(typing._GenericAlias, _root=True): class _UnpackForm(typing._SpecialForm, _root=True): def __repr__(self): - return 'typing_extensions.' + self._name + return f'typing_extensions.{self._name}' def __getitem__(self, parameters): item = typing._type_check(parameters, @@ -1829,7 +1830,7 @@ def __eq__(self, other): def __reduce__(self): return self.__name__ - def __init_subclass__(self, *args, **kwds): + def __init_subclass__(cls, *args, **kwds): if '_root' not in kwds: raise TypeError("Cannot subclass special typing classes") @@ -2038,7 +2039,7 @@ def __new__(cls, typename, bases, ns): # update from user namespace without overriding special namedtuple attributes for key in ns: if key in _prohibited_namedtuple_fields: - raise AttributeError("Cannot overwrite NamedTuple attribute " + key) + raise AttributeError(f"Cannot overwrite NamedTuple attribute {key}") elif key not in _special_namedtuple_fields and key not in nm_tpl._fields: setattr(nm_tpl, key, ns[key]) if typing.Generic in bases: