operations_project/apps/accounts/services/utils.py
2025-05-07 18:01:48 +08:00

78 lines
1.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import uuid
from rest_framework.response import Response
from rest_framework import status
def convert_to_uuid(pk_str):
"""
将字符串转换为UUID格式
Args:
pk_str: 字符串形式的UUID
Returns:
转换后的UUID对象或None
Raises:
ValueError: 如果字符串不是有效的UUID格式
"""
if isinstance(pk_str, uuid.UUID):
return pk_str
pk_str = pk_str.strip()
# 处理没有连字符的UUID
if '-' not in pk_str and len(pk_str) == 32:
pk_with_hyphens = f"{pk_str[0:8]}-{pk_str[8:12]}-{pk_str[12:16]}-{pk_str[16:20]}-{pk_str[20:]}"
return uuid.UUID(pk_with_hyphens)
else:
return uuid.UUID(pk_str)
def format_user_response(user, include_is_active=False):
"""
格式化用户信息响应
Args:
user: 用户对象
include_is_active: 是否包含is_active字段
Returns:
格式化后的用户信息字典
"""
response = {
"id": str(user.id),
"username": user.username,
"email": user.email,
"name": user.name,
"role": user.role,
"department": user.department,
"group": user.group
}
if include_is_active:
response["is_active"] = user.is_active
return response
def validate_uuid_param(pk_str):
"""
验证并转换UUID参数返回标准的错误响应或UUID对象
Args:
pk_str: 字符串形式的UUID
Returns:
元组 (uuid_obj, None) 或 (None, error_response)
"""
try:
uuid_obj = convert_to_uuid(pk_str)
return uuid_obj, None
except ValueError:
error_response = Response({
"code": 400,
"message": f"无效的用户ID格式: {pk_str}。用户ID应为有效的UUID格式。",
"data": None
}, status=status.HTTP_400_BAD_REQUEST)
return None, error_response