style(backend): apply ruff format

This commit is contained in:
2026-05-03 18:14:23 +08:00
parent 738217d9c9
commit ab68f019c5
41 changed files with 960 additions and 970 deletions
+2 -1
View File
@@ -5,6 +5,7 @@
使用方法:
uv run python apps/backend/scripts/create_admin.py
"""
import sys
from pathlib import Path
@@ -51,7 +52,7 @@ def create_admin_user(alias: str):
# 升级为管理员
response = input("\n是否将该用户升级为管理员?(y/n): ")
if response.lower() == 'y':
if response.lower() == "y":
existing_user.role = "admin"
existing_user.is_approved = True # 确保已审批
db.commit()
@@ -34,33 +34,31 @@ def migrate():
columns = [row[1] for row in result]
# 添加 failed_login_attempts 字段
if 'failed_login_attempts' not in columns:
if "failed_login_attempts" not in columns:
logger.info("添加 failed_login_attempts 字段...")
conn.execute(text(
"ALTER TABLE users ADD COLUMN failed_login_attempts INTEGER DEFAULT 0 NOT NULL"
))
conn.execute(
text(
"ALTER TABLE users ADD COLUMN failed_login_attempts INTEGER DEFAULT 0 NOT NULL"
)
)
conn.commit()
logger.info("✓ failed_login_attempts 字段添加成功")
else:
logger.info("✓ failed_login_attempts 字段已存在,跳过")
# 添加 locked_until 字段
if 'locked_until' not in columns:
if "locked_until" not in columns:
logger.info("添加 locked_until 字段...")
conn.execute(text(
"ALTER TABLE users ADD COLUMN locked_until DATETIME"
))
conn.execute(text("ALTER TABLE users ADD COLUMN locked_until DATETIME"))
conn.commit()
logger.info("✓ locked_until 字段添加成功")
else:
logger.info("✓ locked_until 字段已存在,跳过")
# 添加 last_failed_login 字段
if 'last_failed_login' not in columns:
if "last_failed_login" not in columns:
logger.info("添加 last_failed_login 字段...")
conn.execute(text(
"ALTER TABLE users ADD COLUMN last_failed_login DATETIME"
))
conn.execute(text("ALTER TABLE users ADD COLUMN last_failed_login DATETIME"))
conn.commit()
logger.info("✓ last_failed_login 字段添加成功")
else:
+13 -11
View File
@@ -1,6 +1,7 @@
"""
测试新的异常处理系统
"""
import sys
from pathlib import Path
@@ -16,6 +17,7 @@ from backend.exceptions import (
)
from backend.schemas.response import ErrorResponse, ErrorDetail
def test_exceptions():
"""测试自定义异常"""
print("=" * 60)
@@ -32,7 +34,9 @@ def test_exceptions():
try:
raise AuthenticationError("Token已过期")
except AuthenticationError as e:
print(f"✅ AuthenticationError: {e.message} (状态码: {e.status_code}, 代码: {e.error_code})")
print(
f"✅ AuthenticationError: {e.message} (状态码: {e.status_code}, 代码: {e.error_code})"
)
# 测试 AuthorizationError
try:
@@ -44,7 +48,9 @@ def test_exceptions():
try:
raise ResourceNotFoundError("用户不存在")
except ResourceNotFoundError as e:
print(f"✅ ResourceNotFoundError: {e.message} (状态码: {e.status_code}, 代码: {e.error_code})")
print(
f"✅ ResourceNotFoundError: {e.message} (状态码: {e.status_code}, 代码: {e.error_code})"
)
# 测试 BusinessLogicError
try:
@@ -61,11 +67,7 @@ def test_response_schemas():
# 测试 ErrorResponse
error_response = ErrorResponse(
error=ErrorDetail(
code="VALIDATION_ERROR",
message="邮箱格式不正确",
field="email"
)
error=ErrorDetail(code="VALIDATION_ERROR", message="邮箱格式不正确", field="email")
)
response_dict = error_response.model_dump()
@@ -90,18 +92,18 @@ def check_old_exception_patterns():
patterns = {
"HTTPException with detail": r'raise HTTPException.*detail=f?".*{',
"except Exception": r'except Exception as',
"except Exception": r"except Exception as",
}
results = {}
for pattern_name, pattern in patterns.items():
results[pattern_name] = []
for root, dirs, files in os.walk(APPS_DIR / 'backend' / 'api'):
for root, dirs, files in os.walk(APPS_DIR / "backend" / "api"):
for file in files:
if file.endswith('.py'):
if file.endswith(".py"):
filepath = os.path.join(root, file)
with open(filepath, 'r', encoding='utf-8') as f:
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
matches = re.findall(pattern, content, re.MULTILINE)
if matches: