This commit is contained in:
2023-04-06 23:58:56 +03:00
parent 89f3d073d9
commit f954a46601
17 changed files with 264 additions and 10 deletions

48
db/DB.py Normal file
View File

@ -0,0 +1,48 @@
from sqlmodel import Field, SQLModel, create_engine
from sqlalchemy.ext.asyncio.engine import create_async_engine
from sqlalchemy.orm.session import sessionmaker
from sqlalchemy.ext.asyncio.session import AsyncSession
class DB:
# instance = None
config = None
engine = None
async_engine = None
session_maker = None
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(DB, cls).__new__(cls)
return cls.instance
def __init__(self):
from db import config
self.config = config
sqlite_url = self.config['DATABASE_URI']
self.engine = create_engine(sqlite_url, echo=True)
SQLModel.metadata.create_all(self.engine)
def get_engine(self):
return self.engine
def create_async_engine(self):
self.async_engine = create_async_engine(self.config['DATABASE_URI'], furure=True)
self.session_maker = sessionmaker(self.async_engine, expire_on_commit=False, class_=AsyncSession)
class DBException(Exception):
def __init__(self, *args):
self.is_db = True
if args:
self.msg = args[0]
else:
self.msg = None
def __str__(self):
if self.msg:
return "DB error, {0}".format(self.msg)
else:
return "DB error"

6
db/__init__.py Normal file
View File

@ -0,0 +1,6 @@
from dotenv import dotenv_values
from pathlib import Path # Python 3.6+ only
env_path = Path('.') / '.env.local'
config = dotenv_values(dotenv_path=env_path)

52
db/models/User.py Normal file
View File

@ -0,0 +1,52 @@
from typing import Optional
from sqlmodel import Field, SQLModel, Session, select
from db.DB import DB, DBException
from sqlalchemy import exc
import hashlib, uuid, base64
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: Optional[str] = None
login: str = Field(max_length=255)
email: str = Field(sa_column_kwargs={'unique': True})
age: Optional[int] = None
password_hash: str = Field(max_length=255)
status: Optional[int] = Field(default=0)
def create(self):
db = DB()
session = Session(db.get_engine())
self.password_hash = self.create_password_hash(self.password_hash)
session.add(self)
try:
session.commit()
session.refresh(self)
except exc.SQLAlchemyError as sqla_error:
return DBException(sqla_error)
session.close()
return self
@staticmethod
def get_by_id(user_id):
db = DB()
with Session(db.get_engine()) as s:
statement = select(User).where(User.id == user_id)
res = s.exec(statement)
return res.first()
@staticmethod
def create_password_hash(password):
salt = "5gz"
# Adding salt at the last of the password
data_base_password = password + salt
# Encoding the password
hashed = hashlib.md5(data_base_password.encode())
return hashed.hexdigest()