From 15a27059b8dccf19a6fe0f0f7b0c345f6f6f7d55 Mon Sep 17 00:00:00 2001 From: Aakash Singh Date: Tue, 24 Sep 2024 02:53:46 +0530 Subject: [PATCH] lint care/audit_logs --- care/audit_log/helpers.py | 21 ++++++++++----------- care/audit_log/middleware.py | 18 +++++++++--------- care/audit_log/receivers.py | 25 +++++++++++++++++-------- 3 files changed, 36 insertions(+), 28 deletions(-) diff --git a/care/audit_log/helpers.py b/care/audit_log/helpers.py index 04e89814bc..42252ffaa6 100644 --- a/care/audit_log/helpers.py +++ b/care/audit_log/helpers.py @@ -1,3 +1,4 @@ +# ruff: noqa: SLF001 import re from fnmatch import fnmatch from functools import lru_cache @@ -14,7 +15,7 @@ def remove_non_member_fields(d: dict): def instance_finder(v): return isinstance( v, - (list, dict, set), + list | dict | set, ) @@ -41,10 +42,9 @@ class Search(NamedTuple): def _make_search(item): splits = item.split(":") - if len(splits) == 2: + if len(splits) == 2: # noqa: PLR2004 return Search(type=splits[0], value=splits[1]) - else: - return Search(type="plain", value=splits[0]) + return Search(type="plain", value=splits[0]) def candidate_in_scope( @@ -62,7 +62,7 @@ def candidate_in_scope( search_candidate = candidate if is_application: splits = candidate.split(".") - if len(splits) == 2: + if len(splits) == 2: # noqa: PLR2004 app_label, model_name = splits search_candidate = app_label @@ -91,12 +91,11 @@ def exclude_model(model_name): ): return True - if candidate_in_scope( - model_name, settings.AUDIT_LOG["models"]["exclude"]["models"] - ): - return True - - return False + return bool( + candidate_in_scope( + model_name, settings.AUDIT_LOG["models"]["exclude"]["models"] + ) + ) class MetaDataContainer(dict): diff --git a/care/audit_log/middleware.py b/care/audit_log/middleware.py index 35f23efd4b..f2c27d376b 100644 --- a/care/audit_log/middleware.py +++ b/care/audit_log/middleware.py @@ -15,6 +15,7 @@ class RequestInformation(NamedTuple): response: HttpResponse | None exception: Exception | None + logger = logging.getLogger(__name__) @@ -50,7 +51,7 @@ def save(request, response=None, exception=None): if not dal_request_id: dal_request_id = ( f"{request.method.lower()}::" - f"{md5(request.path.lower().encode('utf-8')).hexdigest()}::" + f"{md5(request.path.lower().encode('utf-8')).hexdigest()}::" # noqa: S324 f"{uuid.uuid4().hex}" ) request.dal_request_id = dal_request_id @@ -69,8 +70,7 @@ def get_current_user(): environ = RequestInformation(*AuditLogMiddleware.thread.__dal__) if isinstance(environ.request.user, AnonymousUser): return None - else: - return environ.request.user + return environ.request.user @staticmethod def get_current_request(): @@ -85,14 +85,14 @@ def __call__(self, request: HttpRequest): response: HttpResponse = self.get_response(request) self.save(request, response) - if request.user: - current_user_str = f"{request.user.id}|{request.user}" - else: - current_user_str = None + current_user_str = f"{request.user.id}|{request.user}" if request.user else None logger.info( - f"{request.method} {request.path} {response.status_code} " - f"User:[{current_user_str}]" + "%s %s %s User:[%s]", + request.method, + request.path, + response.status_code, + current_user_str, ) return response diff --git a/care/audit_log/receivers.py b/care/audit_log/receivers.py index 9b812c42a0..95c28d1abb 100644 --- a/care/audit_log/receivers.py +++ b/care/audit_log/receivers.py @@ -1,3 +1,4 @@ +# ruff: noqa: SLF001 import json import logging from typing import NamedTuple @@ -22,6 +23,7 @@ logger = logging.getLogger(__name__) + class Event(NamedTuple): model: str actor: AbstractUser @@ -42,7 +44,7 @@ def pre_save_signal(sender, instance, **kwargs) -> None: model_name = get_model_name(instance) if exclude_model(model_name): - logger.debug(f"{model_name} ignored as per settings") + logger.debug("%s ignored as per settings", model_name) return get_or_create_meta(instance) @@ -61,8 +63,9 @@ def pre_save_signal(sender, instance, **kwargs) -> None: changes = {} if operation not in {Operation.INSERT, Operation.DELETE}: - old, new = remove_non_member_fields(pre.__dict__), remove_non_member_fields( - instance.__dict__ + old, new = ( + remove_non_member_fields(pre.__dict__), + remove_non_member_fields(instance.__dict__), ) try: @@ -107,7 +110,7 @@ def _post_processor(instance, event: Event | None, operation: Operation): model_name = get_model_name(instance) if not event and operation != Operation.DELETE: - logger.debug(f"Event not received for {operation}. Ignoring.") + logger.debug("Event not received for %s. Ignoring.", operation) return try: @@ -118,11 +121,17 @@ def _post_processor(instance, event: Event | None, operation: Operation): else: changes = json.dumps(event.changes if event else {}, cls=LogJsonEncoder) except Exception: - logger.warning(f"Failed to log {event}", exc_info=True) + logger.warning("Failed to log %s", event, exc_info=True) return logger.info( - f"AUDIT_LOG::{request_id}|{actor}|{operation.value}|{model_name}|ID:{instance.pk}|{changes}" + "AUDIT_LOG::%s|%s|%s|%s|ID:%s|%s", + request_id, + actor, + operation.value, + model_name, + instance.pk, + changes, ) @@ -137,7 +146,7 @@ def post_save_signal(sender, instance, created, update_fields: frozenset, **kwar model_name = get_model_name(instance) if exclude_model(model_name): - logger.debug(f"Ignoring {model_name}.") + logger.debug("Ignoring %s.", model_name) return operation = Operation.INSERT if created else Operation.UPDATE @@ -158,7 +167,7 @@ def post_delete_signal(sender, instance, **kwargs) -> None: model_name = get_model_name(instance) if exclude_model(model_name): - logger.debug(f"Ignoring {model_name}.") + logger.debug("Ignoring %s.", model_name) return event = instance._meta.dal.event