Alembic installed and activated. Poems table added

This commit is contained in:
2023-07-23 22:52:31 +03:00
committed by Dmitry Gantimurov
parent b06306a20b
commit d97ca1c43f
13 changed files with 378 additions and 16 deletions

2
back/base.py Normal file
View File

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

View File

@ -1,6 +1,6 @@
from typing import AsyncGenerator
from sqlalchemy import Column, Integer, String, create_engine, select
from sqlalchemy import create_engine, select
# from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
@ -15,7 +15,7 @@ engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(bind=engine, autoflush=True, autocommit=False, expire_on_commit=False)
SessionLocal = sessionmaker(bind=engine, autoflush=True, autocommit=False)
database = SessionLocal()
Base = declarative_base()

View File

@ -36,8 +36,22 @@ if not os.path.exists("./uploads"):
app.mount("/uploads", StaticFiles(directory = "./uploads"))
# Функция, создающая сессию БД при каждом запросе к нашему API.
# Срабатывает до запуска остальных функций.
# Всегда закрывает сессию при окончании работы с ней
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
response = Response("Internal server error", status_code=500)
try:
request.state.db = SessionLocal()
response = await call_next(request)
finally:
request.state.db.close()
return response
@app.get("/api/announcements")#адрес объявлений
def annoncements_list(user_id: int = None, metro: str = None, category: str = None, booked_by: int = -1):
def annoncements_list(user_id: int = None, metro: str = None, category: str = None, booked_by: int = 0):
# Считываем данные из Body и отображаем их на странице.
# В последствии будем вставлять данные в html-форму

View File

@ -6,7 +6,7 @@ from .db import Base
class UserDatabase(Base):#класс пользователя
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)#айди пользователя
id = Column(Integer, primary_key=True, index=True, unique=True)#айди пользователя
phone = Column(Integer, nullable=True)#номер телефона пользователя
email = Column(String)#электронная почта пользователя
password = Column(String) # пароль
@ -44,6 +44,12 @@ class Trashbox(Base):#класс мусорных баков
category = Column(String)#категория продукта из объявления
class Poems(Base):#класс поэзии
__tablename__ = "poems"
id = Column(Integer, primary_key=True, index=True) #айди
poem_text = Column(String) # текст стихотворения
# from typing import AsyncGenerator
# from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
# from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase

2
back/service.py Normal file
View File

@ -0,0 +1,2 @@
from sqlalchemy.orm import Session

View File

@ -1,7 +1,7 @@
from datetime import datetime, timedelta
from typing import Annotated, Union
from fastapi import Depends, FastAPI, HTTPException, status, Response
from fastapi import Depends, FastAPI, HTTPException, status, Response, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
@ -19,16 +19,6 @@ ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# fake_users_db = {
# "johndoe": {
# "email": "johndoe",
# "full_name": "John Doe",
# "email": "johndoe@example.com",
# "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
# "disabled": False,
# }
# }
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@ -95,4 +85,8 @@ async def get_current_active_user(
):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
return current_user
def get_db(request: Request):
return request.state.db