CaiYouHui后端fastapi实现

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # app/schemas/user.py
  2. from pydantic import BaseModel, EmailStr, Field, validator
  3. from typing import Optional
  4. from datetime import datetime, timezone, timedelta
  5. class UserBase(BaseModel):
  6. """用户基础模型"""
  7. username: str = Field(..., min_length=3, max_length=50, example="john_doe")
  8. email: EmailStr = Field(..., example="user@example.com")
  9. full_name: Optional[str] = Field(None, example="John Doe")
  10. class UserCreate(UserBase):
  11. """创建用户模型"""
  12. password: str = Field(..., min_length=6, example="password123")
  13. password_confirm: str = Field(..., example="password123")
  14. @validator('password_confirm')
  15. def passwords_match(cls, v, values, **kwargs):
  16. if 'password' in values and v != values['password']:
  17. raise ValueError('密码不匹配')
  18. return v
  19. class UserLogin(BaseModel):
  20. """用户登录模型"""
  21. username: str = Field(..., example="john_doe")
  22. password: str = Field(..., example="password123")
  23. class UserUpdate(BaseModel):
  24. """更新用户模型"""
  25. full_name: Optional[str] = None
  26. email: Optional[EmailStr] = None
  27. class UserResponse(UserBase):
  28. """用户响应模型"""
  29. id: int
  30. is_active: bool = True
  31. is_verified: bool = False
  32. created_at: datetime
  33. class Config:
  34. from_attributes = True
  35. class UserProfile(UserResponse):
  36. """用户详情模型"""
  37. last_login: Optional[datetime] = None
  38. avatar: Optional[str] = None
  39. class PasswordChange(BaseModel):
  40. """修改密码模型"""
  41. current_password: str
  42. new_password: str = Field(..., min_length=6)
  43. confirm_password: str
  44. @validator('confirm_password')
  45. def passwords_match(cls, v, values, **kwargs):
  46. if 'new_password' in values and v != values['new_password']:
  47. raise ValueError('新密码不匹配')
  48. return v
  49. __all__ = [
  50. "UserBase",
  51. "UserCreate",
  52. "UserLogin",
  53. "UserUpdate",
  54. "UserResponse",
  55. "UserProfile",
  56. "PasswordChange"
  57. ]