2025-08-22 01:23:26 +08:00
|
|
|
import os
|
|
|
|
|
import random
|
2026-02-06 00:58:36 +03:00
|
|
|
import re
|
2025-08-22 01:23:26 +08:00
|
|
|
import string
|
2026-01-22 01:42:42 +08:00
|
|
|
import uuid
|
2025-08-22 01:23:26 +08:00
|
|
|
|
|
|
|
|
RANDOM_STRING_POOL = string.ascii_letters + string.digits
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generate_random_string(length: int = 5) -> str:
|
|
|
|
|
# Use the os.urandom(16) as the seed
|
|
|
|
|
random.seed(os.urandom(16))
|
|
|
|
|
return "".join(random.choices(RANDOM_STRING_POOL, k=length))
|
2026-01-22 01:42:42 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_uuid(string: str) -> bool:
|
|
|
|
|
try:
|
|
|
|
|
uuid.UUID(string)
|
|
|
|
|
return True
|
|
|
|
|
except ValueError:
|
|
|
|
|
return False
|
2026-02-06 00:58:36 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def sanitize_identifier(value: str, default: str = "identifier") -> str:
|
|
|
|
|
"""Sanitizes a string to be a valid Python/Jinja2 identifier.
|
|
|
|
|
|
|
|
|
|
Replaces non-alphanumeric characters (except underscores) with underscores,
|
|
|
|
|
collapses consecutive underscores, strips leading/trailing underscores,
|
|
|
|
|
and prepends an underscore if the result starts with a digit.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
value: The raw value to sanitize.
|
|
|
|
|
default: Fallback value if everything is stripped.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
A sanitized string that is a valid Python identifier.
|
|
|
|
|
"""
|
|
|
|
|
sanitized = re.sub(r"[^a-zA-Z0-9_]", "_", value)
|
|
|
|
|
sanitized = re.sub(r"_+", "_", sanitized)
|
|
|
|
|
sanitized = sanitized.strip("_")
|
|
|
|
|
|
|
|
|
|
if sanitized and sanitized[0].isdigit():
|
|
|
|
|
sanitized = "_" + sanitized
|
|
|
|
|
|
|
|
|
|
if not sanitized:
|
|
|
|
|
sanitized = default
|
|
|
|
|
|
|
|
|
|
return sanitized
|