clean imports (delete imports, which are not used)

This commit is contained in:
DmitryGantimurov 2023-08-12 23:46:09 +03:00
parent a5798cf767
commit 1880f8abec
7 changed files with 86 additions and 25 deletions

View File

@ -9,6 +9,7 @@ from fastapi.requests import Request
from pydantic import json from pydantic import json
from typing import Any, Annotated, List, Union from typing import Any, Annotated, List, Union
from starlette.staticfiles import StaticFiles from starlette.staticfiles import StaticFiles
from sqlalchemy.orm import Session
import requests import requests
from uuid import uuid4 from uuid import uuid4
@ -21,12 +22,8 @@ import pathlib
import shutil import shutil
import os import os
from .db import Base, engine, SessionLocal, database, Session
from .scheduler import app as app_rocketry
from . import schemas, models, utils, service from . import schemas, models, utils, service
Base.metadata.create_all(bind=engine)
app = FastAPI() app = FastAPI()
templates = Jinja2Templates(directory="./front/dist") templates = Jinja2Templates(directory="./front/dist")
@ -269,16 +266,26 @@ async def react_app(req: Request, rest_of_path: str):
@app.post("/api/announcement/dispose") @app.post("/api/announcement/dispose")
def dispose(data: schemas.DisposeRequest, current_user_schema: Annotated[schemas.User, Depends(utils.get_current_user)], 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 = utils.get_user_by_id(db, current_user_schema.id)
# Начисляем баллы пользователю за утилизацию # Начисляем баллы пользователю за утилизацию
current_user.points += 60 current_user.points += 60
# В полученном json переходим к данным мусорки # В полученном json переходим к данным мусорки
data_trashbox = data.trashbox 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, 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) 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.commit()
db.refresh(new_trashox) # обновляем состояние объекта db.refresh(new_trashox) # обновляем состояние объекта
return {"Success": True}

View File

@ -1,13 +1,10 @@
from typing import AsyncGenerator 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.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 sqlalchemy.ext.declarative import declarative_base
from fastapi import Depends
# from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"

View File

@ -1,6 +1,12 @@
from sqlalchemy import Table, MetaData from sqlalchemy import Table, MetaData, text
from .db import engine from .db import engine, Base
tbl = Table('UserDatabase', MetaData(), autoload_with=engine) # tbl = Table('Poems', MetaData(), autoload_with=engine)
tbl.drop(engine, checkfirst=False) # tbl.drop(engine, checkfirst=False)
a = input() # a = input()
# Base.metadata.drop_all(bind=engine)
with engine.connect() as conn:
conn.execute(text("DELETE FROM alembic_version"))
conn.commit()

View File

@ -1,5 +1,4 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, ARRAY, Date, ForeignKey, Enum, UniqueConstraint from sqlalchemy import Column, Integer, String, Boolean, Float, Date, ForeignKey
from fastapi import Depends
from .db import Base, engine from .db import Base, engine
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
@ -52,7 +51,7 @@ class Trashbox(Base): #класс мусорных баков
address = Column(String) address = Column(String)
latitude = Column(Float) latitude = Column(Float)
longtitude = Column(Float) longtitude = Column(Float)
categories = Column(String) #типы мусора (из тех, что возвращает API мусорки) category = Column(String) #типы мусора (из тех, что возвращает API мусорки)
date_of_choice = Column(Date) # Дата выбора мусорки пользователем date_of_choice = Column(Date) # Дата выбора мусорки пользователем
user = relationship("User", back_populates="trashboxes_chosen") user = relationship("User", back_populates="trashboxes_chosen")
@ -66,6 +65,12 @@ class Poems(Base):#класс поэзии
text = Column(String) # текст стихотворения text = Column(String) # текст стихотворения
author = Column(String) # автор стихотворения author = Column(String) # автор стихотворения
# Создаем описанные выше таблицы
Base.metadata.create_all(bind=engine)
# from typing import AsyncGenerator # from typing import AsyncGenerator
# from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine # from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
# from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase # from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase

View File

@ -1,5 +1,5 @@
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import Annotated, Union from typing import Annotated
from fastapi import Depends from fastapi import Depends
from . import models, schemas, utils from . import models, schemas, utils
import random import random

View File

@ -1,15 +1,13 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Annotated, Union from typing import Annotated, Union
from fastapi import Depends, FastAPI, HTTPException, status from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt from jose import JWTError, jwt
from passlib.context import CryptContext from passlib.context import CryptContext
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from sqlalchemy import select
from .db import Session, database from .db import database
from . import models, schemas from . import models, schemas

View File

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