making async api - 2
This commit is contained in:
parent
4326c70dbc
commit
2c870ee983
@ -48,7 +48,8 @@ async def add_poems_to_db(async_db: AsyncSession):
|
|||||||
|
|
||||||
async def filter_ann(schema: pydantic_schemas.SortAnnouncements, db: AsyncSession):
|
async def filter_ann(schema: pydantic_schemas.SortAnnouncements, db: AsyncSession):
|
||||||
"""Функция для последовательного применения различных фильтров (через схему SortAnnouncements)"""
|
"""Функция для последовательного применения различных фильтров (через схему 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 (ключи и значения)
|
fields = schema.__dict__ # параметры передоваемой схемы SortAnnouncements (ключи и значения)
|
||||||
# проходим по названиям фильтров и их значениям
|
# проходим по названиям фильтров и их значениям
|
||||||
for name, filt in fields.items():
|
for name, filt in fields.items():
|
||||||
|
13
back/api.py
13
back/api.py
@ -11,6 +11,7 @@ from typing import Any, Annotated, List, Union
|
|||||||
from starlette.staticfiles import StaticFiles
|
from starlette.staticfiles import StaticFiles
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
from dotenv import load_dotenv, dotenv_values
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
@ -41,6 +42,14 @@ if not os.path.exists("./uploads"):
|
|||||||
# создаем эндпоинт для хранения файлов пользователя
|
# создаем эндпоинт для хранения файлов пользователя
|
||||||
app.mount("/uploads", StaticFiles(directory = "./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])#адрес объявлений
|
@app.get("/api/announcements", response_model=List[pydantic_schemas.Announcement])#адрес объявлений
|
||||||
@ -176,7 +185,7 @@ async def login_for_access_token(
|
|||||||
headers={"WWW-Authenticate": "Bearer"},
|
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(
|
access_token = await auth_utils.create_access_token(
|
||||||
data={"user_id": user.id}, expires_delta=access_token_expires
|
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}")
|
@app.get("/{rest_of_path:path}")
|
||||||
async def react_app(req: Request, rest_of_path: str):
|
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")
|
@app.post("/api/announcement/dispose")
|
||||||
|
@ -14,10 +14,13 @@ from dotenv import load_dotenv
|
|||||||
from .db import SessionLocal
|
from .db import SessionLocal
|
||||||
from . import orm_models, pydantic_schemas
|
from . import orm_models, pydantic_schemas
|
||||||
|
|
||||||
load_dotenv("unimportant.env")
|
# load_dotenv("unimportant.env")
|
||||||
SECRET_KEY = os.getenv("SECRET_KEY")
|
# SECRET_KEY = os.getenv("SECRET_KEY")
|
||||||
ALGORITHM = os.getenv("ALGORITHM")
|
# ALGORITHM = os.getenv("ALGORITHM")
|
||||||
ACCESS_TOKEN_EXPIRE_MINUTES = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES")
|
# 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")
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token")
|
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):
|
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()
|
user_with_required_nickname = query.scalars().first()
|
||||||
if user_with_required_nickname:
|
if user_with_required_nickname:
|
||||||
return 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):
|
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()
|
user_with_required_id = query.scalars().first()
|
||||||
if user_with_required_id:
|
if user_with_required_id:
|
||||||
return 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:
|
else:
|
||||||
expire = datetime.utcnow() + timedelta(minutes=15)
|
expire = datetime.utcnow() + timedelta(minutes=15)
|
||||||
to_encode.update({"exp": expire})
|
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
|
return encoded_jwt
|
||||||
|
|
||||||
|
|
||||||
@ -78,8 +81,8 @@ async def get_current_user(db: Annotated[AsyncSession, Depends(get_session)], to
|
|||||||
headers={"WWW-Authenticate": "Bearer"},
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
payload = await jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
user_id: int = await payload.get("user_id")
|
user_id: int = payload.get("user_id")
|
||||||
if user_id is None:
|
if user_id is None:
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
token_data = pydantic_schemas.TokenData(user_id=user_id)
|
token_data = pydantic_schemas.TokenData(user_id=user_id)
|
||||||
|
@ -3,8 +3,8 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_scoped_session, create_as
|
|||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///./sql_app.db"
|
||||||
SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://postgres:D560c34V112Ak@localhost/porridger"
|
# SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://postgres:D560c34V112Ak@localhost/porridger"
|
||||||
engine = create_async_engine(SQLALCHEMY_DATABASE_URL, echo=True)
|
engine = create_async_engine(SQLALCHEMY_DATABASE_URL, echo=True)
|
||||||
|
|
||||||
SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
|
SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user