From 1880f8abecbd6a3db0e589205405586905991424 Mon Sep 17 00:00:00 2001 From: DmitryGantimurov Date: Sat, 12 Aug 2023 23:46:09 +0300 Subject: [PATCH] clean imports (delete imports, which are not used) --- back/api.py | 19 +++++--- back/db.py | 7 +-- back/delete_db.py | 16 +++++-- back/models.py | 11 +++-- back/service.py | 2 +- back/utils.py | 8 ++-- ...7_in_trashbox_model_categories_category.py | 48 +++++++++++++++++++ 7 files changed, 86 insertions(+), 25 deletions(-) create mode 100644 migrations/versions/547f860f21a7_in_trashbox_model_categories_category.py diff --git a/back/api.py b/back/api.py index 815043b..837d0a7 100644 --- a/back/api.py +++ b/back/api.py @@ -9,6 +9,7 @@ from fastapi.requests import Request from pydantic import json from typing import Any, Annotated, List, Union from starlette.staticfiles import StaticFiles +from sqlalchemy.orm import Session import requests from uuid import uuid4 @@ -21,12 +22,8 @@ import pathlib import shutil import os -from .db import Base, engine, SessionLocal, database, Session -from .scheduler import app as app_rocketry from . import schemas, models, utils, service -Base.metadata.create_all(bind=engine) - app = FastAPI() templates = Jinja2Templates(directory="./front/dist") @@ -269,16 +266,26 @@ async def react_app(req: Request, rest_of_path: str): @app.post("/api/announcement/dispose") def dispose(data: schemas.DisposeRequest, current_user_schema: Annotated[schemas.User, Depends(utils.get_current_user)], - db: Annotated[Session, Depends(utils.get_db)]): + db: Annotated[Session, Depends(utils.get_db)]): # Находим в бд текущего юзера current_user = utils.get_user_by_id(db, current_user_schema.id) # Начисляем баллы пользователю за утилизацию current_user.points += 60 # В полученном json переходим к данным мусорки data_trashbox = data.trashbox + # создаем запись models.Trashbox new_trashox = models.Trashbox(user_id=current_user.id, date_of_choice=datetime.date.today(), name=data_trashbox.Name, - latitude=data_trashbox.Lat, longtitude=data_trashbox.Lng, address=data_trashbox.Address, categories=data_trashbox.Category) + latitude=data_trashbox.Lat, longtitude=data_trashbox.Lng, address=data_trashbox.Address, category=data_trashbox.Category) + # добавляем в бд db.add(new_trashox) + # в соответствии с логикой api, после утилизации объявление пользователя удаляется + # находим объявление с айди data.ann_id + ann_to_del = db.query(models.Announcement).filter(models.Announcement.id == data.ann_id).first() # находим стих в бд + if not ann_to_del: + raise HTTPException(status_code=404, detail="Announcement not found") + # удаляем объявление из бд + db.delete(ann_to_del) db.commit() db.refresh(new_trashox) # обновляем состояние объекта + return {"Success": True} diff --git a/back/db.py b/back/db.py index d4d7872..12d83a7 100644 --- a/back/db.py +++ b/back/db.py @@ -1,13 +1,10 @@ from typing import AsyncGenerator -from sqlalchemy import create_engine, select, MetaData +from sqlalchemy import create_engine, MetaData # from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine -from sqlalchemy.orm import sessionmaker, Session, DeclarativeBase +from sqlalchemy.orm import sessionmaker, DeclarativeBase from sqlalchemy.ext.declarative import declarative_base -from fastapi import Depends -# from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase - SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" diff --git a/back/delete_db.py b/back/delete_db.py index 669ca3b..87966e1 100644 --- a/back/delete_db.py +++ b/back/delete_db.py @@ -1,6 +1,12 @@ -from sqlalchemy import Table, MetaData -from .db import engine +from sqlalchemy import Table, MetaData, text +from .db import engine, Base -tbl = Table('UserDatabase', MetaData(), autoload_with=engine) -tbl.drop(engine, checkfirst=False) -a = input() \ No newline at end of file +# tbl = Table('Poems', MetaData(), autoload_with=engine) +# tbl.drop(engine, checkfirst=False) +# a = input() + +# Base.metadata.drop_all(bind=engine) + +with engine.connect() as conn: + conn.execute(text("DELETE FROM alembic_version")) + conn.commit() \ No newline at end of file diff --git a/back/models.py b/back/models.py index a6717d5..1e807f9 100644 --- a/back/models.py +++ b/back/models.py @@ -1,5 +1,4 @@ -from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, ARRAY, Date, ForeignKey, Enum, UniqueConstraint -from fastapi import Depends +from sqlalchemy import Column, Integer, String, Boolean, Float, Date, ForeignKey from .db import Base, engine from sqlalchemy.orm import relationship @@ -52,7 +51,7 @@ class Trashbox(Base): #класс мусорных баков address = Column(String) latitude = Column(Float) longtitude = Column(Float) - categories = Column(String) #типы мусора (из тех, что возвращает API мусорки) + category = Column(String) #типы мусора (из тех, что возвращает API мусорки) date_of_choice = Column(Date) # Дата выбора мусорки пользователем user = relationship("User", back_populates="trashboxes_chosen") @@ -66,6 +65,12 @@ class Poems(Base):#класс поэзии text = Column(String) # текст стихотворения author = Column(String) # автор стихотворения + +# Создаем описанные выше таблицы +Base.metadata.create_all(bind=engine) + + + # from typing import AsyncGenerator # from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine # from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase diff --git a/back/service.py b/back/service.py index 5b3e572..05104c0 100644 --- a/back/service.py +++ b/back/service.py @@ -1,5 +1,5 @@ from sqlalchemy.orm import Session -from typing import Annotated, Union +from typing import Annotated from fastapi import Depends from . import models, schemas, utils import random diff --git a/back/utils.py b/back/utils.py index 97652d6..e425b78 100644 --- a/back/utils.py +++ b/back/utils.py @@ -1,15 +1,13 @@ from datetime import datetime, timedelta from typing import Annotated, Union -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from passlib.context import CryptContext - from sqlalchemy.orm import Session -from sqlalchemy import select -from .db import Session, database +from .db import database from . import models, schemas diff --git a/migrations/versions/547f860f21a7_in_trashbox_model_categories_category.py b/migrations/versions/547f860f21a7_in_trashbox_model_categories_category.py new file mode 100644 index 0000000..0a4586f --- /dev/null +++ b/migrations/versions/547f860f21a7_in_trashbox_model_categories_category.py @@ -0,0 +1,48 @@ +"""in trashbox model categories->category + +Revision ID: 547f860f21a7 +Revises: a0206e2bf259 +Create Date: 2023-08-12 16:13:44.598427 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '547f860f21a7' +down_revision = 'a0206e2bf259' +branch_labels = None +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') + + # ### 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('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 ###