From 3d62df27cd7673212a18f0dd9e10ea01fe7af8f5 Mon Sep 17 00:00:00 2001 From: konjacpotato Date: Thu, 20 Nov 2025 22:49:12 +0800 Subject: [PATCH] add db migrations --- .dockerignore | 4 +- .env | 11 +- alembic.ini | 147 ++++++++++++++++++ config/settings.py | 3 + llm/deepseek.py | 29 ++++ migrations/README | 1 + migrations/env.py | 81 ++++++++++ migrations/script.py.mako | 28 ++++ .../330873df4e1d_create_table_t_script.py | 44 ++++++ .../versions/4b57e6113ae1_init_tables.py | 39 +++++ models/script.py | 57 +++++++ scheduler/scheduler.py | 2 +- 12 files changed, 440 insertions(+), 6 deletions(-) create mode 100644 alembic.ini create mode 100644 llm/deepseek.py create mode 100644 migrations/README create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/330873df4e1d_create_table_t_script.py create mode 100644 migrations/versions/4b57e6113ae1_init_tables.py create mode 100644 models/script.py diff --git a/.dockerignore b/.dockerignore index 28db922..f115024 100644 --- a/.dockerignore +++ b/.dockerignore @@ -3,4 +3,6 @@ .gitignore Readme.md Dockerfile -docker-compose.yml \ No newline at end of file +docker-compose.yml +alembic.ini +migrations \ No newline at end of file diff --git a/.env b/.env index d1efd13..d63f48e 100644 --- a/.env +++ b/.env @@ -9,8 +9,11 @@ LOG_LEVEL=DEBUG LOG_TYPE=console # 数据库配置 -DB_HOST=localhost -DB_PORT=5432 +DB_HOST=192.168.1.200 +DB_PORT=19732 DB_USER=postgres -DB_PASS=123456 -DB_NAME=mydb \ No newline at end of file +DB_PASS=postgres +DB_NAME=meme + +# 阿里云百炼服务API密钥 +DASHSCOPE_API_KEY=sk-88d6437a6c224ccbb761ec7d994e3b34 \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..c21945d --- /dev/null +++ b/alembic.ini @@ -0,0 +1,147 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +sqlalchemy.url = postgresql+psycopg://postgres:postgres@192.168.1.200:19732/meme + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +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 diff --git a/config/settings.py b/config/settings.py index 3a8b6d9..385c6e2 100644 --- a/config/settings.py +++ b/config/settings.py @@ -24,6 +24,9 @@ class Settings(BaseSettings): DB_PASS: str DB_NAME: str + # 阿里云百炼服务API密钥 + DASHSCOPE_API_KEY: str + class Config: env_file = ".env" env_file_encoding = "utf-8" diff --git a/llm/deepseek.py b/llm/deepseek.py new file mode 100644 index 0000000..1c01678 --- /dev/null +++ b/llm/deepseek.py @@ -0,0 +1,29 @@ +from openai import OpenAI +import os +from config.settings import settings + +client = OpenAI( + # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key="sk-xxx" + api_key=settings.DASHSCOPE_API_KEY, + base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", +) + +messages = [{"role": "user", "content": "你是谁"}] +completion = client.chat.completions.create( + model="deepseek-v3.2-exp", # 您可以按需更换为其它深度思考模型 + messages=messages, + extra_body={"enable_thinking": True}, + stream=True +) +is_answering = False # 是否进入回复阶段 +print("\n" + "=" * 20 + "思考过程" + "=" * 20) +for chunk in completion: + delta = chunk.choices[0].delta + if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None: + if not is_answering: + print(delta.reasoning_content, end="", flush=True) + if hasattr(delta, "content") and delta.content: + if not is_answering: + print("\n" + "=" * 20 + "完整回复" + "=" * 20) + is_answering = True + print(delta.content, end="", flush=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..443c310 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,81 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +from models.base import Base +import models.script # noqa: F401 to ensure the model is imported + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + 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() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,28 @@ +"""${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 +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[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: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/330873df4e1d_create_table_t_script.py b/migrations/versions/330873df4e1d_create_table_t_script.py new file mode 100644 index 0000000..25039e4 --- /dev/null +++ b/migrations/versions/330873df4e1d_create_table_t_script.py @@ -0,0 +1,44 @@ +"""create table t_script + +Revision ID: 330873df4e1d +Revises: 4b57e6113ae1 +Create Date: 2025-11-20 22:15:57.197011 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '330873df4e1d' +down_revision: Union[str, Sequence[str], None] = '4b57e6113ae1' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('t_script', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False, comment='自动递增的唯一内容ID'), + sa.Column('project', sa.String(length=64), nullable=False, comment='项目名称'), + sa.Column('subject', sa.String(length=256), nullable=False, comment='主题'), + sa.Column('content', sa.Text(), nullable=True, comment='内容'), + sa.Column('create_time', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False, comment='创建时间'), + sa.Column('update_time', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False, comment='更新时间'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_t_script_project'), 't_script', ['project'], unique=False) + op.create_index('ux_project_subject', 't_script', ['project', 'subject'], unique=True) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index('ux_project_subject', table_name='t_script') + op.drop_index(op.f('ix_t_script_project'), table_name='t_script') + op.drop_table('t_script') + # ### end Alembic commands ### diff --git a/migrations/versions/4b57e6113ae1_init_tables.py b/migrations/versions/4b57e6113ae1_init_tables.py new file mode 100644 index 0000000..5eb6161 --- /dev/null +++ b/migrations/versions/4b57e6113ae1_init_tables.py @@ -0,0 +1,39 @@ +"""init tables + +Revision ID: 4b57e6113ae1 +Revises: +Create Date: 2025-11-20 22:07:59.558088 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision: str = '4b57e6113ae1' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_apscheduler_jobs_next_run_time'), table_name='apscheduler_jobs') + op.drop_table('apscheduler_jobs') + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('apscheduler_jobs', + sa.Column('id', sa.VARCHAR(length=191), autoincrement=False, nullable=False), + sa.Column('next_run_time', sa.DOUBLE_PRECISION(precision=53), autoincrement=False, nullable=True), + sa.Column('job_state', postgresql.BYTEA(), autoincrement=False, nullable=False), + sa.PrimaryKeyConstraint('id', name=op.f('apscheduler_jobs_pkey')) + ) + op.create_index(op.f('ix_apscheduler_jobs_next_run_time'), 'apscheduler_jobs', ['next_run_time'], unique=False) + # ### end Alembic commands ### diff --git a/models/script.py b/models/script.py new file mode 100644 index 0000000..bd6cfe4 --- /dev/null +++ b/models/script.py @@ -0,0 +1,57 @@ +from datetime import datetime +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import String, Text, Integer, DateTime, Index, func +from models.base import Base + + +class Script(Base): + __tablename__ = "t_script" + + id: Mapped[int] = mapped_column( + Integer, + primary_key=True, + autoincrement=True, + comment="自动递增的唯一内容ID" + ) + + project: Mapped[str] = mapped_column( + String(64), + nullable=False, + index=True, + comment="项目名称" + ) + + subject: Mapped[str] = mapped_column( + String(256), + nullable=False, + comment="主题" + ) + + content: Mapped[str | None] = mapped_column( + Text, + nullable=True, + comment="内容" + ) + + create_time: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + server_default=func.now(), + nullable=False, + comment="创建时间" + ) + + update_time: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + server_default=func.now(), + onupdate=func.now(), + nullable=False, + comment="更新时间" + ) + + # ——可选优化:添加 项目 + 主题 联合唯一索引—— + __table_args__ = ( + Index("ux_project_subject", "project", "subject", unique=True), + ) + + def __repr__(self): + return f"