UserDatabase->User, ForeignKey added

This commit is contained in:
DmitryGantimurov 2023-07-30 12:35:08 +03:00
parent 517609ddbd
commit aaf0d20c65
13 changed files with 92 additions and 277 deletions

View File

@ -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()

5
back/delete_db.py Normal file
View File

@ -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)

View File

@ -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/")

View File

@ -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)#срок годности продукта из объявления

View File

@ -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")

View File

@ -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():

View File

@ -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 ###

View File

@ -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 ###

View File

@ -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 ###

View File

@ -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 ###

View File

@ -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 ###

View File

@ -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 ###

View File

@ -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 ###