Skip to content

Commit 7473d2e

Browse files
committed
Database sington
1 parent ddd15a8 commit 7473d2e

File tree

5 files changed

+59
-25
lines changed

5 files changed

+59
-25
lines changed

app/__init__.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,29 @@
33
"""
44

55
from fastapi import FastAPI
6+
from fastapi.responses import JSONResponse
67

78
from app import api
9+
from app.core import exps
810
from app.core.settings import settings
911

1012
app = FastAPI(
1113
title=settings.APP_TITLE,
1214
root_path=settings.APP_PATH,
1315
version=settings.APP_VERSION,
1416
contact={
15-
'name': 'Fast Code',
16-
'url': 'https://fast-code.pro/',
17-
'email': '[email protected]',
17+
"name": "Fast Code",
18+
"url": "https://fast-code.pro/",
19+
"email": "[email protected]",
1820
},
1921
)
2022

2123
app.include_router(api.api_router)
24+
25+
26+
@app.exception_handler(exps.BaseException)
27+
async def exception_handler(request, exc: exps.BaseException):
28+
return JSONResponse(
29+
status_code=exc.status_code,
30+
content={"detail": exc.message},
31+
)

app/core/db.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
1-
"""
2-
Database
3-
"""
4-
51
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
62
from sqlmodel.ext.asyncio.session import AsyncSession
7-
83
from app import repositories as repos
94
from app.core.settings import settings
105

116

127
class Database:
8+
_instance = None
9+
10+
def __new__(cls, *args, **kwargs):
11+
if cls._instance is None:
12+
cls._instance = super(Database, cls).__new__(cls)
13+
return cls._instance
14+
1315
def __init__(
1416
self, engine: AsyncEngine | None = None, session: AsyncSession | None = None
1517
) -> None:
16-
self.engine = engine
17-
self.session = session
18+
if not hasattr(self, "initialized"): # Проверка, инициализирован ли объект
19+
self.engine = engine
20+
self.session = session
21+
self.initialized = True # Установим флаг инициализации
1822

1923
async def __set_async_engine(self) -> None:
2024
if self.engine is None:

app/core/exps.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,36 @@
22
Exceptions
33
"""
44

5-
from fastapi import HTTPException, status
5+
6+
class BaseException(Exception):
7+
def __init__(self, message: str, status_code: int = 500):
8+
super().__init__(message)
9+
self.message = message
10+
self.status_code = status_code
11+
612

713
# Users
8-
USER_EXISTS = HTTPException(status.HTTP_409_CONFLICT, 'User is already taken.')
9-
USER_NOT_FOUND = HTTPException(status.HTTP_404_NOT_FOUND, 'User not found.')
10-
USER_IS_CORRECT = HTTPException(
11-
status.HTTP_401_UNAUTHORIZED, 'User is correct.'
12-
)
14+
class UserExistsException(BaseException):
15+
def __init__(self):
16+
super().__init__("User is already taken.", status_code=409)
17+
18+
19+
class UserNotFoundException(BaseException):
20+
def __init__(self):
21+
super().__init__("User not found.", status_code=404)
22+
23+
24+
class UserIsCorrectException(BaseException):
25+
def __init__(self):
26+
super().__init__("User is correct.", status_code=401)
27+
1328

1429
# Tokens
15-
TOKEN_INVALID = HTTPException(status.HTTP_401_UNAUTHORIZED, 'Invalid token.')
16-
TOKEN_EXPIRED = HTTPException(status.HTTP_401_UNAUTHORIZED, 'Token expired.')
30+
class TokenInvalidException(BaseException):
31+
def __init__(self):
32+
super().__init__("Invalid token.", status_code=401)
33+
34+
35+
class TokenExpiredException(BaseException):
36+
def __init__(self):
37+
super().__init__("Token expired.", status_code=401)

app/logic/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def __init__(self, db: Database):
1111
self.users = Users(self)
1212

1313
@classmethod
14-
async def create(cls):
14+
async def create(cls) -> "Logic":
1515
async with Database() as db:
1616
return cls(db)
1717

app/logic/users.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __init__(self, logic: "Logic"):
1515

1616
async def create(self, email: str, password: str) -> User | None:
1717
if await self.logic.db.user.retrieve_by_email(email):
18-
raise exps.USER_EXISTS
18+
raise exps.UserExistsException()
1919

2020
password_hash = self.logic.security.pwd.hashpwd(password)
2121
model = User(email=email, password=password_hash)
@@ -25,17 +25,16 @@ async def create(self, email: str, password: str) -> User | None:
2525
async def generate_token(self, email: str, password: str) -> AccessToken | None:
2626
if user := await self.logic.db.user.retrieve_by_email(email):
2727
if not self.logic.security.pwd.checkpwd(password, user.password):
28-
raise exps.USER_IS_CORRECT
29-
access_token = self.logic.security.jwt.encode_token(
30-
{"id": user.id}, 1440)
28+
raise exps.UserIsCorrectException()
29+
access_token = self.logic.security.jwt.encode_token({"id": user.id}, 1440)
3130
return AccessToken(token=access_token)
32-
raise exps.USER_NOT_FOUND
31+
raise exps.UserNotFoundException()
3332

3433
async def retrieve_by_token(self, token: str) -> User | None:
3534
if payload := self.logic.security.jwt.decode_token(token):
3635
if not (
3736
user := await self.logic.db.user.retrieve_one(ident=payload.get("id"))
3837
):
39-
raise exps.USER_NOT_FOUND
38+
raise exps.UserNotFoundException()
4039
else:
4140
return user

0 commit comments

Comments
 (0)