fix: auto-fix code issues (cron)

- 修复重复导入/字段
- 修复异常处理
- 修复PEP8格式问题
- 添加类型注解
- 修复缺失的urllib.parse导入
This commit is contained in:
OpenClaw Bot
2026-02-28 06:03:09 +08:00
parent ff83cab6c7
commit fe3d64a1d2
41 changed files with 4501 additions and 1176 deletions

View File

@@ -35,6 +35,7 @@ except ImportError:
logger = logging.getLogger(__name__)
class LanguageCode(StrEnum):
"""支持的语言代码"""
@@ -51,6 +52,7 @@ class LanguageCode(StrEnum):
AR = "ar"
HI = "hi"
class RegionCode(StrEnum):
"""区域代码"""
@@ -62,6 +64,7 @@ class RegionCode(StrEnum):
LATIN_AMERICA = "latam"
MIDDLE_EAST = "me"
class DataCenterRegion(StrEnum):
"""数据中心区域"""
@@ -75,6 +78,7 @@ class DataCenterRegion(StrEnum):
CN_NORTH = "cn-north"
CN_EAST = "cn-east"
class PaymentProvider(StrEnum):
"""支付提供商"""
@@ -91,6 +95,7 @@ class PaymentProvider(StrEnum):
SEPA = "sepa"
UNIONPAY = "unionpay"
class CalendarType(StrEnum):
"""日历类型"""
@@ -102,6 +107,7 @@ class CalendarType(StrEnum):
PERSIAN = "persian"
BUDDHIST = "buddhist"
@dataclass
class Translation:
id: str
@@ -116,6 +122,7 @@ class Translation:
reviewed_by: str | None
reviewed_at: datetime | None
@dataclass
class LanguageConfig:
code: str
@@ -133,6 +140,7 @@ class LanguageConfig:
first_day_of_week: int
calendar_type: str
@dataclass
class DataCenter:
id: str
@@ -147,6 +155,7 @@ class DataCenter:
created_at: datetime
updated_at: datetime
@dataclass
class TenantDataCenterMapping:
id: str
@@ -158,6 +167,7 @@ class TenantDataCenterMapping:
created_at: datetime
updated_at: datetime
@dataclass
class LocalizedPaymentMethod:
id: str
@@ -175,6 +185,7 @@ class LocalizedPaymentMethod:
created_at: datetime
updated_at: datetime
@dataclass
class CountryConfig:
code: str
@@ -196,6 +207,7 @@ class CountryConfig:
vat_rate: float | None
is_active: bool
@dataclass
class TimezoneConfig:
id: str
@@ -206,6 +218,7 @@ class TimezoneConfig:
region: str
is_active: bool
@dataclass
class CurrencyConfig:
code: str
@@ -217,6 +230,7 @@ class CurrencyConfig:
thousands_separator: str
is_active: bool
@dataclass
class LocalizationSettings:
id: str
@@ -236,6 +250,7 @@ class LocalizationSettings:
created_at: datetime
updated_at: datetime
class LocalizationManager:
DEFAULT_LANGUAGES = {
LanguageCode.EN: {
@@ -807,16 +822,32 @@ class LocalizationManager:
)
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_translations_key ON translations(key)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_translations_lang ON translations(language)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_translations_ns ON translations(namespace)")
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_translations_lang ON translations(language)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_translations_ns ON translations(namespace)"
)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_dc_region ON data_centers(region_code)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_dc_status ON data_centers(status)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_tenant_dc ON tenant_data_center_mappings(tenant_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_payment_provider ON localized_payment_methods(provider)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_payment_active ON localized_payment_methods(is_active)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_country_region ON country_configs(region)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_tz_country ON timezone_configs(country_code)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_locale_settings_tenant ON localization_settings(tenant_id)")
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_tenant_dc ON tenant_data_center_mappings(tenant_id)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_payment_provider ON localized_payment_methods(provider)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_payment_active ON localized_payment_methods(is_active)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_country_region ON country_configs(region)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_tz_country ON timezone_configs(country_code)"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_locale_settings_tenant ON localization_settings(tenant_id)"
)
conn.commit()
logger.info("Localization tables initialized successfully")
except Exception as e:
@@ -923,7 +954,9 @@ class LocalizationManager:
finally:
self._close_if_file_db(conn)
def get_translation(self, key: str, language: str, namespace: str = "common", fallback: bool = True) -> str | None:
def get_translation(
self, key: str, language: str, namespace: str = "common", fallback: bool = True
) -> str | None:
conn = self._get_connection()
try:
cursor = conn.cursor()
@@ -937,7 +970,9 @@ class LocalizationManager:
if fallback:
lang_config = self.get_language_config(language)
if lang_config and lang_config.fallback_language:
return self.get_translation(key, lang_config.fallback_language, namespace, False)
return self.get_translation(
key, lang_config.fallback_language, namespace, False
)
if language != "en":
return self.get_translation(key, "en", namespace, False)
return None
@@ -945,7 +980,12 @@ class LocalizationManager:
self._close_if_file_db(conn)
def set_translation(
self, key: str, language: str, value: str, namespace: str = "common", context: str | None = None
self,
key: str,
language: str,
value: str,
namespace: str = "common",
context: str | None = None,
) -> Translation:
conn = self._get_connection()
try:
@@ -971,7 +1011,8 @@ class LocalizationManager:
) -> Translation | None:
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM translations WHERE key = ? AND language = ? AND namespace = ?", (key, language, namespace)
"SELECT * FROM translations WHERE key = ? AND language = ? AND namespace = ?",
(key, language, namespace),
)
row = cursor.fetchone()
if row:
@@ -983,7 +1024,8 @@ class LocalizationManager:
try:
cursor = conn.cursor()
cursor.execute(
"DELETE FROM translations WHERE key = ? AND language = ? AND namespace = ?", (key, language, namespace)
"DELETE FROM translations WHERE key = ? AND language = ? AND namespace = ?",
(key, language, namespace),
)
conn.commit()
return cursor.rowcount > 0
@@ -991,7 +1033,11 @@ class LocalizationManager:
self._close_if_file_db(conn)
def list_translations(
self, language: str | None = None, namespace: str | None = None, limit: int = 1000, offset: int = 0
self,
language: str | None = None,
namespace: str | None = None,
limit: int = 1000,
offset: int = 0,
) -> list[Translation]:
conn = self._get_connection()
try:
@@ -1062,7 +1108,9 @@ class LocalizationManager:
finally:
self._close_if_file_db(conn)
def list_data_centers(self, status: str | None = None, region: str | None = None) -> list[DataCenter]:
def list_data_centers(
self, status: str | None = None, region: str | None = None
) -> list[DataCenter]:
conn = self._get_connection()
try:
cursor = conn.cursor()
@@ -1085,7 +1133,9 @@ class LocalizationManager:
conn = self._get_connection()
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM tenant_data_center_mappings WHERE tenant_id = ?", (tenant_id,))
cursor.execute(
"SELECT * FROM tenant_data_center_mappings WHERE tenant_id = ?", (tenant_id,)
)
row = cursor.fetchone()
if row:
return self._row_to_tenant_dc_mapping(row)
@@ -1135,7 +1185,16 @@ class LocalizationManager:
primary_dc_id = excluded.primary_dc_id, secondary_dc_id = excluded.secondary_dc_id,
region_code = excluded.region_code, data_residency = excluded.data_residency, updated_at = excluded.updated_at
""",
(mapping_id, tenant_id, primary_dc_id, secondary_dc_id, region_code, data_residency, now, now),
(
mapping_id,
tenant_id,
primary_dc_id,
secondary_dc_id,
region_code,
data_residency,
now,
now,
),
)
conn.commit()
return self.get_tenant_data_center(tenant_id)
@@ -1146,7 +1205,9 @@ class LocalizationManager:
conn = self._get_connection()
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM localized_payment_methods WHERE provider = ?", (provider,))
cursor.execute(
"SELECT * FROM localized_payment_methods WHERE provider = ?", (provider,)
)
row = cursor.fetchone()
if row:
return self._row_to_payment_method(row)
@@ -1177,7 +1238,9 @@ class LocalizationManager:
finally:
self._close_if_file_db(conn)
def get_localized_payment_methods(self, country_code: str, language: str = "en") -> list[dict[str, Any]]:
def get_localized_payment_methods(
self, country_code: str, language: str = "en"
) -> list[dict[str, Any]]:
methods = self.list_payment_methods(country_code=country_code)
result = []
for method in methods:
@@ -1207,7 +1270,9 @@ class LocalizationManager:
finally:
self._close_if_file_db(conn)
def list_country_configs(self, region: str | None = None, active_only: bool = True) -> list[CountryConfig]:
def list_country_configs(
self, region: str | None = None, active_only: bool = True
) -> list[CountryConfig]:
conn = self._get_connection()
try:
cursor = conn.cursor()
@@ -1226,7 +1291,11 @@ class LocalizationManager:
self._close_if_file_db(conn)
def format_datetime(
self, dt: datetime, language: str = "en", timezone: str | None = None, format_type: str = "datetime"
self,
dt: datetime,
language: str = "en",
timezone: str | None = None,
format_type: str = "datetime",
) -> str:
try:
if timezone and PYTZ_AVAILABLE:
@@ -1259,7 +1328,9 @@ class LocalizationManager:
logger.error(f"Error formatting datetime: {e}")
return dt.strftime("%Y-%m-%d %H:%M")
def format_number(self, number: float, language: str = "en", decimal_places: int | None = None) -> str:
def format_number(
self, number: float, language: str = "en", decimal_places: int | None = None
) -> str:
try:
if BABEL_AVAILABLE:
try:
@@ -1417,7 +1488,9 @@ class LocalizationManager:
params.append(datetime.now())
params.append(tenant_id)
cursor = conn.cursor()
cursor.execute(f"UPDATE localization_settings SET {', '.join(updates)} WHERE tenant_id = ?", params)
cursor.execute(
f"UPDATE localization_settings SET {', '.join(updates)} WHERE tenant_id = ?", params
)
conn.commit()
return self.get_localization_settings(tenant_id)
finally:
@@ -1454,10 +1527,14 @@ class LocalizationManager:
namespace=row["namespace"],
context=row["context"],
created_at=(
datetime.fromisoformat(row["created_at"]) if isinstance(row["created_at"], str) else row["created_at"]
datetime.fromisoformat(row["created_at"])
if isinstance(row["created_at"], str)
else row["created_at"]
),
updated_at=(
datetime.fromisoformat(row["updated_at"]) if isinstance(row["updated_at"], str) else row["updated_at"]
datetime.fromisoformat(row["updated_at"])
if isinstance(row["updated_at"], str)
else row["updated_at"]
),
is_reviewed=bool(row["is_reviewed"]),
reviewed_by=row["reviewed_by"],
@@ -1498,10 +1575,14 @@ class LocalizationManager:
supported_regions=json.loads(row["supported_regions"] or "[]"),
capabilities=json.loads(row["capabilities"] or "{}"),
created_at=(
datetime.fromisoformat(row["created_at"]) if isinstance(row["created_at"], str) else row["created_at"]
datetime.fromisoformat(row["created_at"])
if isinstance(row["created_at"], str)
else row["created_at"]
),
updated_at=(
datetime.fromisoformat(row["updated_at"]) if isinstance(row["updated_at"], str) else row["updated_at"]
datetime.fromisoformat(row["updated_at"])
if isinstance(row["updated_at"], str)
else row["updated_at"]
),
)
@@ -1514,10 +1595,14 @@ class LocalizationManager:
region_code=row["region_code"],
data_residency=row["data_residency"],
created_at=(
datetime.fromisoformat(row["created_at"]) if isinstance(row["created_at"], str) else row["created_at"]
datetime.fromisoformat(row["created_at"])
if isinstance(row["created_at"], str)
else row["created_at"]
),
updated_at=(
datetime.fromisoformat(row["updated_at"]) if isinstance(row["updated_at"], str) else row["updated_at"]
datetime.fromisoformat(row["updated_at"])
if isinstance(row["updated_at"], str)
else row["updated_at"]
),
)
@@ -1536,10 +1621,14 @@ class LocalizationManager:
min_amount=row["min_amount"],
max_amount=row["max_amount"],
created_at=(
datetime.fromisoformat(row["created_at"]) if isinstance(row["created_at"], str) else row["created_at"]
datetime.fromisoformat(row["created_at"])
if isinstance(row["created_at"], str)
else row["created_at"]
),
updated_at=(
datetime.fromisoformat(row["updated_at"]) if isinstance(row["updated_at"], str) else row["updated_at"]
datetime.fromisoformat(row["updated_at"])
if isinstance(row["updated_at"], str)
else row["updated_at"]
),
)
@@ -1582,15 +1671,21 @@ class LocalizationManager:
region_code=row["region_code"],
data_residency=row["data_residency"],
created_at=(
datetime.fromisoformat(row["created_at"]) if isinstance(row["created_at"], str) else row["created_at"]
datetime.fromisoformat(row["created_at"])
if isinstance(row["created_at"], str)
else row["created_at"]
),
updated_at=(
datetime.fromisoformat(row["updated_at"]) if isinstance(row["updated_at"], str) else row["updated_at"]
datetime.fromisoformat(row["updated_at"])
if isinstance(row["updated_at"], str)
else row["updated_at"]
),
)
_localization_manager = None
def get_localization_manager(db_path: str = "insightflow.db") -> LocalizationManager:
global _localization_manager
if _localization_manager is None: