link_shortener/app/dao.py

25 lines
925 B
Python

from sqlalchemy import select, insert
from app.database import async_session_maker
from app.models import URLs
from app.shemas import SURLs
class URLsDAO:
@staticmethod
async def add_new_url(original_url: str) -> int:
async with async_session_maker() as session:
query = insert(URLs).values(original_url=original_url).returning(URLs.url_hash)
result = await session.execute(query)
await session.commit()
result = result.scalar()
return result
@staticmethod
async def find_by_hash(url_hash: int) -> SURLs:
async with async_session_maker() as session:
query = select(URLs).filter_by(url_hash=url_hash)
result = await session.execute(query)
result: URLs = result.scalar_one_or_none()
if result:
return SURLs(url_hash=result.url_hash, original_url=result.original_url)