Odd fields in User model removed. Schemas updated

This commit is contained in:
DmitryGantimurov 2023-07-29 23:46:33 +03:00
parent eb19113d78
commit 86acf3e326
6 changed files with 70 additions and 21 deletions

View File

@ -1,2 +1,2 @@
from .db import Base
from .models import UserDatabase, Announcement, Trashbox
from .models import User, Announcement, Trashbox

View File

@ -211,11 +211,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 {"data": 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,6 +1,7 @@
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, Date
from fastapi import Depends
from .db import Base, engine
from sqlalchemy.orm import relationship
# class User(SQLAlchemyBaseUserTableUUID, Base):
@ -8,18 +9,17 @@ from .db import Base, engine
class UserDatabase(Base):#класс пользователя
class User(Base):#класс пользователя
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True, unique=True)#айди пользователя
phone = Column(Integer, nullable=True)#номер телефона пользователя
email = Column(String)#электронная почта пользователя
password = Column(String) # пароль
hashed_password = Column(String)
name = Column(String, nullable=True)#имя пользователя
surname = Column(String)#фамилия пользователя
disabled = Column(Boolean, default=True)
disabled = Column(Boolean, default=False)
items = relationship("Announcement", back_populates="owner")
class Announcement(Base): #класс объявления
__tablename__ = "announcements"
@ -28,7 +28,7 @@ class Announcement(Base): #класс объявления
user_id = Column(Integer)#айди создателя объявления
name = Column(String) # название объявления
category = Column(String)#категория продукта из объявления
best_by = Column(Integer)#срок годности продукта из объявления
best_by = Column(Date)#срок годности продукта из объявления
address = Column(String)
longtitude = Column(Integer)
latitude = Column(Integer)
@ -38,6 +38,8 @@ class Announcement(Base): #класс объявления
trashId = Column(Integer, nullable=True)
booked_by = Column(Integer)#статус бронирования (либо -1, либо айди бронирующего)
owner = relationship("User", back_populates="items")
class Trashbox(Base):#класс мусорных баков
__tablename__ = "trashboxes"

View File

@ -1,10 +1,31 @@
from pydantic import BaseModel
from typing import Annotated, Union
from datetime import date
class Book(BaseModel):
id: int
class DelAnnouncement(BaseModel):
id: int
class Announcement(BaseModel):
id: int
user_id: int
name: str
category: str
best_by: date
address: str
longtitude: float
latitude: float
description: str
src: Union[str, None] = None #изображение продукта в объявлении
metro: str #ближайщее метро от адреса нахождения продукта
trashId: Union[int, None] = None
booked_by: int #статус бронирования (либо -1, либо айди бронирующего)
class Token(BaseModel):
access_token: str
# token_type: str
@ -16,21 +37,17 @@ class TokenData(BaseModel):
class User(BaseModel):
id: int
phone: Union[int, None] = None
email: str
name: Union[str, None] = None
surname: str
disabled: Union[bool, None] = None
items: list[Announcement] = []
class Config:
orm_mode = True
class UserInDB(User):
password: str
hashed_password: str
class DelAnnouncement(BaseModel):
id: int

View File

@ -10,7 +10,7 @@ from sqlalchemy.orm import Session
from sqlalchemy import select
# from .db import Session, database
from .models import UserDatabase
from .models import User
from .schemas import Token, TokenData, UserInDB, User
@ -33,7 +33,7 @@ def get_password_hash(password):
# проблема здесь
def get_user(db: Session, email: str):
user_with_required_email = db.query(UserDatabase).filter(UserDatabase.email == email).one()
user_with_required_email = db.query(User).filter(User.email == email).first()
if user_with_required_email:
return user_with_required_email
return None
@ -76,11 +76,11 @@ async def get_current_user(db: Session, token: Annotated[str, Depends(oauth2_sch
user = get_user(db, email=token_data.email)
if user is None:
raise credentials_exception
return UserInDB(user)
return User.from_orm(user)
async def get_current_active_user(
current_user: Annotated[UserInDB, Depends(get_current_user)]
current_user: Annotated[User, Depends(get_current_user)]
):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")

View File

@ -0,0 +1,30 @@
"""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 ###