| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- """
- 平台API Key数据ORM定义
- 定义平台API Key的数据库表结构,用于存储用户创建的API密钥信息
- 用于调用本平台开放API的密钥管理
- """
- from datetime import datetime
- from sqlalchemy import Column, Integer, String, DateTime, Index, ForeignKey
- from sqlalchemy.sql import func
- from sqlalchemy.orm import relationship
- from app.database import Base
- class PlatformApiKey(Base):
- """
- 平台API Key ORM类
- 存储用户创建的平台API密钥信息
- - API Key使用SHA256哈希存储,仅在创建时返回完整密钥
- - 每个用户最多可创建5个有效API Key
- - 支持启用/禁用状态管理
- """
- __tablename__ = "platform_api_key"
- # 主键ID
- id = Column(
- Integer,
- primary_key=True,
- autoincrement=True,
- comment="主键ID"
- )
- # 用户ID(外键关联users表)
- user_id = Column(
- String(50),
- ForeignKey("aigcspace.users.id", ondelete="CASCADE"),
- nullable=False,
- comment="用户ID"
- )
- # API Key(SHA256哈希存储)
- api_key = Column(
- String(100),
- nullable=False,
- comment="API Key(SHA256哈希)"
- )
- # API Key前缀(用于显示,如sk-aigc-xxxx...xxxx)
- api_key_prefix = Column(
- String(20),
- nullable=False,
- comment="API Key前缀用于显示"
- )
- # 备注名称
- name = Column(
- String(100),
- nullable=True,
- comment="备注名称"
- )
- # 状态:active/disabled
- status = Column(
- String(20),
- nullable=False,
- default="active",
- comment="状态:active/disabled"
- )
- # 密钥类型:public(公钥,访问云端模型)/ local(本地私钥,访问本地模型)
- key_type = Column(
- String(20),
- nullable=False,
- default="public",
- comment="密钥类型:public/local"
- )
- # 最后使用时间
- last_used_at = Column(
- DateTime,
- nullable=True,
- comment="最后使用时间"
- )
- # 创建时间(自动设置)
- created_at = Column(
- DateTime,
- nullable=False,
- server_default=func.now(),
- comment="创建时间"
- )
- # 更新时间(自动更新)
- updated_at = Column(
- DateTime,
- nullable=False,
- server_default=func.now(),
- onupdate=func.now(),
- comment="更新时间"
- )
- # 表级配置
- __table_args__ = (
- Index('idx_platform_api_key_user_id', 'user_id'),
- Index('idx_platform_api_key_api_key', 'api_key'),
- Index('idx_platform_api_key_status', 'status'),
- {'schema': 'aigcspace', 'comment': '平台API Key表'}
- )
- def __repr__(self):
- return f"<PlatformApiKey(id={self.id}, user_id='{self.user_id}', prefix='{self.api_key_prefix}', status='{self.status}')>"
|