Files
sqlalchemy-fastapi-pydentic…/server/database/db.py
2025-09-25 17:54:34 +03:00

90 lines
3.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
#from sqlalchemy import create_engine #Не async
from sqlalchemy.orm import DeclarativeBase, sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy import Column, Integer, String, Boolean, select
from pathlib import Path
db_folder = Path(__file__).parent / "DB"
db_folder.mkdir(parents=True, exist_ok=True)
db_path = db_folder / "example.db"
async_engine = create_async_engine(f"sqlite+aiosqlite:///{db_path}", echo=True)
#sqlite+aiosqlite — тип БД + async-драйвер ///example.db — путь к файлу (три слэша, если путь относительный; четыре, если абсолютный
#async_engine = create_async_engine( "postgresql+asyncpg://user:pass@host:5432/mydb", echo=True) #Можно указать Pgpool-II для psql или proxysql для mysql mariadb
from passlib.context import CryptContext
#Hash password
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
class Base(DeclarativeBase):
pass
AsyncSessionLocal = sessionmaker(async_engine,class_=AsyncSession, expire_on_commit=False)
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String(254), unique=True, nullable=False)
description = Column(String, nullable=False)
activated = Column(Boolean, default=False)
password = Column(String, nullable=False)
async def init_db():
async with async_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def create_user(user_info):
async with AsyncSessionLocal() as session:
new_user = User(email=user_info.email, description=user_info.description, activated=user_info.activated, password=hash_password(user_info.password))
session.add(new_user)
await session.commit()
await session.refresh(new_user)
async def get_user_by_email(email):
async with AsyncSessionLocal() as session:
result = await session.execute(select(User).where(User.email==email))
user = result.scalar_one_or_none()
return user
async def get_all_rows():
async with AsyncSessionLocal() as session:
result = await session.execute(select(User))
users = result.scalars().all()
return users
async def update_user(user_info):
async with AsyncSessionLocal() as session:
result = await session.execute(select(User).where(User.id==user_info.id))
user = result.scalar_one_or_none()
if user:
user.email = user_info.email
user.description = user_info.description
user.activated = user_info.activated
user.password = hash_password(user_info.password)
await session.commit()
async def delete_user(email):
async with AsyncSessionLocal() as session:
result = await session.execute(select(User).where(User.email==email))
user = result.scalar_one_or_none()
if user:
await session.delete(user)
await session.commit()
async def login_user(user_info):
async with AsyncSessionLocal() as session:
result = await session.execute(select(User).where(User.email == user_info.email))
user = result.scalar_one_or_none()
if user and verify_password(user_info.password, user.password):
return user
return None
async def reset_user(user_info):
async with AsyncSessionLocal() as session:
result = await session.execute(select(User).where(User.email == user_info.email))
user = result.scalar_one_or_none()
if user:
user.password = hash_password(user_info.new_password)
await session.commit()
return user
return None
async def main():
await init_db()