Change rating and dispose endpoints fixed

This commit is contained in:
DmitryGantimurov 2023-08-08 23:41:54 +03:00
parent 15d61ecc4b
commit 0c47da5543
5 changed files with 90 additions and 15 deletions

View File

@ -183,6 +183,8 @@ def add_points(data: schemas.AddRating, current_user: Annotated[schemas.User, De
raise HTTPException(status_code=404, detail="Item not found") raise HTTPException(status_code=404, detail="Item not found")
user.rating = (user.rating*user.num_of_ratings + data.rate)/(user.num_of_ratings + 1) user.rating = (user.rating*user.num_of_ratings + data.rate)/(user.num_of_ratings + 1)
user.num_of_ratings += 1 user.num_of_ratings += 1
database.commit()
database.refresh(user) # обновляем состояние объекта
return {"Success": True} return {"Success": True}
@ -245,11 +247,12 @@ async def react_app(req: Request, rest_of_path: str):
return templates.TemplateResponse('index.html', { 'request': req }) return templates.TemplateResponse('index.html', { 'request': req })
@app.post("api/announcement/dispose") @app.post("/api/announcement/dispose")
def dispose(data: schemas.TrashboxResponse, current_user: Annotated[schemas.User, Depends(utils.get_current_user)]): def dispose(data: schemas.DisposeRequest, current_user_schema: Annotated[schemas.User, Depends(utils.get_current_user)]):
current_user = utils.get_user_by_id(database, current_user_schema.id)
current_user.points += 60 current_user.points += 60
new_trashox = models.Trashbox(user_id=current_user.id, date_of_chose=datetime.date.today(), name=data.Name, new_trashox = models.Trashbox(user_id=current_user.id, date_of_choice=datetime.date.today(), name=data.Name,
latitude=data.Lat, longtitude=data.Lng, address=data.Address, category=data.Categories) latitude=data.Lat, longtitude=data.Lng, address=data.Address, categories=data.Categories)
database.add(new_trashox) database.add(new_trashox)
database.commit() database.commit()
database.refresh(new_trashox) # обновляем состояние объекта database.refresh(new_trashox) # обновляем состояние объекта

View File

@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, Date, ForeignKey, Enum, UniqueConstraint from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, ARRAY, Date, ForeignKey, Enum, UniqueConstraint
from fastapi import Depends from fastapi import Depends
from .db import Base, engine from .db import Base, engine
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
@ -30,8 +30,8 @@ class Announcement(Base): #класс объявления
category = Column(String) #категория продукта из объявления category = Column(String) #категория продукта из объявления
best_by = Column(Date) #срок годности продукта из объявления best_by = Column(Date) #срок годности продукта из объявления
address = Column(String) address = Column(String)
longtitude = Column(Integer) longtitude = Column(Float)
latitude = Column(Integer) latitude = Column(Float)
description = Column(String) #описание продукта в объявлении description = Column(String) #описание продукта в объявлении
src = Column(String, nullable=True) #изображение продукта в объявлении src = Column(String, nullable=True) #изображение продукта в объявлении
metro = Column(String) #ближайщее метро от адреса нахождения продукта metro = Column(String) #ближайщее метро от адреса нахождения продукта
@ -50,10 +50,10 @@ class Trashbox(Base): #класс мусорных баков
user_id = Column(Integer, ForeignKey("users.id")) # айди выбравшего мусорку user_id = Column(Integer, ForeignKey("users.id")) # айди выбравшего мусорку
name = Column(String, nullable=True)#название мусорки name = Column(String, nullable=True)#название мусорки
address = Column(String) address = Column(String)
latitude = Column(Integer) latitude = Column(Float)
longtitude = Column(Integer) longtitude = Column(Float)
category = Column(String) #типы мусора (из тех, что возвращает API мусорки) categories = Column(String) #типы мусора (из тех, что возвращает API мусорки)
date_of_chose = Column(Date) # Дата выбора мусорки пользователем date_of_choice = Column(Date) # Дата выбора мусорки пользователем
user = relationship("User", back_populates="trashboxes_chosen") user = relationship("User", back_populates="trashboxes_chosen")

View File

@ -77,20 +77,20 @@ class Poem(BaseModel):
author: str author: str
class TrashboxBase(BaseModel): class TrashboxBase(BaseModel):
Name: str
Lat: float Lat: float
Lng: float Lng: float
class TrashboxResponse(TrashboxBase): class TrashboxResponse(TrashboxBase):
Name: str
Address: str Address: str
Categories: List[str] Categories: str
class TrashboxRequest(TrashboxBase): class TrashboxRequest(TrashboxBase):
Category: str Category: str
class DisposeRequest(BaseModel): class DisposeRequest(TrashboxResponse):
ann_id: int ann_id: int
trashbox: TrashboxRequest
class SortAnnouncements(BaseModel): class SortAnnouncements(BaseModel):
obsolete: Union[int, None] = False obsolete: Union[int, None] = False

View File

@ -0,0 +1,36 @@
"""date_of_chose->date_of_choice; category became Array
Revision ID: 0e97e2f703e8
Revises: a991606e0a35
Create Date: 2023-08-08 21:43:00.992516
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0e97e2f703e8'
down_revision = 'a991606e0a35'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('date_of_choice', sa.Date(), nullable=True))
# batch_op.create_foreign_key(None, 'users', ['user_id'], ['id'])
batch_op.drop_column('date_of_chose')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('date_of_chose', sa.DATE(), nullable=True))
# batch_op.drop_constraint(None, type_='foreignkey')
batch_op.drop_column('date_of_choice')
# ### end Alembic commands ###

View File

@ -0,0 +1,36 @@
"""latitude, longtitude type changed to float (before we used integer); category-> categories
Revision ID: a0206e2bf259
Revises: 0e97e2f703e8
Create Date: 2023-08-08 22:01:10.937018
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a0206e2bf259'
down_revision = '0e97e2f703e8'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('categories', sa.String(), nullable=True))
# batch_op.create_foreign_key(None, 'users', ['user_id'], ['id'])
batch_op.drop_column('category')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('category', sa.VARCHAR(), nullable=True))
# batch_op.drop_constraint(None, type_='foreignkey')
batch_op.drop_column('categories')
# ### end Alembic commands ###