diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3cf8c6d --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +env +__pycache__ \ No newline at end of file diff --git a/README.md b/README.md index 1ce8e16..3465e4d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,95 @@ -# JieNote_backend -2025春季软件工程课程团队项目JieNote项目后端 +# JieNote Backend + +This is the backend service for JieNote, built with FastAPI. + +## Features +- RESTful API endpoints +- Modular structure for scalability + +## File Structure +- `app/`: Contains the main application code. + - `main.py`: Entry point for the FastAPI application. + - `models/`: Database models and schemas. + - `core/`: Core configurations and settings. + - include database settings + - include JWT settings + - include CORS settings + - …… + - `curd/`: CRUD operations for database interactions. + - `db/`: Database connection and session management. + - `schemas/`: Pydantic schemas for data validation. + - `static/`: Static files (e.g., images, CSS). + - `routers/`: API route definitions. +- `tests/`: Contains test cases for the application. +- `requirements.txt`: List of dependencies. +- `README.md`: Documentation for the project. +- `alembic/`: Database migration scripts and configurations. +- `env/`: Virtual environment (not included in version control). +- `img/`: Images used in the project. + +## Setup +1. Create a virtual environment: ✔ + ```bash + python -m venv env + ``` +2. Activate the virtual environment: + - On Windows: + ```bash + .\env\Scripts\activate + ``` + - On macOS/Linux: + ```bash + source env/bin/activate + ``` +3. Install dependencies: + ```bash + pip install -r requirements.txt + ``` +4. freeze requirements(do before commit !!!): + ```bash + pip freeze > requirements.txt + ``` + +## Database Migration + +1. Install Alembic: ✔ + ```bash + pip install alembic + ``` +2. Initialize Alembic: ✔ + ```bash + alembic init alembic + ``` +3. Configure Alembic: ✔ + + 1. Edit `alembic.ini` to set the database URL. + 2. Edit `alembic/env.py` to set up the target metadata. + ```python + from app.models import Base # Import your models here + target_metadata = Base.metadata + ``` +4. Create a migration script: need to modify the script + ```bash + alembic revision --autogenerate -m "提交信息" + ``` +5. Apply the migration: need to modify the script + ```bash + alembic upgrade head + ``` + + +## Run the Application +```bash +uvicorn app.main:app --reload +``` + +## Folder Structure +- `app/`: Contains the main application code. +- `tests/`: Contains test cases. +- `env/`: Virtual environment (not included in version control). + +## ER Diagram +![ER Diagram](img/er_diagram.jpg) + +## License +MIT License diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..fa56891 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,119 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +# Use forward slashes (/) also on windows to provide an os agnostic path +script_location = alembic + +# 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. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library. +# Any required deps can 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 alembic/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 "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +# version_path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +version_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 + +sqlalchemy.url = mysql+pymysql://root:coders007@47.93.172.156:3306/JieNote + + +[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 exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[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/alembic/README b/alembic/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..41ef15e --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,79 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from app.db.base import Base + +from alembic import context + +# 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/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..480b130 --- /dev/null +++ b/alembic/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, 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/alembic/versions/1bf7c40393d4_definition_of_all_entity_and_relation.py b/alembic/versions/1bf7c40393d4_definition_of_all_entity_and_relation.py new file mode 100644 index 0000000..8c6e9f2 --- /dev/null +++ b/alembic/versions/1bf7c40393d4_definition_of_all_entity_and_relation.py @@ -0,0 +1,77 @@ +"""definition of all entity and relation + +Revision ID: 1bf7c40393d4 +Revises: 56ae02842433 +Create Date: 2025-04-10 10:44:24.487467 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '1bf7c40393d4' +down_revision: Union[str, None] = '56ae02842433' +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('articlenotes', + sa.Column('articleid', sa.Integer(), nullable=True), + sa.Column('noteid', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('noteid') + ) + op.create_index(op.f('ix_articlenotes_noteid'), 'articlenotes', ['noteid'], unique=False) + op.create_table('articlesetarticles', + sa.Column('articlesetid', sa.Integer(), nullable=True), + sa.Column('articleid', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('articleid') + ) + op.create_index(op.f('ix_articlesetarticles_articleid'), 'articlesetarticles', ['articleid'], unique=False) + op.create_table('articletags', + sa.Column('articleid', sa.Integer(), nullable=True), + sa.Column('tagid', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('tagid') + ) + op.create_index(op.f('ix_articletags_tagid'), 'articletags', ['tagid'], unique=False) + op.create_table('grouparticlesets', + sa.Column('groupid', sa.Integer(), nullable=True), + sa.Column('articlesetid', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('articlesetid') + ) + op.create_index(op.f('ix_grouparticlesets_articlesetid'), 'grouparticlesets', ['articlesetid'], unique=False) + op.create_table('userarticlesets', + sa.Column('userid', sa.Integer(), nullable=True), + sa.Column('articlesetid', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('articlesetid') + ) + op.create_index(op.f('ix_userarticlesets_articlesetid'), 'userarticlesets', ['articlesetid'], unique=False) + op.create_table('usergroups', + sa.Column('userid', sa.Integer(), nullable=False), + sa.Column('groupid', sa.Integer(), nullable=False), + sa.Column('isadmin', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('userid', 'groupid') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('usergroups') + op.drop_index(op.f('ix_userarticlesets_articlesetid'), table_name='userarticlesets') + op.drop_table('userarticlesets') + op.drop_index(op.f('ix_grouparticlesets_articlesetid'), table_name='grouparticlesets') + op.drop_table('grouparticlesets') + op.drop_index(op.f('ix_articletags_tagid'), table_name='articletags') + op.drop_table('articletags') + op.drop_index(op.f('ix_articlesetarticles_articleid'), table_name='articlesetarticles') + op.drop_table('articlesetarticles') + op.drop_index(op.f('ix_articlenotes_noteid'), table_name='articlenotes') + op.drop_table('articlenotes') + # ### end Alembic commands ### diff --git a/alembic/versions/56ae02842433_definition_of_all_entity.py b/alembic/versions/56ae02842433_definition_of_all_entity.py new file mode 100644 index 0000000..0cf41da --- /dev/null +++ b/alembic/versions/56ae02842433_definition_of_all_entity.py @@ -0,0 +1,46 @@ +"""definition of all entity + +Revision ID: 56ae02842433 +Revises: c976ca5c1d8f +Create Date: 2025-04-10 00:04:27.588283 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import mysql + +# revision identifiers, used by Alembic. +revision: str = '56ae02842433' +down_revision: Union[str, None] = 'c976ca5c1d8f' +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.add_column('users', sa.Column('email', sa.String(length=30), nullable=False)) + op.add_column('users', sa.Column('username', sa.String(length=30), nullable=False)) + op.drop_index('ix_users_teacher_name', table_name='users') + op.drop_index('ix_users_work_number', table_name='users') + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=False) + op.drop_column('users', 'teacher_name') + op.drop_column('users', 'work_number') + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('users', sa.Column('work_number', mysql.INTEGER(), autoincrement=False, nullable=False)) + op.add_column('users', sa.Column('teacher_name', mysql.VARCHAR(length=20), nullable=False)) + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.create_index('ix_users_work_number', 'users', ['work_number'], unique=False) + op.create_index('ix_users_teacher_name', 'users', ['teacher_name'], unique=False) + op.drop_column('users', 'username') + op.drop_column('users', 'email') + # ### end Alembic commands ### diff --git a/alembic/versions/5c562ce917d3_init.py b/alembic/versions/5c562ce917d3_init.py new file mode 100644 index 0000000..da6aaf7 --- /dev/null +++ b/alembic/versions/5c562ce917d3_init.py @@ -0,0 +1,44 @@ +"""init + +Revision ID: 5c562ce917d3 +Revises: e911f584a9c0 +Create Date: 2025-04-09 10:20:46.223969 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '5c562ce917d3' +down_revision: Union[str, None] = 'e911f584a9c0' +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('users', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('work_number', sa.Integer(), nullable=False), + sa.Column('hash_password', sa.String(length=60), nullable=False), + sa.Column('teacher_name', sa.String(length=20), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_teacher_name'), 'users', ['teacher_name'], unique=False) + op.create_index(op.f('ix_users_work_number'), 'users', ['work_number'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_users_work_number'), table_name='users') + op.drop_index(op.f('ix_users_teacher_name'), table_name='users') + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_table('users') + # ### end Alembic commands ### diff --git "a/alembic/versions/5dc79cf05715_\346\267\273\345\212\240\346\225\260\346\215\256\345\272\223\345\256\236\344\275\223\345\205\263\347\263\273\345\256\232\344\271\211.py" "b/alembic/versions/5dc79cf05715_\346\267\273\345\212\240\346\225\260\346\215\256\345\272\223\345\256\236\344\275\223\345\205\263\347\263\273\345\256\232\344\271\211.py" new file mode 100644 index 0000000..cacd6d0 --- /dev/null +++ "b/alembic/versions/5dc79cf05715_\346\267\273\345\212\240\346\225\260\346\215\256\345\272\223\345\256\236\344\275\223\345\205\263\347\263\273\345\256\232\344\271\211.py" @@ -0,0 +1,141 @@ +"""添加数据库实体关系定义 + +Revision ID: 5dc79cf05715 +Revises: 1bf7c40393d4 +Create Date: 2025-04-11 20:59:07.250741 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import mysql + +# revision identifiers, used by Alembic. +revision: str = '5dc79cf05715' +down_revision: Union[str, None] = '1bf7c40393d4' +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('folders', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(length=30), nullable=True), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('groups_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['groups_id'], ['groups.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_folders_id'), 'folders', ['id'], unique=False) + op.create_table('user_group', + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=False), + sa.Column('is_admin', sa.Boolean(), nullable=True), + sa.ForeignKeyConstraint(['group_id'], ['groups.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('user_id', 'group_id') + ) + op.drop_index('ix_articlesetarticles_articleid', table_name='articlesetarticles') + op.drop_table('articlesetarticles') + op.drop_index('ix_articletags_tagid', table_name='articletags') + op.drop_table('articletags') + op.drop_index('ix_userarticlesets_articlesetid', table_name='userarticlesets') + op.drop_table('userarticlesets') + op.drop_index('ix_grouparticlesets_articlesetid', table_name='grouparticlesets') + op.drop_table('grouparticlesets') + op.drop_index('ix_articlesets_id', table_name='articlesets') + op.drop_table('articlesets') + op.drop_index('ix_articlenotes_noteid', table_name='articlenotes') + op.drop_table('articlenotes') + op.drop_table('usergroups') + op.add_column('articles', sa.Column('folder_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'articles', 'folders', ['folder_id'], ['id']) + op.add_column('notes', sa.Column('article_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'notes', 'articles', ['article_id'], ['id']) + op.add_column('tags', sa.Column('article_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'tags', 'articles', ['article_id'], ['id']) + op.add_column('users', sa.Column('avatar', sa.String(length=100), nullable=True)) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('users', 'avatar') + op.drop_constraint(None, 'tags', type_='foreignkey') + op.drop_column('tags', 'article_id') + op.drop_constraint(None, 'notes', type_='foreignkey') + op.drop_column('notes', 'article_id') + op.drop_constraint(None, 'articles', type_='foreignkey') + op.drop_column('articles', 'folder_id') + op.create_table('usergroups', + sa.Column('userid', mysql.INTEGER(), autoincrement=False, nullable=False), + sa.Column('groupid', mysql.INTEGER(), autoincrement=False, nullable=False), + sa.Column('isadmin', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('userid', 'groupid'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_table('articlenotes', + sa.Column('articleid', mysql.INTEGER(), autoincrement=False, nullable=True), + sa.Column('noteid', mysql.INTEGER(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('noteid'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_index('ix_articlenotes_noteid', 'articlenotes', ['noteid'], unique=False) + op.create_table('articlesets', + sa.Column('id', mysql.INTEGER(), autoincrement=True, nullable=False), + sa.Column('name', mysql.VARCHAR(length=30), nullable=True), + sa.PrimaryKeyConstraint('id'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_index('ix_articlesets_id', 'articlesets', ['id'], unique=False) + op.create_table('grouparticlesets', + sa.Column('groupid', mysql.INTEGER(), autoincrement=False, nullable=True), + sa.Column('articlesetid', mysql.INTEGER(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('articlesetid'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_index('ix_grouparticlesets_articlesetid', 'grouparticlesets', ['articlesetid'], unique=False) + op.create_table('userarticlesets', + sa.Column('userid', mysql.INTEGER(), autoincrement=False, nullable=True), + sa.Column('articlesetid', mysql.INTEGER(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('articlesetid'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_index('ix_userarticlesets_articlesetid', 'userarticlesets', ['articlesetid'], unique=False) + op.create_table('articletags', + sa.Column('articleid', mysql.INTEGER(), autoincrement=False, nullable=True), + sa.Column('tagid', mysql.INTEGER(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('tagid'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_index('ix_articletags_tagid', 'articletags', ['tagid'], unique=False) + op.create_table('articlesetarticles', + sa.Column('articlesetid', mysql.INTEGER(), autoincrement=False, nullable=True), + sa.Column('articleid', mysql.INTEGER(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('articleid'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_index('ix_articlesetarticles_articleid', 'articlesetarticles', ['articleid'], unique=False) + op.drop_table('user_group') + op.drop_index(op.f('ix_folders_id'), table_name='folders') + op.drop_table('folders') + # ### end Alembic commands ### diff --git "a/alembic/versions/b7940480e6e6_\346\267\273\345\212\240\346\225\260\346\215\256\345\272\223\345\256\236\344\275\223\345\205\263\347\263\273\345\256\232\344\271\211.py" "b/alembic/versions/b7940480e6e6_\346\267\273\345\212\240\346\225\260\346\215\256\345\272\223\345\256\236\344\275\223\345\205\263\347\263\273\345\256\232\344\271\211.py" new file mode 100644 index 0000000..1b082cb --- /dev/null +++ "b/alembic/versions/b7940480e6e6_\346\267\273\345\212\240\346\225\260\346\215\256\345\272\223\345\256\236\344\275\223\345\205\263\347\263\273\345\256\232\344\271\211.py" @@ -0,0 +1,40 @@ +"""添加数据库实体关系定义 + +Revision ID: b7940480e6e6 +Revises: 5dc79cf05715 +Create Date: 2025-04-11 21:10:47.613089 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import mysql + +# revision identifiers, used by Alembic. +revision: str = 'b7940480e6e6' +down_revision: Union[str, None] = '5dc79cf05715' +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.add_column('folders', sa.Column('group_id', sa.Integer(), nullable=True)) + op.create_unique_constraint('uq_user_group_folder', 'folders', ['user_id', 'group_id']) + op.drop_constraint('folders_ibfk_1', 'folders', type_='foreignkey') + op.create_foreign_key(None, 'folders', 'groups', ['group_id'], ['id']) + op.drop_column('folders', 'groups_id') + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('folders', sa.Column('groups_id', mysql.INTEGER(), autoincrement=False, nullable=True)) + op.drop_constraint(None, 'folders', type_='foreignkey') + op.create_foreign_key('folders_ibfk_1', 'folders', 'groups', ['groups_id'], ['id']) + op.drop_constraint('uq_user_group_folder', 'folders', type_='unique') + op.drop_column('folders', 'group_id') + # ### end Alembic commands ### diff --git "a/alembic/versions/c976ca5c1d8f_\344\275\277\347\224\250\350\277\234\347\250\213\346\225\260\346\215\256\345\272\223.py" "b/alembic/versions/c976ca5c1d8f_\344\275\277\347\224\250\350\277\234\347\250\213\346\225\260\346\215\256\345\272\223.py" new file mode 100644 index 0000000..f27967b --- /dev/null +++ "b/alembic/versions/c976ca5c1d8f_\344\275\277\347\224\250\350\277\234\347\250\213\346\225\260\346\215\256\345\272\223.py" @@ -0,0 +1,44 @@ +"""使用远程数据库 + +Revision ID: c976ca5c1d8f +Revises: 5c562ce917d3 +Create Date: 2025-04-09 21:33:43.133516 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'c976ca5c1d8f' +down_revision: Union[str, None] = '5c562ce917d3' +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('users', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('work_number', sa.Integer(), nullable=False), + sa.Column('hash_password', sa.String(length=60), nullable=False), + sa.Column('teacher_name', sa.String(length=20), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_teacher_name'), 'users', ['teacher_name'], unique=False) + op.create_index(op.f('ix_users_work_number'), 'users', ['work_number'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_users_work_number'), table_name='users') + op.drop_index(op.f('ix_users_teacher_name'), table_name='users') + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_table('users') + # ### end Alembic commands ### diff --git a/alembic/versions/e911f584a9c0_init.py b/alembic/versions/e911f584a9c0_init.py new file mode 100644 index 0000000..9114c37 --- /dev/null +++ b/alembic/versions/e911f584a9c0_init.py @@ -0,0 +1,42 @@ +"""init + +Revision ID: e911f584a9c0 +Revises: +Create Date: 2025-04-09 10:17:37.889061 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import mysql + +# revision identifiers, used by Alembic. +revision: str = 'e911f584a9c0' +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: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index('ix_examples_id', table_name='examples') + op.drop_table('examples') + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('examples', + sa.Column('id', mysql.INTEGER(), autoincrement=True, nullable=False), + sa.Column('name', mysql.VARCHAR(length=50), nullable=False), + sa.Column('description', mysql.VARCHAR(length=255), nullable=True), + sa.PrimaryKeyConstraint('id'), + mysql_collate='utf8mb4_0900_ai_ci', + mysql_default_charset='utf8mb4', + mysql_engine='InnoDB' + ) + op.create_index('ix_examples_id', 'examples', ['id'], unique=False) + # ### end Alembic commands ### diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..68818c4 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,6 @@ +class Settings: + PROJECT_NAME: str = "JieNote Backend" + VERSION: str = "1.0.0" + SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:coders007@47.93.172.156:3306/JieNote" # 替换为实际的用户名、密码和数据库名称 + +settings = Settings() \ No newline at end of file diff --git a/app/curd/__init__.py b/app/curd/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..d885a92 --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,2 @@ +from app.db.base_class import Base # 导入创建的base类 +from app.models.model import User \ No newline at end of file diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..d692f60 --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,13 @@ +from typing import Any + +from sqlalchemy.ext.declarative import as_declarative, declared_attr + + +@as_declarative() +class Base: + id: Any + __name__: str + # Generate __tablename__ automatically + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..5801d8e --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,7 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True) #连接mysql +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..e8f2e2f --- /dev/null +++ b/app/main.py @@ -0,0 +1,11 @@ +from fastapi import FastAPI + +app = FastAPI() + +@app.get("/") +def read_root(): + return {"Hello": "World"} + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: str = None): + return {"item_id": item_id, "q": q} \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..026426c --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +from .model import User \ No newline at end of file diff --git a/app/models/base.py b/app/models/base.py new file mode 100644 index 0000000..860e542 --- /dev/null +++ b/app/models/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() diff --git a/app/models/model.py b/app/models/model.py new file mode 100644 index 0000000..0f2959d --- /dev/null +++ b/app/models/model.py @@ -0,0 +1,76 @@ +from sqlalchemy import Column, Integer, String, Boolean, Table, ForeignKey, UniqueConstraint +from sqlalchemy.orm import relationship + +from app.db.base_class import Base + +# 多对多关系表 +user_group = Table( + 'user_group', Base.metadata, + Column('user_id', Integer, ForeignKey('users.id'), primary_key=True), + Column('group_id', Integer, ForeignKey('groups.id'), primary_key=True), + Column('is_admin', Boolean, default=False) # 是否是管理员 +) + +class User(Base): + __tablename__ = 'users' + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + email = Column(String(30), index=True, nullable=False, unique=True) + username = Column(String(30), index=True, nullable=False) + hash_password = Column(String(60), nullable=False) + avatar = Column(String(100), nullable=True) # 头像的url + groups = relationship('Group', secondary=user_group, back_populates='users') + +class Group(Base): + __tablename__ = 'groups' + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + leader = Column(Integer) # the id of the leader + users = relationship('User', secondary=user_group, back_populates='groups') + +class Folder(Base): # 文件夹 + __tablename__ = 'folders' + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + name = Column(String(30)) + user_id = Column(Integer, ForeignKey('users.id')) + group_id = Column(Integer, ForeignKey('groups.id')) + user = relationship('User', back_populates='folders') + group = relationship('Group', back_populates='folders') + + __table_args__ = ( + UniqueConstraint('user_id', 'group_id', name='uq_user_group_folder'), + ) + +class Article(Base): + __tablename__ = 'articles' + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + name = Column(String(30)) + folder_id = Column(Integer, ForeignKey('folders.id')) + folder = relationship('Folder', back_populates='articles') + +class Note(Base): + __tablename__ = 'notes' + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + name = Column(String(30)) + article_id = Column(Integer, ForeignKey('articles.id')) + article = relationship('Article', back_populates='notes') + +class Tag(Base): + __tablename__ = 'tags' + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + content = Column(String(30)) + article_id = Column(Integer, ForeignKey('articles.id')) + article = relationship('Article', back_populates='tags') + +# 添加反向关系 +User.folders = relationship('Folder', back_populates='users') +Group.folders = relationship('Folder', back_populates='groups') +Folder.articles = relationship('Article', back_populates='folders') +Article.notes = relationship('Note', back_populates='articles') +Article.tags = relationship('Tag', back_populates='articles') + + diff --git a/app/routers/__init__.py b/app/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/static/__init__.py b/app/static/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/img/er_diagram.jpg b/img/er_diagram.jpg new file mode 100644 index 0000000..fd353ee Binary files /dev/null and b/img/er_diagram.jpg differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..84b9803 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ +alembic==1.15.2 +annotated-types==0.7.0 +anyio==4.9.0 +click==8.1.8 +colorama==0.4.6 +dotenv==0.9.9 +fastapi==0.115.12 +greenlet==3.1.1 +h11==0.14.0 +idna==3.10 +Mako==1.3.9 +MarkupSafe==3.0.2 +passlib==1.7.4 +pydantic==2.11.2 +pydantic_core==2.33.1 +PyMySQL==1.1.1 +python-dotenv==1.1.0 +sniffio==1.3.1 +SQLAlchemy==2.0.40 +starlette==0.46.1 +typing-inspection==0.4.0 +typing_extensions==4.13.1 +uvicorn==0.34.0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29