Compare commits

...

3 Commits

9 changed files with 164 additions and 52 deletions

View File

@ -98,7 +98,7 @@ async def put_in_db(name: Annotated[str, Form()], category: Annotated[str, Form(
# создаем объект Announcement
temp_ancmt = orm_models.Announcement(user_id=current_user.id, name=name, category=category, best_by=bestBy,
address=address, longtitude=longtitude, latitude=latitude, description=description, metro=metro,
trashId=trashId, src=uploaded_name, booked_by=0)
trashId=trashId, src=uploaded_name, booked_counter=0)
try:
db.add(temp_ancmt) # добавляем в бд
await db.commit() # сохраняем изменения
@ -142,12 +142,25 @@ async def change_book_status(data: pydantic_schemas.Book, current_user: Annotate
if current_user.id == announcement_to_change.user_id:
raise HTTPException(status_code=403, detail="A user can't book his announcement")
else:
# Инкрементируем поле booked_by на 1
announcement_to_change.booked_by += 1
# фиксируем изменения в бд
await db.commit()
await db.refresh(announcement_to_change)
return {"Success": True}
# ищем пару с заданными id объявления и пользователя
query = await db.execute(select(orm_models.AnnouncementUser).where(
orm_models.AnnouncementUser.announcement_id == announcement_to_change.id).where(
orm_models.AnnouncementUser.booking_user_id == current_user.id))
pair_found = query.scalars().first()
# если не найдена
if not pair_found:
# создаем новый объект таблицы AnnouncementUser
new_pair = orm_models.AnnouncementUser(announcement_to_change.id, current_user.id)
# Инкрементируем поле booked_counter на 1
announcement_to_change.booked_counter += 1
# вставляем индекс забронировавшего пользователя в поле booked_by
db.add(new_pair)
# фиксируем изменения в бд
await db.commit()
await db.refresh(announcement_to_change)
return {"Success": True}
raise HTTPException(status_code=403, detail="The announcement is already booked by this user")
# reginstration
@ -208,7 +221,7 @@ async def generate_refresh_token(
):
# задаем временной интервал, в течение которого токен можно использовать
access_token_expires = auth_utils.timedelta(minutes=auth_utils.ACCESS_TOKEN_EXPIRE_MINUTES)
# создаем новый токен токен
# создаем новый токен
access_token = auth_utils.create_access_token(
data={"user_id": current_user.id}, expires_delta=access_token_expires
)

View File

@ -21,7 +21,7 @@ async def main():
await init_models()
server = Server(config=uvicorn.Config(app_fastapi, workers=1, loop="asyncio", host="0.0.0.0"))
server = Server(config=uvicorn.Config(app_fastapi, workers=1, loop="asyncio", host="127.0.0.1"))
api = asyncio.create_task(server.serve())
sched = asyncio.create_task(app_rocketry.serve())

View File

@ -1,9 +1,10 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, Date, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String, Boolean, Float, Date, ForeignKey, ForeignKeyConstraint
from sqlalchemy.orm import relationship, mapped_column, composite, Mapped
from sqlalchemy.dialects import postgresql
import dataclasses
from .db import Base, engine
class User(Base):#класс пользователя
__tablename__ = "users"
@ -18,7 +19,7 @@ class User(Base):#класс пользователя
num_of_ratings = Column(Integer, default=0) # количество оценок (т.е. то, сколько раз другие пользователи оценили текущего)
reg_date = Column(Date) # дата регистрации
announcements = relationship("Announcement", back_populates="user", lazy='selectin')
announcements = relationship("Announcement", secondary="announcementuser", back_populates="user", lazy='selectin')
trashboxes_chosen = relationship("Trashbox", back_populates="user", lazy='selectin')
class Announcement(Base): #класс объявления
@ -36,11 +37,35 @@ class Announcement(Base): #класс объявления
src = Column(String, nullable=True) #изображение продукта в объявлении
metro = Column(String) #ближайщее метро от адреса нахождения продукта
trashId = Column(Integer, nullable=True)
booked_by = Column(Integer) #количество забронировавших (0 - никто не забронировал)
# state = Column(Enum(State), default=State.published) # состояние объявления (опубликовано, забронировано, устарело)
booked_by = Column(Integer, nullable=True) # id пользователя, забронировавшего объявление
booked_counter = Column(Integer, nullable=True) #количество забронировавших (0 - никто не забронировал)
obsolete = Column(Boolean, default=False) # состояние объявления (по-умолчанию считаем его актуальным)
user = relationship("User", back_populates="announcements")
user = relationship("User", secondary="announcementuser", back_populates="announcements")
# Класс пары, хранящей id объявления и id забронировавшего юзера
@dataclasses.dataclass
class UserAnouncementPair:
announcement_id: int
booking_user_id: int
class AnnouncementUser(Base):
__tablename__ = "announcementuser"
def __init__(self, an_id, b_u_id):
self.announcement_id = an_id
self.booking_user_id = b_u_id
announcement_id = Column(Integer, ForeignKey("announcements.id"), primary_key=True) # id забронированного объявления
booking_user_id = Column(Integer, ForeignKey("users.id"), primary_key=True) # id пользователя, забронировавшего объявление
# class Ratings(Base):
# __tablename__ = "ratings"
# rated_user_id = Column(Integer, primary_key=True) # id пользователя, оставившего оценку
# rating_value = Column(Integer, primary_key=True) # оценка
class Trashbox(Base): #класс мусорных баков

View File

@ -1,8 +1,8 @@
"""lazy=selectin added to user table relationships
"""create constructor to make object (if leave as is, with two primary keys, says that one argument required, but two were given). Booked_counter can be nullable
Revision ID: 8e631a2fe6b8
Revises:
Create Date: 2023-09-02 23:45:08.799366
Revision ID: 19dbd9793f11
Revises: 945c70aa70e7
Create Date: 2024-08-13 15:29:21.542539
"""
from typing import Sequence, Union
@ -12,8 +12,8 @@ import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '8e631a2fe6b8'
down_revision: Union[str, None] = None
revision: str = '19dbd9793f11'
down_revision: Union[str, None] = '945c70aa70e7'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

View File

@ -20,7 +20,6 @@ def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('announcements', schema=None) as batch_op:
batch_op.add_column(sa.Column('user_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('state', sa.Enum('published', 'taken', 'obsolete', name='state'), nullable=True))
# batch_op.drop_constraint(None, type_='foreignkey')
batch_op.create_foreign_key('fk_users_id', 'users', ['user_id'], ['id'])
batch_op.drop_column('owner_id')
@ -42,7 +41,6 @@ def downgrade():
batch_op.add_column(sa.Column('owner_id', sa.INTEGER(), nullable=True))
# batch_op.drop_constraint('fk_users_id', type_='foreignkey')
batch_op.create_foreign_key(None, 'users', ['owner_id'], ['id'])
batch_op.drop_column('state')
batch_op.drop_column('user_id')
# ### end Alembic commands ###

View File

@ -18,13 +18,6 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('poems', schema=None) as batch_op:
batch_op.add_column(sa.Column('title', sa.String(), nullable=True))
batch_op.add_column(sa.Column('text', sa.String(), nullable=True))
batch_op.add_column(sa.Column('author', sa.String(), nullable=True))
batch_op.drop_column('poem_name')
batch_op.drop_column('poem_text')
with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('category', sa.String(), nullable=True))
batch_op.drop_column('categories')
@ -37,12 +30,4 @@ def downgrade():
with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('categories', sa.VARCHAR(), nullable=True))
batch_op.drop_column('category')
with op.batch_alter_table('poems', schema=None) as batch_op:
batch_op.add_column(sa.Column('poem_text', sa.VARCHAR(), nullable=True))
batch_op.add_column(sa.Column('poem_name', sa.VARCHAR(), nullable=True))
batch_op.drop_column('author')
batch_op.drop_column('text')
batch_op.drop_column('title')
# ### end Alembic commands ###

View File

@ -0,0 +1,66 @@
"""Added booked_by column which contains id of users who booked the announcement old booked_by renamed to booked_counter
Revision ID: 5a8105ac1a4f
Revises: 547f860f21a7
Create Date: 2024-08-09 15:07:51.386406
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '5a8105ac1a4f'
down_revision: Union[str, None] = '547f860f21a7'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('announcements', sa.Column('booked_counter', sa.Integer(), nullable=True))
op.alter_column('announcements', 'longtitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.alter_column('announcements', 'latitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.drop_column('announcements', 'booked_by')
op.alter_column('trashboxes', 'latitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.alter_column('trashboxes', 'longtitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.create_foreign_key(None, 'trashboxes', 'users', ['user_id'], ['id'])
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'trashboxes', type_='foreignkey')
op.alter_column('trashboxes', 'longtitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.alter_column('trashboxes', 'latitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.add_column('announcements', sa.Column('booked_by', sa.INTEGER(), autoincrement=False, nullable=True))
op.alter_column('announcements', 'latitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.alter_column('announcements', 'longtitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.drop_column('announcements', 'booked_counter')
# ### end Alembic commands ###

View File

@ -0,0 +1,38 @@
"""booked_by colomn changed to Integer, added new table AnnouncementUser implementing one to many relationships
Revision ID: 945c70aa70e7
Revises: 5a8105ac1a4f
Create Date: 2024-08-12 20:36:08.669574
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '945c70aa70e7'
down_revision: Union[str, None] = '5a8105ac1a4f'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('announcementuser',
sa.Column('announcement_id', sa.Integer(), nullable=False),
sa.Column('booking_user_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['announcement_id'], ['announcements.id'], ),
sa.ForeignKeyConstraint(['booking_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('announcement_id', 'booking_user_id')
)
op.add_column('announcements', sa.Column('booked_by', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('announcements', 'booked_by')
op.drop_table('announcementuser')
# ### end Alembic commands ###

View File

@ -18,10 +18,8 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('_alembic_tmp_users')
with op.batch_alter_table('announcements', schema=None) as batch_op:
batch_op.add_column(sa.Column('obsolete', sa.Boolean(), nullable=True))
batch_op.drop_column('state')
with op.batch_alter_table('poems', schema=None) as batch_op:
batch_op.add_column(sa.Column('title', sa.String(), nullable=True))
@ -49,16 +47,5 @@ def downgrade():
batch_op.drop_column('title')
with op.batch_alter_table('announcements', schema=None) as batch_op:
batch_op.add_column(sa.Column('state', sa.VARCHAR(length=9), nullable=True))
batch_op.drop_column('obsolete')
op.create_table('_alembic_tmp_users',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('email', sa.VARCHAR(), nullable=True),
sa.Column('hashed_password', sa.VARCHAR(), nullable=True),
sa.Column('name', sa.VARCHAR(), nullable=True),
sa.Column('surname', sa.VARCHAR(), nullable=True),
sa.Column('disabled', sa.BOOLEAN(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###