-
Notifications
You must be signed in to change notification settings - Fork 51
Sourcery refactored main branch #110
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
| ] | ||
|
Comment on lines
-51
to
+52
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| return status.HTTP_200_OK, result | ||
|
|
||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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' | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| return self.get(**{case_insensitive_username_field: username}) | ||
|
|
||
| def create_user(self, first_name, last_name, email, password=None): | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
Comment on lines
-18
to
+21
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ): |
||
| # Non-classes we just check directly | ||
| return not asyncio.iscoroutinefunction(application) | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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))}' | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
|
||
| def _get_context_id(self): | ||
| """ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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(): | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| await self.application_exception(exception, details) | ||
| try: | ||
| del self.application_instances[scope_id] | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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) | ||
|
Comment on lines
-33
to
+39
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
|
||
|
|
||
| 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): | ||
|
Comment on lines
-79
to
+77
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| 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: | ||
|
Comment on lines
-468
to
+469
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ): |
||
| return func(*args, **kwargs) | ||
| finally: | ||
| # Only delete the launch_map parent if we set it, otherwise it is | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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"]}', | ||
|
Comment on lines
-59
to
+64
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| "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 | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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." | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| ) | ||
|
|
||
| # 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}>" | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
|
||
| @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)] | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ): |
||
| 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.") | ||
|
Comment on lines
-272
to
+267
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
|
||
| 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}" | ||
|
Comment on lines
-303
to
+296
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| self.models_module = import_module(models_module_name) | ||
|
|
||
| def ready(self): | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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}" | ||
|
Comment on lines
-88
to
+91
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| ) | ||
|
|
||
| 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}'?" | ||
|
Comment on lines
-160
to
+159
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| 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}." | ||
|
Comment on lines
-216
to
+226
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ): |
||
| ) | ||
| 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.") | ||
|
Comment on lines
-280
to
+270
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
| 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) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function
get_onerefactored with the following changes:inline-immediately-returned-variable)