You've already forked Promocode-API
mirror of
https://github.com/devitq/Promocode-API.git
synced 2026-05-22 20:57:11 +00:00
сhore: code refactoring
This commit is contained in:
@@ -23,7 +23,7 @@ router = Router(tags=["business"])
|
|||||||
response={
|
response={
|
||||||
status.OK: schemas.BusinessSignUpOut,
|
status.OK: schemas.BusinessSignUpOut,
|
||||||
status.BAD_REQUEST: global_schemas.BadRequestError,
|
status.BAD_REQUEST: global_schemas.BadRequestError,
|
||||||
status.CONFLICT: global_schemas.UniqueConstraintError,
|
status.CONFLICT: global_schemas.ConflictError,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
def signup(
|
def signup(
|
||||||
@@ -135,6 +135,7 @@ def create_promocode(
|
|||||||
response={
|
response={
|
||||||
status.OK: list[schemas.PromocodeViewOut],
|
status.OK: list[schemas.PromocodeViewOut],
|
||||||
status.BAD_REQUEST: global_schemas.BadRequestError,
|
status.BAD_REQUEST: global_schemas.BadRequestError,
|
||||||
|
status.UNAUTHORIZED: global_schemas.UnauthorizedError,
|
||||||
},
|
},
|
||||||
exclude_none=True,
|
exclude_none=True,
|
||||||
)
|
)
|
||||||
@@ -188,7 +189,8 @@ def list_promocode(
|
|||||||
auth=BusinessAuth(),
|
auth=BusinessAuth(),
|
||||||
response={
|
response={
|
||||||
status.OK: schemas.PromocodeViewOut,
|
status.OK: schemas.PromocodeViewOut,
|
||||||
status.NOT_FOUND: global_schemas.NotFoundError,
|
status.BAD_REQUEST: global_schemas.BadRequestError,
|
||||||
|
status.UNAUTHORIZED: global_schemas.UnauthorizedError,
|
||||||
},
|
},
|
||||||
exclude_none=True,
|
exclude_none=True,
|
||||||
)
|
)
|
||||||
@@ -228,7 +230,8 @@ def get_promocode(
|
|||||||
auth=BusinessAuth(),
|
auth=BusinessAuth(),
|
||||||
response={
|
response={
|
||||||
status.OK: schemas.PromocodeViewOut,
|
status.OK: schemas.PromocodeViewOut,
|
||||||
status.NOT_FOUND: global_schemas.NotFoundError,
|
status.BAD_REQUEST: global_schemas.BadRequestError,
|
||||||
|
status.UNAUTHORIZED: global_schemas.UnauthorizedError,
|
||||||
},
|
},
|
||||||
exclude_none=True,
|
exclude_none=True,
|
||||||
)
|
)
|
||||||
@@ -286,7 +289,8 @@ def patch_promocode(
|
|||||||
auth=BusinessAuth(),
|
auth=BusinessAuth(),
|
||||||
response={
|
response={
|
||||||
status.OK: schemas.PromocodeStats,
|
status.OK: schemas.PromocodeStats,
|
||||||
status.NOT_FOUND: global_schemas.NotFoundError,
|
status.BAD_REQUEST: global_schemas.BadRequestError,
|
||||||
|
status.UNAUTHORIZED: global_schemas.UnauthorizedError,
|
||||||
},
|
},
|
||||||
exclude_none=True,
|
exclude_none=True,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ import ninja.errors
|
|||||||
from django.http import HttpRequest, HttpResponse
|
from django.http import HttpRequest, HttpResponse
|
||||||
from ninja import NinjaAPI
|
from ninja import NinjaAPI
|
||||||
|
|
||||||
from config.errors import UniqueConstraintError
|
from config.errors import ConflictError
|
||||||
|
|
||||||
logger = logging.getLogger("django")
|
logger = logging.getLogger("django")
|
||||||
|
|
||||||
|
|
||||||
def handle_unique_constraint_error(
|
def handle_conflict_error(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
exc: UniqueConstraintError,
|
exc: ConflictError,
|
||||||
router: NinjaAPI,
|
router: NinjaAPI,
|
||||||
) -> HttpResponse:
|
) -> HttpResponse:
|
||||||
detail = list(exc.validation_error)
|
detail = list(exc.validation_error)
|
||||||
@@ -97,7 +97,7 @@ def handle_unknown_exception(
|
|||||||
|
|
||||||
|
|
||||||
exception_handlers = [
|
exception_handlers = [
|
||||||
(UniqueConstraintError, handle_unique_constraint_error),
|
(ConflictError, handle_conflict_error),
|
||||||
(django.core.exceptions.ValidationError, handle_django_validation_error),
|
(django.core.exceptions.ValidationError, handle_django_validation_error),
|
||||||
(ninja.errors.AuthenticationError, handle_authentication_error),
|
(ninja.errors.AuthenticationError, handle_authentication_error),
|
||||||
(ninja.errors.ValidationError, handle_validation_error),
|
(ninja.errors.ValidationError, handle_validation_error),
|
||||||
|
|||||||
@@ -4,17 +4,21 @@ from typing import Any
|
|||||||
from ninja import Schema
|
from ninja import Schema
|
||||||
|
|
||||||
|
|
||||||
|
class BadRequestError(Schema):
|
||||||
|
detail: Any
|
||||||
|
|
||||||
|
|
||||||
class UnauthorizedError(Schema):
|
class UnauthorizedError(Schema):
|
||||||
detail: str = status.UNAUTHORIZED.phrase
|
detail: str = status.UNAUTHORIZED.phrase
|
||||||
|
|
||||||
|
|
||||||
|
class ForbiddenError(Schema):
|
||||||
|
detail: str = status.FORBIDDEN.phrase
|
||||||
|
|
||||||
|
|
||||||
class NotFoundError(Schema):
|
class NotFoundError(Schema):
|
||||||
detail: str = status.NOT_FOUND.phrase
|
detail: str = status.NOT_FOUND.phrase
|
||||||
|
|
||||||
|
|
||||||
class BadRequestError(Schema):
|
class ConflictError(Schema):
|
||||||
detail: Any
|
|
||||||
|
|
||||||
|
|
||||||
class UniqueConstraintError(Schema):
|
|
||||||
detail: Any
|
detail: Any
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from apps.promo.models import (
|
|||||||
PromocodeLike,
|
PromocodeLike,
|
||||||
)
|
)
|
||||||
from apps.user.models import User
|
from apps.user.models import User
|
||||||
from config.errors import UniqueConstraintError
|
from config.errors import ConflictError
|
||||||
from config.integrations.antifraud.interactor import AntifraudServiceInteractor
|
from config.integrations.antifraud.interactor import AntifraudServiceInteractor
|
||||||
|
|
||||||
router = Router(tags=["user"])
|
router = Router(tags=["user"])
|
||||||
@@ -27,7 +27,7 @@ router = Router(tags=["user"])
|
|||||||
response={
|
response={
|
||||||
status.OK: schemas.UserSignUpOut,
|
status.OK: schemas.UserSignUpOut,
|
||||||
status.BAD_REQUEST: global_schemas.BadRequestError,
|
status.BAD_REQUEST: global_schemas.BadRequestError,
|
||||||
status.CONFLICT: global_schemas.UniqueConstraintError,
|
status.CONFLICT: global_schemas.ConflictError,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
def signup(
|
def signup(
|
||||||
@@ -216,16 +216,20 @@ def get_activations_history(
|
|||||||
.order_by("-timestamp")
|
.order_by("-timestamp")
|
||||||
)
|
)
|
||||||
|
|
||||||
result = []
|
promocodes = []
|
||||||
for activation in activations:
|
for activation in activations:
|
||||||
promocode = activation.promocode
|
promocode = activation.promocode
|
||||||
promocode.like_count = activation.like_count
|
promocode.like_count = activation.like_count
|
||||||
promocode.comment_count = activation.comment_count
|
promocode.comment_count = activation.comment_count
|
||||||
promocode.is_liked_by_user = activation.is_liked_by_user
|
promocode.is_liked_by_user = activation.is_liked_by_user
|
||||||
promocode.is_activated_by_user = True
|
promocode.is_activated_by_user = True
|
||||||
result.append(utils.map_promocode_to_schema(promocode))
|
promocodes.append(utils.map_promocode_to_schema(promocode))
|
||||||
|
|
||||||
return status.OK, result
|
response["X-Total-Count"] = len(promocodes)
|
||||||
|
|
||||||
|
promocodes = promocodes[filters.offset : filters.offset + filters.limit]
|
||||||
|
|
||||||
|
return status.OK, promocodes
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
@@ -292,7 +296,7 @@ def add_like(
|
|||||||
if not promocodes.exists():
|
if not promocodes.exists():
|
||||||
raise HttpError(status.NOT_FOUND, status.NOT_FOUND.phrase)
|
raise HttpError(status.NOT_FOUND, status.NOT_FOUND.phrase)
|
||||||
|
|
||||||
with contextlib.suppress(UniqueConstraintError):
|
with contextlib.suppress(ConflictError):
|
||||||
PromocodeLike.objects.create(promocode=promocodes.first(), user=user)
|
PromocodeLike.objects.create(promocode=promocodes.first(), user=user)
|
||||||
|
|
||||||
return status.OK, schemas.PromocodeLikeOut()
|
return status.OK, schemas.PromocodeLikeOut()
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Any
|
|||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
from config.errors import UniqueConstraintError
|
from config.errors import ConflictError
|
||||||
|
|
||||||
|
|
||||||
class BaseModel(models.Model):
|
class BaseModel(models.Model):
|
||||||
@@ -39,10 +39,10 @@ class BaseModel(models.Model):
|
|||||||
try:
|
try:
|
||||||
self.validate_unique()
|
self.validate_unique()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
raise UniqueConstraintError(e) from None
|
raise ConflictError(e) from None
|
||||||
|
|
||||||
if validate_constraints:
|
if validate_constraints:
|
||||||
try:
|
try:
|
||||||
self.validate_constraints()
|
self.validate_constraints()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
raise UniqueConstraintError(e) from None
|
raise ConflictError(e) from None
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
|
|
||||||
|
|
||||||
class UniqueConstraintError(Exception):
|
class ConflictError(Exception):
|
||||||
def __init__(self, validation_error: ValidationError) -> None:
|
def __init__(self, validation_error: ValidationError) -> None:
|
||||||
self.validation_error = validation_error
|
self.validation_error = validation_error
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ class AntifraudHealthCheck(BaseHealthCheckBackend):
|
|||||||
|
|
||||||
def check_status(self) -> None:
|
def check_status(self) -> None:
|
||||||
try:
|
try:
|
||||||
response = httpx.get(f"{settings.ANTIFRAUD_ADDRESS}/api/ping")
|
response = httpx.get(
|
||||||
|
f"{settings.ANTIFRAUD_ADDRESS}/api/ping", timeout=1
|
||||||
|
)
|
||||||
if response.status_code >= status.INTERNAL_SERVER_ERROR:
|
if response.status_code >= status.INTERNAL_SERVER_ERROR:
|
||||||
self.add_error("Antifraud service is unaccessible")
|
self.add_error("Antifraud service is unaccessible")
|
||||||
except httpx.HTTPError:
|
except httpx.HTTPError:
|
||||||
|
|||||||
@@ -100,11 +100,9 @@ class AntifraudServiceInteractor:
|
|||||||
cache.set(cache_key, result)
|
cache.set(cache_key, result)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
except Exception:
|
||||||
except Exception as e:
|
|
||||||
logger.exception(
|
logger.exception(
|
||||||
"Unexpected error during antifraud validation: %s",
|
"Unexpected error during antifraud validation",
|
||||||
e, # noqa: TRY401
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return {"ok": False}
|
return {"ok": False}
|
||||||
|
|||||||
Reference in New Issue
Block a user