making async api - 2

This commit is contained in:
DmitryGantimurov 2023-08-31 23:41:48 +03:00
parent 4326c70dbc
commit 2c870ee983
4 changed files with 27 additions and 14 deletions

View File

@ -48,7 +48,8 @@ async def add_poems_to_db(async_db: AsyncSession):
async def filter_ann(schema: pydantic_schemas.SortAnnouncements, db: AsyncSession):
"""Функция для последовательного применения различных фильтров (через схему SortAnnouncements)"""
res = await db.execute(select(orm_models.Announcement)).scalars().all()
res = await db.execute(select(orm_models.Announcement))
res = res.fetchall()
fields = schema.__dict__ # параметры передоваемой схемы SortAnnouncements (ключи и значения)
# проходим по названиям фильтров и их значениям
for name, filt in fields.items():

View File

@ -11,6 +11,7 @@ from typing import Any, Annotated, List, Union
from starlette.staticfiles import StaticFiles
from sqlalchemy.orm import Session
from sqlalchemy import select
from dotenv import load_dotenv, dotenv_values
import requests
from uuid import uuid4
@ -41,6 +42,14 @@ if not os.path.exists("./uploads"):
# создаем эндпоинт для хранения файлов пользователя
app.mount("/uploads", StaticFiles(directory = "./uploads"))
# load_dotenv("unimportant.env")
# ACCESS_TOKEN_EXPIRE_MINUTES = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES")
ACCESS_TOKEN_EXPIRE_MINUTES = 1440
# эндпоинт для возвращения согласия в pdf
@app.get("/privacy_policy.pdf")
async def privacy_policy():
return FileResponse("privacy_policy.pdf")
# получение списка объявлений
@app.get("/api/announcements", response_model=List[pydantic_schemas.Announcement])#адрес объявлений
@ -176,7 +185,7 @@ async def login_for_access_token(
headers={"WWW-Authenticate": "Bearer"},
)
# задаем временной интервал, в течение которого токен можно использовать
access_token_expires = await auth_utils.timedelta(minutes=auth_utils.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token_expires = auth_utils.timedelta(minutes=auth_utils.ACCESS_TOKEN_EXPIRE_MINUTES)
# создаем токен
access_token = await auth_utils.create_access_token(
data={"user_id": user.id}, expires_delta=access_token_expires
@ -289,7 +298,7 @@ async def get_trashboxes(data: pydantic_schemas.TrashboxRequest = Depends()):#к
@app.get("/{rest_of_path:path}")
async def react_app(req: Request, rest_of_path: str):
await templates.TemplateResponse('index.html', { 'request': req })
return templates.TemplateResponse('index.html', { 'request': req })
@app.post("/api/announcement/dispose")

View File

@ -14,10 +14,13 @@ from dotenv import load_dotenv
from .db import SessionLocal
from . import orm_models, pydantic_schemas
load_dotenv("unimportant.env")
SECRET_KEY = os.getenv("SECRET_KEY")
ALGORITHM = os.getenv("ALGORITHM")
ACCESS_TOKEN_EXPIRE_MINUTES = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES")
# load_dotenv("unimportant.env")
# SECRET_KEY = os.getenv("SECRET_KEY")
# ALGORITHM = os.getenv("ALGORITHM")
# ACCESS_TOKEN_EXPIRE_MINUTES = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES")
ACCESS_TOKEN_EXPIRE_MINUTES = 1440
SECRET_KEY = "651a52941cf5de14d48ef5d7af115709"
ALGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token")
@ -36,7 +39,7 @@ async def get_password_hash(password):
async def get_user_by_nickname(db: Annotated[AsyncSession, Depends(get_session)], nickname: str):
query = db.execute(select(orm_models.User).where(orm_models.User.nickname == nickname))
query = await db.execute(select(orm_models.User).where(orm_models.User.nickname == nickname))
user_with_required_nickname = query.scalars().first()
if user_with_required_nickname:
return user_with_required_nickname
@ -44,7 +47,7 @@ async def get_user_by_nickname(db: Annotated[AsyncSession, Depends(get_session)]
async def get_user_by_id(db: Annotated[AsyncSession, Depends(get_session)], user_id: int):
query = db.execute(select(orm_models.User).where(orm_models.User.id == user_id))
query = await db.execute(select(orm_models.User).where(orm_models.User.id == user_id))
user_with_required_id = query.scalars().first()
if user_with_required_id:
return user_with_required_id
@ -67,7 +70,7 @@ async def create_access_token(data: dict, expires_delta: Union[timedelta, None]
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = await jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
@ -78,8 +81,8 @@ async def get_current_user(db: Annotated[AsyncSession, Depends(get_session)], to
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = await jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: int = await payload.get("user_id")
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: int = payload.get("user_id")
if user_id is None:
raise credentials_exception
token_data = pydantic_schemas.TokenData(user_id=user_id)

View File

@ -3,8 +3,8 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_scoped_session, create_as
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://postgres:D560c34V112Ak@localhost/porridger"
SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///./sql_app.db"
# SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://postgres:D560c34V112Ak@localhost/porridger"
engine = create_async_engine(SQLALCHEMY_DATABASE_URL, echo=True)
SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)