From 2585f73ab47e34a2d6d15898e42e0eed6c237642 Mon Sep 17 00:00:00 2001 From: HighnessAtharva Date: Thu, 5 Jan 2023 00:27:04 +0530 Subject: [PATCH] Code Refactor I have changed code across several files to be more Pythonic, readable and succinct. --- src/flask/app.py | 61 +++++++++++++++------------------------ src/flask/blueprints.py | 8 ++--- src/flask/cli.py | 35 ++++++++++------------ src/flask/config.py | 12 ++------ src/flask/ctx.py | 4 +-- src/flask/debughelpers.py | 4 +-- src/flask/sessions.py | 4 +-- src/flask/wrappers.py | 15 ++-------- 8 files changed, 54 insertions(+), 89 deletions(-) diff --git a/src/flask/app.py b/src/flask/app.py index 315cb6b1..7c3cbe75 100644 --- a/src/flask/app.py +++ b/src/flask/app.py @@ -9,6 +9,7 @@ import weakref from collections.abc import Iterator as _abc_Iterator from datetime import timedelta from itertools import chain +from itertools import product from threading import Lock from types import TracebackType @@ -823,9 +824,7 @@ class Flask(Scaffold): .. versionadded:: 0.8 """ - root_path = self.root_path - if instance_relative: - root_path = self.instance_path + root_path = self.instance_path if instance_relative else self.root_path defaults = dict(self.default_config) defaults["ENV"] = os.environ.get("FLASK_ENV") or "production" defaults["DEBUG"] = get_debug_flag() @@ -994,7 +993,7 @@ class Flask(Scaffold): for name in names: if name in self.template_context_processors: for func in self.template_context_processors[name]: - context.update(func()) + context |= func() context.update(orig_ctx) @@ -1007,7 +1006,7 @@ class Flask(Scaffold): """ rv = {"app": self, "g": g} for processor in self.shell_context_processors: - rv.update(processor()) + rv |= processor() return rv @property @@ -1167,11 +1166,7 @@ class Flask(Scaffold): sn_host, _, sn_port = server_name.partition(":") if not host: - if sn_host: - host = sn_host - else: - host = "127.0.0.1" - + host = sn_host or "127.0.0.1" if port or port == 0: port = int(port) elif sn_port: @@ -1559,18 +1554,17 @@ class Flask(Scaffold): exc_class, code = self._get_exc_class_and_code(type(e)) names = (*request.blueprints, None) - for c in (code, None) if code is not None else (None,): - for name in names: - handler_map = self.error_handler_spec[name][c] + for c, name in product((code, None) if code is not None else (None,), names): + handler_map = self.error_handler_spec[name][c] - if not handler_map: - continue + if not handler_map: + continue - for cls in exc_class.__mro__: - handler = handler_map.get(cls) + for cls in exc_class.__mro__: + handler = handler_map.get(cls) - if handler is not None: - return handler + if handler is not None: + return handler return None def handle_http_exception( @@ -1604,9 +1598,7 @@ class Flask(Scaffold): return e handler = self._find_error_handler(e) - if handler is None: - return e - return self.ensure_sync(handler)(e) + return e if handler is None else self.ensure_sync(handler)(e) def trap_http_exception(self, e: Exception) -> bool: """Checks if an HTTP exception should be trapped or not. By default @@ -1638,10 +1630,7 @@ class Flask(Scaffold): ): return True - if trap_bad_request: - return isinstance(e, BadRequest) - - return False + return isinstance(e, BadRequest) if trap_bad_request else False def handle_user_exception( self, e: Exception @@ -1795,7 +1784,8 @@ class Flask(Scaffold): ): return self.make_default_options_response() # otherwise dispatch to the handler for that endpoint - view_args: t.Dict[str, t.Any] = req.view_args # type: ignore[assignment] + # type: ignore[assignment] + view_args: t.Dict[str, t.Any] = req.view_args return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) def full_dispatch_request(self) -> Response: @@ -1886,10 +1876,7 @@ class Flask(Scaffold): .. versionadded:: 2.0 """ - if iscoroutinefunction(func): - return self.async_to_sync(func) - - return func + return self.async_to_sync(func) if iscoroutinefunction(func) else func def async_to_sync( self, func: t.Callable[..., t.Coroutine] @@ -2142,7 +2129,7 @@ class Flask(Scaffold): # make sure the body is an instance of the response class if not isinstance(rv, self.response_class): - if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator): + if isinstance(rv, (str, bytes, bytearray, _abc_Iterator)): # let the response class set the status and headers instead of # waiting to do it manually, so that the class can handle any # special logic @@ -2213,11 +2200,11 @@ class Flask(Scaffold): # If subdomain matching is disabled (the default), use the # default subdomain in all cases. This should be the default # in Werkzeug but it currently does not have that feature. - if not self.subdomain_matching: - subdomain = self.url_map.default_subdomain or None - else: - subdomain = None - + subdomain = ( + None + if self.subdomain_matching + else self.url_map.default_subdomain or None + ) return self.url_map.bind_to_environ( request.environ, server_name=self.config["SERVER_NAME"], diff --git a/src/flask/blueprints.py b/src/flask/blueprints.py index f6d62ba8..020f32bb 100644 --- a/src/flask/blueprints.py +++ b/src/flask/blueprints.py @@ -84,7 +84,7 @@ class BlueprintSetupState: #: A dictionary with URL defaults that is added to each and every #: URL that was defined with the blueprint. self.url_defaults = dict(self.blueprint.url_values_defaults) - self.url_defaults.update(self.options.get("url_defaults", ())) + self.url_defaults |= self.options.get("url_defaults", ()) def add_url_rule( self, @@ -387,7 +387,7 @@ class Blueprint(Scaffold): f" provide a unique name." ) - first_bp_registration = not any(bp is self for bp in app.blueprints.values()) + first_bp_registration = all(bp is not self for bp in app.blueprints.values()) first_name_registration = name not in app.blueprints app.blueprints[name] = self @@ -414,9 +414,7 @@ class Blueprint(Scaffold): value = defaultdict( dict, { - code: { - exc_class: func for exc_class, func in code_values.items() - } + code: dict(code_values.items()) for code, code_values in value.items() }, ) diff --git a/src/flask/cli.py b/src/flask/cli.py index 37a15ff2..cb6f045d 100644 --- a/src/flask/cli.py +++ b/src/flask/cli.py @@ -299,20 +299,17 @@ class ScriptInfo: if self.create_app is not None: app = self.create_app() + elif self.app_import_path: + path, name = (re.split(r":(?![\\/])", self.app_import_path, 1) + [None])[:2] + import_name = prepare_import(path) + app = locate_app(import_name, name) else: - if self.app_import_path: - path, name = ( - re.split(r":(?![\\/])", self.app_import_path, 1) + [None] - )[:2] + for path in ("wsgi.py", "app.py"): import_name = prepare_import(path) - app = locate_app(import_name, name) - else: - for path in ("wsgi.py", "app.py"): - import_name = prepare_import(path) - app = locate_app(import_name, None, raise_if_not_found=False) + app = locate_app(import_name, None, raise_if_not_found=False) - if app: - break + if app: + break if not app: raise NoAppException( @@ -797,14 +794,14 @@ def _validate_key(ctx, param, value): 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param ) - if not cert: + if cert: + ctx.params["cert"] = cert, value + + else: raise click.BadParameter('"--cert" must also be specified.', ctx, param) - ctx.params["cert"] = cert, value - - else: - if cert and not (is_adhoc or is_context): - raise click.BadParameter('Required when using "--cert".', ctx, param) + elif cert and not is_adhoc and not is_context: + raise click.BadParameter('Required when using "--cert".', ctx, param) return value @@ -962,7 +959,7 @@ def shell_command() -> None: with open(startup) as f: eval(compile(f.read(), startup, "exec"), ctx) - ctx.update(current_app.make_shell_context()) + ctx |= current_app.make_shell_context() # Site, customize, or startup script can set a hook to call when # entering interactive mode. The default one sets up readline with @@ -1008,7 +1005,7 @@ def routes_command(sort: str, all_methods: bool) -> None: ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS")) - if sort in ("endpoint", "rule"): + if sort in {"endpoint", "rule"}: rules = sorted(rules, key=attrgetter(sort)) elif sort == "methods": rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore diff --git a/src/flask/config.py b/src/flask/config.py index d4fc310f..4fa6f6c2 100644 --- a/src/flask/config.py +++ b/src/flask/config.py @@ -1,3 +1,4 @@ +import contextlib import errno import json import os @@ -133,12 +134,8 @@ class Config(dict): value = os.environ[key] - try: + with contextlib.suppress(Exception): value = loads(value) - except Exception: - # Keep the value as a string if loading failed. - pass - # Change to key.removeprefix(prefix) on Python >= 3.9. key = key[len_prefix:] @@ -325,10 +322,7 @@ class Config(dict): for k, v in self.items(): if not k.startswith(namespace): continue - if trim_namespace: - key = k[len(namespace) :] - else: - key = k + key = k[len(namespace) :] if trim_namespace else k if lowercase: key = key.lower() rv[key] = v diff --git a/src/flask/ctx.py b/src/flask/ctx.py index c79c26dc..a82b75d6 100644 --- a/src/flask/ctx.py +++ b/src/flask/ctx.py @@ -374,8 +374,8 @@ class RequestContext: session_interface = self.app.session_interface self.session = session_interface.open_session(self.app, self.request) - if self.session is None: - self.session = session_interface.make_null_session(self.app) + if self.session is None: + self.session = session_interface.make_null_session(self.app) # Match the request URL after loading the session, so that the # session is available in custom URL converters. diff --git a/src/flask/debughelpers.py b/src/flask/debughelpers.py index b0639892..6a94162e 100644 --- a/src/flask/debughelpers.py +++ b/src/flask/debughelpers.py @@ -129,9 +129,7 @@ def explain_template_loading_attempts(app: Flask, template, attempts) -> None: info.append(f"{idx + 1:5}: trying loader of {src_info}") - for line in _dump_loader_info(loader): - info.append(f" {line}") - + info.extend(f" {line}" for line in _dump_loader_info(loader)) if triple is None: detail = "no match" else: diff --git a/src/flask/sessions.py b/src/flask/sessions.py index 02b8cf76..c79ddaac 100644 --- a/src/flask/sessions.py +++ b/src/flask/sessions.py @@ -28,7 +28,7 @@ class SessionMixin(MutableMapping): @permanent.setter def permanent(self, value: bool) -> None: - self["_permanent"] = bool(value) + self["_permanent"] = value #: Some implementations can detect whether a session is newly #: created, but that is not guaranteed. Use with caution. The mixin @@ -195,7 +195,7 @@ class SessionInterface: # set explicitly, or cached from SERVER_NAME detection # if False, return None if rv is not None: - return rv if rv else None + return rv or None rv = app.config["SERVER_NAME"] diff --git a/src/flask/wrappers.py b/src/flask/wrappers.py index e36a72cb..00822121 100644 --- a/src/flask/wrappers.py +++ b/src/flask/wrappers.py @@ -52,10 +52,7 @@ class Request(RequestBase): @property def max_content_length(self) -> t.Optional[int]: # type: ignore """Read-only view of the ``MAX_CONTENT_LENGTH`` config key.""" - if current_app: - return current_app.config["MAX_CONTENT_LENGTH"] - else: - return None + return current_app.config["MAX_CONTENT_LENGTH"] if current_app else None @property def endpoint(self) -> t.Optional[str]: @@ -67,10 +64,7 @@ class Request(RequestBase): This in combination with :attr:`view_args` can be used to reconstruct the same URL or a modified URL. """ - if self.url_rule is not None: - return self.url_rule.endpoint - - return None + return self.url_rule.endpoint if self.url_rule is not None else None @property def blueprint(self) -> t.Optional[str]: @@ -103,10 +97,7 @@ class Request(RequestBase): """ name = self.blueprint - if name is None: - return [] - - return _split_blueprint_path(name) + return [] if name is None else _split_blueprint_path(name) def _load_form_data(self) -> None: super()._load_form_data()