From aaf0d20c6542fe85b5c4521b2c8869b30d02bf1c Mon Sep 17 00:00:00 2001 From: DmitryGantimurov Date: Sun, 30 Jul 2023 12:35:08 +0300 Subject: [PATCH] UserDatabase->User, ForeignKey added --- back/db_manipultations.py | 40 --------- back/delete_db.py | 5 ++ back/main.py | 45 +++++----- back/models.py | 4 +- back/utils.py | 11 ++- migrations/env.py | 5 +- migrations/versions/0006eca30e2c_first.py | 28 ------- ...foreignkey_added_to_announcement_model.py} | 83 ++++++++++++------- .../18001c2231e3_poems_table_added.py | 34 -------- ...47_new_colomn_poem_name_added_to_poems_.py | 28 ------- ...a5_new_colomn_poem_name_added_to_poems_.py | 28 ------- ...odd_fields_in_user_model_removed_links_.py | 30 ------- ...new_colomn_disabled_added_to_user_table.py | 28 ------- 13 files changed, 92 insertions(+), 277 deletions(-) delete mode 100644 back/db_manipultations.py create mode 100644 back/delete_db.py delete mode 100644 migrations/versions/0006eca30e2c_first.py rename migrations/versions/{33c5716276b5_try_to_make_alembic_see_models.py => 00529d20660b_foreignkey_added_to_announcement_model.py} (51%) delete mode 100644 migrations/versions/18001c2231e3_poems_table_added.py delete mode 100644 migrations/versions/1cf412fb7547_new_colomn_poem_name_added_to_poems_.py delete mode 100644 migrations/versions/57c3df575fa5_new_colomn_poem_name_added_to_poems_.py delete mode 100644 migrations/versions/6ef6877e89ff_odd_fields_in_user_model_removed_links_.py delete mode 100644 migrations/versions/daffcb4729af_new_colomn_disabled_added_to_user_table.py diff --git a/back/db_manipultations.py b/back/db_manipultations.py deleted file mode 100644 index 7ebbc33..0000000 --- a/back/db_manipultations.py +++ /dev/null @@ -1,40 +0,0 @@ -from .db import engine -from .models import Announcement, UserDatabase, Trashbox, Base - - -Base.metadata.create_all(bind=engine) - -db = SessionLocal() - -# Пробный чувак -tom = UserDatabase(name="Tom", phone="89999999", email="pupka", password="1234", surname="Smith") -# db.add(tom) # добавляем в бд -# db.commit() # сохраняем изменения -# db.refresh(tom) # обновляем состояние объекта - -# Пробное объявление 1 -a1 = Announcement(user_id=1, category="cat", best_by="201223", address="abd", longtitude=23, latitude=22, -description="abv", src="111", metro="Lesnaya", booked_by=2) -# Пробное объявление 2 -a2 = Announcement(user_id=1, category="dog", best_by="221223", address="abd", longtitude=50, latitude=12, -description="vvv", src="110", metro="Petrogradskaya", booked_by=2) - -a3 = Announcement(user_id=1, category="a", best_by="221223", address="abd", longtitude=20, latitude=25, -description="vvv", src="101", metro="metro", booked_by=2) - -trash1 = Trashbox(name="Tom", address="abd", longtitude=23, latitude=22, category="indisposable") - -# db.add(a1) # добавляем в бд -# db.add(a2) # добавляем в бд -# db.add(a3) # добавляем в бд -# db.add(trash1) # добавляем в бд -# db.commit() # сохраняем изменения -# db.refresh(a1) # обновляем состояние объекта -# db.refresh(a2) # обновляем состояние объекта -# db.refresh(a3) # обновляем состояние объекта -# db.refresh(trash1) # обновляем состояние объекта - -# # Удалить все -# db.query(User).delete() -# db.query(Announcement).delete() -# db.commit() \ No newline at end of file diff --git a/back/delete_db.py b/back/delete_db.py new file mode 100644 index 0000000..ba91297 --- /dev/null +++ b/back/delete_db.py @@ -0,0 +1,5 @@ +from sqlalchemy import Table, MetaData +from .db import engine + +tbl = Table('UserDatabase', MetaData(), autoload_with=engine) +tbl.drop(engine, checkfirst=False) \ No newline at end of file diff --git a/back/main.py b/back/main.py index 7673a35..b588b83 100644 --- a/back/main.py +++ b/back/main.py @@ -20,9 +20,8 @@ import os from .utils import * from .db import Base, engine, SessionLocal, database -from .models import Announcement, Trashbox, UserDatabase, Poems -from . import schemas +from . import schemas, models Base.metadata.create_all(bind=engine) @@ -82,23 +81,23 @@ def annoncements_list(user_id: int = None, metro: str = None, category: str = No # Считываем данные из Body и отображаем их на странице. # В последствии будем вставлять данные в html-форму - a = database.query(Announcement) - b = database.query(Announcement) - c = database.query(Announcement) - d = database.query(Announcement) - e = database.query(Announcement) + a = database.query(models.Announcement) + b = database.query(models.Announcement) + c = database.query(models.Announcement) + d = database.query(models.Announcement) + e = database.query(models.Announcement) if user_id != None: - b = a.filter(Announcement.user_id == user_id) + b = a.filter(models.Announcement.user_id == user_id) if metro != None: - c = a.filter(Announcement.metro == metro) + c = a.filter(models.Announcement.metro == metro) if category != None: - d = a.filter(Announcement.category == category) + d = a.filter(models.Announcement.category == category) if booked_by != -1: - e = a.filter(Announcement.booked_by == booked_by) + e = a.filter(models.Announcement.booked_by == booked_by) if not any([category, user_id, metro]) and booked_by == -1: result = a.all() @@ -114,7 +113,7 @@ def single_annoncement(user_id:int): # Считываем данные из Body и отображаем их на странице. # В последствии будем вставлять данные в html-форму try: - annoncement = database.get(Announcement, user_id) + annoncement = database.get(models.Announcement, user_id) return {"id": annoncement.id, "user_id": annoncement.user_id, "name": annoncement.name, "category": annoncement.category, "best_by": annoncement.best_by, "address": annoncement.address, "description": annoncement.description, "metro": annoncement.metro, "latitude": annoncement.latitude, @@ -145,7 +144,7 @@ trashId: Annotated[int, Form()] = None): uploaded_name = "/uploads/"+destination.name - temp_ancmt = Announcement(user_id=userId, name=name, category=category, best_by=bestBy, address=address, longtitude=longtitude, latitude=latitude, description=description, src=uploaded_name, metro=metro, trashId=trashId, booked_by=-1) + temp_ancmt = models.Announcement(user_id=userId, name=name, category=category, best_by=bestBy, address=address, longtitude=longtitude, latitude=latitude, description=description, src=uploaded_name, metro=metro, trashId=trashId, booked_by=-1) database.add(temp_ancmt) # добавляем в бд database.commit() # сохраняем изменения database.refresh(temp_ancmt) # обновляем состояние объекта @@ -158,7 +157,7 @@ trashId: Annotated[int, Form()] = None): @app.delete("/api/announcement") #адрес объявления def delete_from_db(annoncement: schemas.DelAnnouncement): # функция удаления объекта из БД try: - to_delete = database.query(Announcement).filter(Announcement.id==announcement.id).first() + to_delete = database.query(models.Announcement).filter(models.Announcement.id==announcement.id).first() database.delete(to_delete) # удаление из БД database.commit() # сохраняем изменения return {"Answer" : True} @@ -171,7 +170,7 @@ def delete_from_db(annoncement: schemas.DelAnnouncement): # функция у def change_book_status(data: schemas.Book): try: # Находим объявление по данному id - announcement_to_change = database.query(Announcement).filter(Announcement.id == data.id).first() + announcement_to_change = database.query(models.Announcement).filter(Announcement.id == data.id).first() # Изменяем поле booked_status на полученный id announcement_to_change.booked_status += 1 return {"Success": True} @@ -183,8 +182,8 @@ def change_book_status(data: schemas.Book): # {"id":1, "email":"poopka@mail.ru", "password":"good", "name":"Vasya", "surname":"Poopkin"} @app.post("/api/signup") def create_user(data = Body()): - if database.query(UserDatabase).filter(UserDatabase.email == data["email"]).first() == None: - new_user = UserDatabase(email=data["email"], hashed_password=get_password_hash(data["password"]), + if database.query(models.User).filter(models.User.email == data["email"]).first() == None: + new_user = models.User(email=data["email"], hashed_password=get_password_hash(data["password"]), name=data["name"], surname=data["surname"]) database.add(new_user) database.commit() @@ -193,7 +192,7 @@ def create_user(data = Body()): return {"Success": False, "Message": "Пользователь с таким email уже зарегестрирован,"} -@app.post("/api/token", response_model=Token) +@app.post("/api/token", response_model=schemas.Token) async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] ): @@ -211,11 +210,11 @@ async def login_for_access_token( return {"access_token":access_token} -@app.get("/api/users/me/", response_model=schemas.User) -async def read_users_me( #!!!!!!!!!!! - current_user: Annotated[schemas.User, Depends(get_current_active_user)] -): - return current_user +# @app.get("/api/users/me/", response_model=schemas.User) +# async def read_users_me( #!!!!!!!!!!! +# current_user: Annotated[schemas.User, Depends(get_current_active_user)] +# ): +# return current_user # @app.get("/api/users/me/items/") diff --git a/back/models.py b/back/models.py index 6f8af8c..ef59272 100644 --- a/back/models.py +++ b/back/models.py @@ -1,4 +1,4 @@ -from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, Date +from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, Date, ForeignKey from fastapi import Depends from .db import Base, engine from sqlalchemy.orm import relationship @@ -25,7 +25,7 @@ class Announcement(Base): #класс объявления __tablename__ = "announcements" id = Column(Integer, primary_key=True, index=True)#айди объявления - user_id = Column(Integer)#айди создателя объявления + owner_id = Column(Integer, ForeignKey("users.id"))#айди создателя объявления name = Column(String) # название объявления category = Column(String)#категория продукта из объявления best_by = Column(Date)#срок годности продукта из объявления diff --git a/back/utils.py b/back/utils.py index 5ff2397..466972b 100644 --- a/back/utils.py +++ b/back/utils.py @@ -10,8 +10,7 @@ from sqlalchemy.orm import Session from sqlalchemy import select # from .db import Session, database -from .models import User -from .schemas import Token, TokenData, UserInDB, User +from . import models, schemas @@ -33,7 +32,7 @@ def get_password_hash(password): # проблема здесь def get_user(db: Session, email: str): - user_with_required_email = db.query(User).filter(User.email == email).first() + user_with_required_email = db.query(models.User).filter(models.User.email == email).first() if user_with_required_email: return user_with_required_email return None @@ -70,17 +69,17 @@ async def get_current_user(db: Session, token: Annotated[str, Depends(oauth2_sch email: str = payload.get("sub") if email is None: raise credentials_exception - token_data = TokenData(email=email) + token_data = schemas.TokenData(email=email) except JWTError: raise credentials_exception user = get_user(db, email=token_data.email) if user is None: raise credentials_exception - return User.from_orm(user) + return schemas.User.from_orm(user) async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[schemas.User, Depends(get_current_user)] ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") diff --git a/migrations/env.py b/migrations/env.py index 692d4b8..d3c1002 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -49,6 +49,7 @@ def run_migrations_offline(): target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, + render_as_batch=True ) with context.begin_transaction(): @@ -72,7 +73,9 @@ def run_migrations_online(): with connectable.connect() as connection: context.configure( - connection=connection, target_metadata=target_metadata + connection=connection, + target_metadata=target_metadata, + render_as_batch=True ) with context.begin_transaction(): diff --git a/migrations/versions/0006eca30e2c_first.py b/migrations/versions/0006eca30e2c_first.py deleted file mode 100644 index 4f379a7..0000000 --- a/migrations/versions/0006eca30e2c_first.py +++ /dev/null @@ -1,28 +0,0 @@ -"""first - -Revision ID: 0006eca30e2c -Revises: -Create Date: 2023-07-23 22:32:43.496939 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '0006eca30e2c' -down_revision = None -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - pass - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - pass - # ### end Alembic commands ### diff --git a/migrations/versions/33c5716276b5_try_to_make_alembic_see_models.py b/migrations/versions/00529d20660b_foreignkey_added_to_announcement_model.py similarity index 51% rename from migrations/versions/33c5716276b5_try_to_make_alembic_see_models.py rename to migrations/versions/00529d20660b_foreignkey_added_to_announcement_model.py index 84de522..90f2b35 100644 --- a/migrations/versions/33c5716276b5_try_to_make_alembic_see_models.py +++ b/migrations/versions/00529d20660b_foreignkey_added_to_announcement_model.py @@ -1,8 +1,8 @@ -"""Try to make alembic see models +"""ForeignKey added to Announcement model -Revision ID: 33c5716276b5 -Revises: 0006eca30e2c -Create Date: 2023-07-23 22:42:07.532395 +Revision ID: 00529d20660b +Revises: +Create Date: 2023-07-30 12:24:13.714196 """ from alembic import op @@ -10,31 +10,23 @@ import sqlalchemy as sa # revision identifiers, used by Alembic. -revision = '33c5716276b5' -down_revision = '0006eca30e2c' +revision = '00529d20660b' +down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('announcements', + op.create_table('poems', sa.Column('id', sa.Integer(), nullable=False), - sa.Column('user_id', sa.Integer(), nullable=True), - sa.Column('name', sa.String(), nullable=True), - sa.Column('category', sa.String(), nullable=True), - sa.Column('best_by', sa.Integer(), nullable=True), - sa.Column('address', sa.String(), nullable=True), - sa.Column('longtitude', sa.Integer(), nullable=True), - sa.Column('latitude', sa.Integer(), nullable=True), - sa.Column('description', sa.String(), nullable=True), - sa.Column('src', sa.String(), nullable=True), - sa.Column('metro', sa.String(), nullable=True), - sa.Column('trashId', sa.Integer(), nullable=True), - sa.Column('booked_by', sa.Integer(), nullable=True), + sa.Column('poem_name', sa.String(), nullable=True), + sa.Column('poem_text', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id') ) - op.create_index(op.f('ix_announcements_id'), 'announcements', ['id'], unique=False) + with op.batch_alter_table('poems', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_poems_id'), ['id'], unique=False) + op.create_table('trashboxes', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=True), @@ -44,27 +36,60 @@ def upgrade(): sa.Column('category', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id') ) - op.create_index(op.f('ix_trashboxes_id'), 'trashboxes', ['id'], unique=False) + with op.batch_alter_table('trashboxes', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_trashboxes_id'), ['id'], unique=False) + op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), - sa.Column('phone', sa.Integer(), nullable=True), sa.Column('email', sa.String(), nullable=True), - sa.Column('password', sa.String(), nullable=True), sa.Column('hashed_password', sa.String(), nullable=True), sa.Column('name', sa.String(), nullable=True), sa.Column('surname', sa.String(), nullable=True), + sa.Column('disabled', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id') ) - op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=True) + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_users_id'), ['id'], unique=True) + + op.create_table('announcements', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('owner_id', sa.Integer(), nullable=True), + sa.Column('name', sa.String(), nullable=True), + sa.Column('category', sa.String(), nullable=True), + sa.Column('best_by', sa.Date(), nullable=True), + sa.Column('address', sa.String(), nullable=True), + sa.Column('longtitude', sa.Integer(), nullable=True), + sa.Column('latitude', sa.Integer(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('src', sa.String(), nullable=True), + sa.Column('metro', sa.String(), nullable=True), + sa.Column('trashId', sa.Integer(), nullable=True), + sa.Column('booked_by', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('announcements', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_announcements_id'), ['id'], unique=False) + # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_users_id'), table_name='users') - op.drop_table('users') - op.drop_index(op.f('ix_trashboxes_id'), table_name='trashboxes') - op.drop_table('trashboxes') - op.drop_index(op.f('ix_announcements_id'), table_name='announcements') + with op.batch_alter_table('announcements', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_announcements_id')) + op.drop_table('announcements') + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_users_id')) + + op.drop_table('users') + with op.batch_alter_table('trashboxes', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_trashboxes_id')) + + op.drop_table('trashboxes') + with op.batch_alter_table('poems', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_poems_id')) + + op.drop_table('poems') # ### end Alembic commands ### diff --git a/migrations/versions/18001c2231e3_poems_table_added.py b/migrations/versions/18001c2231e3_poems_table_added.py deleted file mode 100644 index 78675aa..0000000 --- a/migrations/versions/18001c2231e3_poems_table_added.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Poems table added - -Revision ID: 18001c2231e3 -Revises: 33c5716276b5 -Create Date: 2023-07-23 22:50:16.055961 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '18001c2231e3' -down_revision = '33c5716276b5' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('poems', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('poem_text', sa.String(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.create_index(op.f('ix_poems_id'), 'poems', ['id'], unique=False) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_poems_id'), table_name='poems') - op.drop_table('poems') - # ### end Alembic commands ### diff --git a/migrations/versions/1cf412fb7547_new_colomn_poem_name_added_to_poems_.py b/migrations/versions/1cf412fb7547_new_colomn_poem_name_added_to_poems_.py deleted file mode 100644 index 40bbd75..0000000 --- a/migrations/versions/1cf412fb7547_new_colomn_poem_name_added_to_poems_.py +++ /dev/null @@ -1,28 +0,0 @@ -"""new colomn (poem_name) added to poems table - -Revision ID: 1cf412fb7547 -Revises: daffcb4729af -Create Date: 2023-07-27 21:29:57.568487 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '1cf412fb7547' -down_revision = 'daffcb4729af' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - pass - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - pass - # ### end Alembic commands ### diff --git a/migrations/versions/57c3df575fa5_new_colomn_poem_name_added_to_poems_.py b/migrations/versions/57c3df575fa5_new_colomn_poem_name_added_to_poems_.py deleted file mode 100644 index 61b9048..0000000 --- a/migrations/versions/57c3df575fa5_new_colomn_poem_name_added_to_poems_.py +++ /dev/null @@ -1,28 +0,0 @@ -"""new colomn (poem_name) added to poems table - -Revision ID: 57c3df575fa5 -Revises: 1cf412fb7547 -Create Date: 2023-07-27 21:40:06.979472 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '57c3df575fa5' -down_revision = '1cf412fb7547' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('poems', sa.Column('poem_name', sa.String(), nullable=True)) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('poems', 'poem_name') - # ### end Alembic commands ### diff --git a/migrations/versions/6ef6877e89ff_odd_fields_in_user_model_removed_links_.py b/migrations/versions/6ef6877e89ff_odd_fields_in_user_model_removed_links_.py deleted file mode 100644 index c8c162b..0000000 --- a/migrations/versions/6ef6877e89ff_odd_fields_in_user_model_removed_links_.py +++ /dev/null @@ -1,30 +0,0 @@ -"""odd fields in user model removed. links between User and Announcement added. UserDatabase renamed to User - -Revision ID: 6ef6877e89ff -Revises: 57c3df575fa5 -Create Date: 2023-07-29 23:35:33.833531 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '6ef6877e89ff' -down_revision = '57c3df575fa5' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('users', 'password') - op.drop_column('users', 'phone') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('users', sa.Column('phone', sa.INTEGER(), nullable=True)) - op.add_column('users', sa.Column('password', sa.VARCHAR(), nullable=True)) - # ### end Alembic commands ### diff --git a/migrations/versions/daffcb4729af_new_colomn_disabled_added_to_user_table.py b/migrations/versions/daffcb4729af_new_colomn_disabled_added_to_user_table.py deleted file mode 100644 index b6abe04..0000000 --- a/migrations/versions/daffcb4729af_new_colomn_disabled_added_to_user_table.py +++ /dev/null @@ -1,28 +0,0 @@ -"""new colomn (disabled) added to user table - -Revision ID: daffcb4729af -Revises: 18001c2231e3 -Create Date: 2023-07-26 23:54:22.640750 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'daffcb4729af' -down_revision = '18001c2231e3' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('users', sa.Column('disabled', sa.Boolean(), nullable=True)) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('users', 'disabled') - # ### end Alembic commands ###