chore: bootstrap storage migrations and frontend
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
sqlalchemy.url = mysql+pymysql://root:root123@localhost:3306/ai_doc_template?charset=utf8mb4
|
||||
|
||||
[post_write_hooks]
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
@@ -0,0 +1,62 @@
|
||||
from logging.config import fileConfig
|
||||
import os
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from app.database import Base
|
||||
from app.models.block_config import BlockConfig
|
||||
from app.models.template import Template
|
||||
from app.models.template_block import TemplateBlock
|
||||
|
||||
|
||||
config = context.config
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def get_database_url() -> str:
|
||||
db_host = os.getenv("DB_HOST", "localhost")
|
||||
db_port = os.getenv("DB_PORT", "3306")
|
||||
db_user = os.getenv("DB_USER", "root")
|
||||
db_pass = os.getenv("DB_PASS", "root123")
|
||||
db_name = os.getenv("DB_NAME", "ai_doc_template")
|
||||
return f"mysql+pymysql://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}?charset=utf8mb4"
|
||||
|
||||
|
||||
config.set_main_option("sqlalchemy.url", get_database_url())
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=get_database_url(),
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,74 @@
|
||||
"""create template tables
|
||||
|
||||
Revision ID: 20260701_0001
|
||||
Revises:
|
||||
Create Date: 2026-07-01 12:00:00
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = "20260701_0001"
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"template",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("name", sa.String(length=200), nullable=False, comment="模板名称"),
|
||||
sa.Column("type", sa.String(length=50), nullable=True, comment="报告类/公文类/总结类/合同类"),
|
||||
sa.Column("version", sa.String(length=20), nullable=True, comment="版本号"),
|
||||
sa.Column("original_file_path", sa.String(length=500), nullable=False, comment="原始 Word 文件路径"),
|
||||
sa.Column("status", sa.Integer(), nullable=True, comment="1=启用 0=停用"),
|
||||
sa.Column("created_by", sa.String(length=50), nullable=True, comment="创建人"),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_table(
|
||||
"template_block",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("template_id", sa.Integer(), nullable=False, comment="所属模板"),
|
||||
sa.Column("block_id", sa.String(length=50), nullable=False, comment="唯一标识 block_001"),
|
||||
sa.Column("parent_block_id", sa.String(length=50), nullable=True, comment="父级 block_id"),
|
||||
sa.Column("block_type", sa.String(length=20), nullable=False, comment="title/heading/paragraph/table"),
|
||||
sa.Column("block_name", sa.String(length=200), nullable=True, comment="区域名称"),
|
||||
sa.Column("text_preview", sa.String(length=500), nullable=True, comment="文本预览"),
|
||||
sa.Column("level", sa.Integer(), nullable=True, comment="0=文档标题 1=一级 2=二级"),
|
||||
sa.Column("sort_order", sa.Integer(), nullable=True, comment="排序号"),
|
||||
sa.Column("table_rows", sa.Integer(), nullable=True, comment="表格行数"),
|
||||
sa.Column("table_cols", sa.Integer(), nullable=True, comment="表格列数"),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(["template_id"], ["template.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_table(
|
||||
"block_config",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("template_id", sa.Integer(), nullable=False),
|
||||
sa.Column("block_id", sa.String(length=50), nullable=False),
|
||||
sa.Column("region_name", sa.String(length=200), nullable=True, comment="区域名称"),
|
||||
sa.Column("region_type", sa.String(length=30), nullable=True, comment="ai_generate/manual/fixed/table"),
|
||||
sa.Column("data_sources", sa.Text(), nullable=True, comment="数据来源 JSON 数组"),
|
||||
sa.Column("prompt", sa.Text(), nullable=True, comment="提示词"),
|
||||
sa.Column("output_format", sa.String(length=30), nullable=True, comment="输出格式"),
|
||||
sa.Column("need_review", sa.Integer(), nullable=True, comment="1=需要审核"),
|
||||
sa.Column("remark", sa.Text(), nullable=True, comment="备注"),
|
||||
sa.Column("enabled", sa.Integer(), nullable=True, comment="1=启用"),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(["template_id"], ["template.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("template_id", "block_id", name="uq_template_block"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("block_config")
|
||||
op.drop_table("template_block")
|
||||
op.drop_table("template")
|
||||
@@ -1,28 +1,108 @@
|
||||
import os
|
||||
from io import BytesIO
|
||||
|
||||
# 先实现本地文件存储,MinIO 作为选项
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
|
||||
STORAGE_BASE = os.getenv("LOCAL_STORAGE_PATH", "./data/files")
|
||||
MINIO_ENDPOINT = os.getenv("MINIO_ENDPOINT", "localhost:9000")
|
||||
MINIO_ACCESS_KEY = os.getenv("MINIO_ACCESS_KEY", "minioadmin")
|
||||
MINIO_SECRET_KEY = os.getenv("MINIO_SECRET_KEY", "minioadmin")
|
||||
MINIO_SECURE = os.getenv("MINIO_SECURE", "false").lower() == "true"
|
||||
|
||||
|
||||
def save_file(content: bytes, file_path: str) -> str:
|
||||
"""保存文件到本地存储,返回完整路径"""
|
||||
full_path = os.path.join(STORAGE_BASE, file_path)
|
||||
def _local_path(bucket: str, file_path: str) -> str:
|
||||
return os.path.join(STORAGE_BASE, bucket, file_path)
|
||||
|
||||
|
||||
def _save_local(bucket: str, file_path: str, content: bytes) -> str:
|
||||
full_path = _local_path(bucket, file_path)
|
||||
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
||||
with open(full_path, "wb") as f:
|
||||
f.write(content)
|
||||
return full_path
|
||||
|
||||
|
||||
def read_file(file_path: str) -> bytes:
|
||||
"""读取文件内容"""
|
||||
full_path = os.path.join(STORAGE_BASE, file_path)
|
||||
with open(full_path, "rb") as f:
|
||||
def _read_local(bucket: str, file_path: str) -> bytes:
|
||||
with open(_local_path(bucket, file_path), "rb") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def get_minio_client() -> Minio:
|
||||
return Minio(
|
||||
MINIO_ENDPOINT,
|
||||
access_key=MINIO_ACCESS_KEY,
|
||||
secret_key=MINIO_SECRET_KEY,
|
||||
secure=MINIO_SECURE,
|
||||
)
|
||||
|
||||
|
||||
def ensure_bucket(bucket_name: str) -> bool:
|
||||
"""确保 bucket 存在;MinIO 不可用时返回 False 表示使用本地降级。"""
|
||||
try:
|
||||
client = get_minio_client()
|
||||
if not client.bucket_exists(bucket_name):
|
||||
client.make_bucket(bucket_name)
|
||||
return True
|
||||
except S3Error:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def upload_file(bucket: str, file_path: str, content: bytes) -> str:
|
||||
"""上传文件到 MinIO;连接失败时降级保存到本地文件系统。"""
|
||||
if ensure_bucket(bucket):
|
||||
try:
|
||||
client = get_minio_client()
|
||||
client.put_object(
|
||||
bucket,
|
||||
file_path,
|
||||
BytesIO(content),
|
||||
length=len(content),
|
||||
content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
)
|
||||
return f"minio://{bucket}/{file_path}"
|
||||
except S3Error:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return _save_local(bucket, file_path, content)
|
||||
|
||||
|
||||
def download_file(bucket: str, file_path: str) -> bytes:
|
||||
"""从 MinIO 下载文件;读取失败时尝试本地降级路径。"""
|
||||
if ensure_bucket(bucket):
|
||||
try:
|
||||
client = get_minio_client()
|
||||
response = client.get_object(bucket, file_path)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
except S3Error:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return _read_local(bucket, file_path)
|
||||
|
||||
|
||||
def save_file(content: bytes, file_path: str) -> str:
|
||||
"""兼容旧调用:保存到默认 templates bucket。"""
|
||||
return upload_file("templates", file_path, content)
|
||||
|
||||
|
||||
def read_file(file_path: str) -> bytes:
|
||||
"""兼容旧调用:从默认 templates bucket 读取。"""
|
||||
return download_file("templates", file_path)
|
||||
|
||||
|
||||
def delete_file(file_path: str):
|
||||
"""删除文件"""
|
||||
full_path = os.path.join(STORAGE_BASE, file_path)
|
||||
"""删除本地降级文件。MinIO 对象删除后续按接口需要再补充。"""
|
||||
full_path = _local_path("templates", file_path)
|
||||
if os.path.exists(full_path):
|
||||
os.remove(full_path)
|
||||
|
||||
Reference in New Issue
Block a user