Explorar o código

refactor: streamline import statements and improve code readability across admin routes

Manuel hai 9 meses
pai
achega
be51525f80

+ 5 - 3
routes/admin/acls.py

@@ -5,7 +5,11 @@ from flask import flash, redirect, render_template, request, url_for
 from services.auth.auth_service import admin_required
 from services.squid.acls_service import (
     add_acl as service_add_acl,
+)
+from services.squid.acls_service import (
     delete_acl as service_delete_acl,
+)
+from services.squid.acls_service import (
     edit_acl as service_edit_acl,
 )
 
@@ -32,9 +36,7 @@ def register_routes(bp):
         options = request.form.getlist("options[]")
         comment = request.form.get("comment", "").strip()
 
-        success, message = service_add_acl(
-            name, acl_type, values, options, comment, cm
-        )
+        success, message = service_add_acl(name, acl_type, values, options, comment, cm)
         return flash_and_redirect(success, message, "admin.manage_acls")
 
     @bp.route("/acls/edit", methods=["POST"])

+ 4 - 0
routes/admin/delay_pools.py

@@ -5,7 +5,11 @@ from flask import render_template, request
 from services.auth.auth_service import admin_required
 from services.squid.delay_pools_service import (
     add_delay_pool as service_add_delay_pool,
+)
+from services.squid.delay_pools_service import (
     delete_delay_pool as service_delete_delay_pool,
+)
+from services.squid.delay_pools_service import (
     edit_delay_pool as service_edit_delay_pool,
 )
 

+ 7 - 4
routes/admin/helpers.py

@@ -10,11 +10,11 @@ from loguru import logger
 
 from utils.admin import SquidConfigManager
 
-
 # ---------------------------------------------------------------------------
 # Config manager accessor (replaces global mutable)
 # ---------------------------------------------------------------------------
 
+
 def get_config_manager() -> SquidConfigManager:
     """Return the shared :class:`SquidConfigManager` instance.
 
@@ -40,6 +40,7 @@ def reload_config_manager() -> SquidConfigManager:
 # Flash + Redirect helper
 # ---------------------------------------------------------------------------
 
+
 def flash_and_redirect(success: bool, message: str, endpoint: str, **kwargs):
     """Flash a message and redirect to *endpoint* in a single call."""
     flash(message, "success" if success else "error")
@@ -50,6 +51,7 @@ def flash_and_redirect(success: bool, message: str, endpoint: str, **kwargs):
 # Debug mode helper
 # ---------------------------------------------------------------------------
 
+
 def is_debug() -> bool:
     """Return ``True`` when the Flask app is running in debug mode.
 
@@ -65,6 +67,7 @@ def is_debug() -> bool:
 # Form field parsing helpers
 # ---------------------------------------------------------------------------
 
+
 def get_int_form_field(name: str) -> int | None:
     """Parse an integer from ``request.form[name]``.
 
@@ -80,6 +83,7 @@ def get_int_form_field(name: str) -> int | None:
 # JSON error response helpers
 # ---------------------------------------------------------------------------
 
+
 def json_error(message: str, status_code: int = 400, *, details: str | None = None):
     """Build a standard JSON error response.
 
@@ -104,9 +108,8 @@ def json_success(message: str, *, extra: dict | None = None):
 # Flash error with debug details
 # ---------------------------------------------------------------------------
 
-def flash_error_with_details(
-    user_message: str, exception: Exception | None = None
-):
+
+def flash_error_with_details(user_message: str, exception: Exception | None = None):
     """Flash an error message; include exception details in debug mode."""
     if is_debug() and exception is not None:
         flash(f"{user_message}: {exception}", "error")

+ 6 - 0
routes/admin/http_access.py

@@ -5,8 +5,14 @@ from flask import flash, redirect, render_template, request, url_for
 from services.auth.auth_service import admin_required
 from services.squid.http_access_service import (
     add_http_access as service_add_http_access,
+)
+from services.squid.http_access_service import (
     delete_http_access as service_delete_http_access,
+)
+from services.squid.http_access_service import (
     edit_http_access as service_edit_http_access,
+)
+from services.squid.http_access_service import (
     move_http_access as service_move_http_access,
 )
 

+ 1 - 3
routes/admin/logs.py

@@ -15,7 +15,5 @@ def register_routes(bp):
         max_lines = min(max(max_lines, 10), 1000)
 
         log_files = [Config.SQUID_LOG, Config.SQUID_CACHE_LOG]
-        logs = service_read_logs(
-            log_files, max_lines, debug=bool(current_app.debug)
-        )
+        logs = service_read_logs(log_files, max_lines, debug=bool(current_app.debug))
         return render_template("admin/logs.html", logs=logs, max_lines=max_lines)

+ 8 - 7
routes/admin/squid_config.py

@@ -8,18 +8,19 @@ from services.database.admin_helpers import load_env_vars, save_env_vars
 from services.squid.config_service import save_config as service_save_config
 from services.squid.split_config_service import (
     get_split_files_info as service_get_split_files_info,
+)
+from services.squid.split_config_service import (
     get_split_view_data as service_get_split_view_data,
+)
+from services.squid.split_config_service import (
     split_config as service_split_config,
 )
 from services.squid.squid_config_splitter import SquidConfigSplitter
 
 from .helpers import (
-    flash_and_redirect,
     flash_error_with_details,
     get_config_manager,
-    is_debug,
     json_error,
-    json_success,
     reload_config_manager,
 )
 
@@ -51,7 +52,9 @@ def register_routes(bp):
                 flash(message, "success")
                 return redirect(url_for("admin.view_config"))
             else:
-                flash_error_with_details("Error saving configuration", Exception(message))
+                flash_error_with_details(
+                    "Error saving configuration", Exception(message)
+                )
         return render_template(
             "admin/edit_config.html", config_content=cm.config_content
         )
@@ -129,9 +132,7 @@ def register_routes(bp):
             )
         except RuntimeError as e:
             logger.error(f"Error de validación: {e}")
-            return json_error(
-                "Error de validación de la configuración", 400
-            )
+            return json_error("Error de validación de la configuración", 400)
         except Exception as e:
             logger.exception("Error al dividir el archivo de configuración")
             return json_error(

+ 4 - 4
routes/admin/system_api.py

@@ -14,10 +14,12 @@ from services.database.db_info_service import (
 )
 from services.system.system_service import (
     reload_squid as service_reload_squid,
+)
+from services.system.system_service import (
     restart_squid as service_restart_squid,
 )
 
-from .helpers import is_debug, json_error, json_success
+from .helpers import json_error, json_success
 
 
 def register_routes(bp):
@@ -79,6 +81,4 @@ def register_routes(bp):
 
         except Exception as e:
             logger.exception("Error deleting data from table")
-            return json_error(
-                "Error interno del servidor", 500, details=str(e)
-            )
+            return json_error("Error interno del servidor", 500, details=str(e))

+ 6 - 6
services/security/blocklist_enforcement.py

@@ -39,6 +39,7 @@ BLOCKLIST_ACL_NAME = "squidstats_blocklist"
 # URL / filename validation helpers
 # ---------------------------------------------------------------------------
 
+
 def validate_source_url(source_url: str | None) -> bool:
     """Validate that *source_url* is a well-formed URL.
 
@@ -109,6 +110,7 @@ def resolve_safe_blocklist_path(base_dir: str, filename: str) -> str | None:
 # Enforcement state queries
 # ---------------------------------------------------------------------------
 
+
 def get_enforced_blocklist_urls(cm) -> set[str]:
     """Return the set of source_url values currently enforced as Squid ACLs.
 
@@ -166,6 +168,7 @@ def get_enforced_blocklist_paths(cm) -> dict[str, str]:
 # Enable / disable single blocklist
 # ---------------------------------------------------------------------------
 
+
 def enable_single_blocklist(source_url: str | None, cm) -> tuple[bool, str]:
     """Enable Squid enforcement for a single blocklist (by source_url).
 
@@ -266,6 +269,7 @@ def disable_single_blocklist(source_url: str | None, cm) -> tuple[bool, str]:
 # Internal helpers
 # ---------------------------------------------------------------------------
 
+
 def _read_acl_content(cm) -> str | None:
     """Read ACL content respecting modular vs monolithic config."""
     if cm.is_modular:
@@ -348,9 +352,7 @@ def _upsert_acl_line(cm, acl_line: str, comment_line: str):
         if not cm.save_modular_config("100_acls.conf", "\n".join(lines)):
             raise RuntimeError("Error guardando ACL en config modular")
     else:
-        lines = _filter_acl_lines(
-            cm.config_content.split("\n"), acl_line, comment_line
-        )
+        lines = _filter_acl_lines(cm.config_content.split("\n"), acl_line, comment_line)
         acl_section_end = -1
         for i, line in enumerate(lines):
             if line.strip().startswith("acl "):
@@ -378,9 +380,7 @@ def _remove_acl_line(cm, acl_line: str):
     cm.save_config("\n".join(new_lines))
 
 
-def _filter_acl_lines(
-    lines: list[str], acl_line: str, comment_line: str
-) -> list[str]:
+def _filter_acl_lines(lines: list[str], acl_line: str, comment_line: str) -> list[str]:
     """Remove existing occurrences of an ACL line and its comment."""
     lines = [
         ln