Skip to content

Commit

Permalink
Merge pull request #1
Browse files Browse the repository at this point in the history
* feat(core): remove err_code field, change dict type to None field whe…

* feat(settings): add utils logger

* chore(.idea): remove .idea
  • Loading branch information
lihuacai168 authored Aug 19, 2023
1 parent 0723add commit ba2a85c
Show file tree
Hide file tree
Showing 11 changed files with 83 additions and 120 deletions.
36 changes: 0 additions & 36 deletions .idea/inspectionProfiles/Project_Default.xml

This file was deleted.

6 changes: 0 additions & 6 deletions .idea/inspectionProfiles/profiles_settings.xml

This file was deleted.

8 changes: 0 additions & 8 deletions .idea/modules.xml

This file was deleted.

5 changes: 5 additions & 0 deletions apidemo/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,11 @@
"level": "INFO",
"propagate": True,
},
"utils": {
"handlers": ["default", "console", "error"],
"level": "INFO",
"propagate": True,
},

},
}
12 changes: 7 additions & 5 deletions core/response.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""分页核心函数"""
from django.core.paginator import Paginator
from django.db.models import QuerySet

Expand All @@ -6,11 +7,12 @@


def get_page(
qs: QuerySet,
f: PageFilter,
t: GenericResultsType) -> PageSchema:
p = Paginator(qs, per_page=f.page_size).get_page(f.page_index)
return PageSchema[t](
queryset: QuerySet,
pager_filter: PageFilter,
generic_result_type: GenericResultsType) -> PageSchema:
"""标准分页"""
p = Paginator(queryset, per_page=pager_filter.page_size).get_page(pager_filter.page_index)
return PageSchema[generic_result_type](
total=p.paginator.count,
page_size=p.paginator.per_page,
page_index=p.number,
Expand Down
16 changes: 0 additions & 16 deletions core/schema.py

This file was deleted.

52 changes: 23 additions & 29 deletions core/schemas.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from enum import IntEnum
from typing import TypeVar, Generic, List
from typing import TypeVar, Generic, List, Optional
from ninja import Schema
from pydantic import conint, validator, BaseModel, Field
from pydantic.generics import GenericModel


class ErrorMsg(BaseModel):
err_code: conint(ge=0) = 10000
err_msg: str = 'SUCCESS'
message: Optional[str] = None
success: bool = True


GenericResultsType = TypeVar("GenericResultsType")
Expand All @@ -31,35 +31,29 @@ class PageSchema(GenericModel, Generic[GenericResultsType]):
class PageFilter(Schema):
page_index: int = 1
page_size: conint(ge=1, le=100) = 10
ordering: str = Field('', alias="ordering", description='排序字段,多个时用,分割')
ordering: str = Field("", alias="ordering", description="排序字段,多个时用,分割")

@validator('page_index')
@validator("page_index")
def page_index_check(cls, page_index):
if page_index <= 1:
return 1
return page_index

def dict(self,
*,
exclude_none=True,
exclude={'page_index', 'page_size', 'ordering'},
by_alias: bool = False,
skip_defaults: bool = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
) -> 'DictStrAny':
return super().dict(exclude_none=exclude_none, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults,
exclude_unset=exclude_unset, exclude_defaults=exclude_defaults)


class ErrorCode(IntEnum):
DuplicateEntry = 11062
OperationalError = 11045
RecordNotFound = 11063


DefaultResponse = {
'err_code': 0,
'err_msg': 'SUCCESS',
'data': None
}
def dict(
self,
*,
exclude_none=True,
exclude={"page_index", "page_size", "ordering"},
by_alias: bool = False,
skip_defaults: bool = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
) -> "DictStrAny":
return super().dict(
exclude_none=exclude_none,
exclude=exclude,
by_alias=by_alias,
skip_defaults=skip_defaults,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
)
16 changes: 8 additions & 8 deletions core/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from core import cache, response
from core.model import CoreModelSoftDelete
from core.schemas import DictId, PageFilter, PageSchema, StandResponse, ErrorCode
from core.schemas import DictId, PageFilter, PageSchema, StandResponse
from utils import model_opertion
from utils.model_opertion import GenericPayload

Expand Down Expand Up @@ -74,7 +74,7 @@ def get_obj(self, id: int) -> StandResponse:

def list_obj(self, page_filter: PageFilter, page_schema: PageSchema) -> PageSchema:
qs = self.model.objects.filter(**page_filter.dict())
return response.get_page(qs=qs, f=page_filter, t=page_schema)
return response.get_page(queryset=qs, pager_filter=page_filter, generic_result_type=page_schema)

def update_obj(
self, id: int, payload, user_email
Expand Down Expand Up @@ -123,31 +123,31 @@ def _get_obj_by_id(self, id: int, is_deleted=0) -> Union[Model, None]:
return None
return obj

def get_obj(self, id: int) -> StandResponse:
def get_obj(self, id: int) -> StandResponse[Union[Model, None]]:
return StandResponse(data=self._get_obj_by_id(id=id))

def list_obj(self, page_filter: PageFilter, page_schema: PageSchema) -> PageSchema:
qs = self.model.objects.filter(**page_filter.dict(), is_deleted=0)
return response.get_page(qs=qs, f=page_filter, t=page_schema)
return response.get_page(queryset=qs, pager_filter=page_filter, generic_result_type=page_schema)

def update_obj(
self, id: int, payload: GenericPayload, user_email: str
) -> StandResponse[Union[DictId, dict]]:
) -> StandResponse[Union[DictId, None]]:
obj = self._get_obj_by_id(id=id)
if obj is None:
return StandResponse[dict](err_msg=f"{id=} not exist", err_code=ErrorCode.RecordNotFound, data={})
return StandResponse[dict](message=f"{id=} not exist", success=False, data={})
return model_opertion.update_by_obj(
updater=user_email, obj=obj, **payload.dict()
)

def partial_update(self, id: int, user_email: str, **fields_kv):
def partial_update(self, id: int, user_email: str, **fields_kv) -> StandResponse[Union[DictId, None]]:
obj = self._get_obj_by_id(id=id)
return model_opertion.update_by_obj(updater=user_email, obj=obj, **fields_kv)

def delete_obj(self, id: int) -> StandResponse[bool]:
obj = self._get_obj_by_id(id=id)
if obj is None:
return StandResponse[bool](data=False, err_msg=f"{id=} not exist")
return StandResponse[bool](data=False, message=f"{id=} not exist")
obj.is_deleted = str(uuid.uuid1())
obj.save()
return StandResponse[bool](data=True)
Expand Down
27 changes: 27 additions & 0 deletions employee/migrations/0005_alter_department_id_alter_employee_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 4.2.2 on 2023-08-19 02:37

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("employee", "0004_department_create_at_department_creator_and_more"),
]

operations = [
migrations.AlterField(
model_name="department",
name="id",
field=models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
migrations.AlterField(
model_name="employee",
name="id",
field=models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
]
5 changes: 3 additions & 2 deletions employee/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""员工curd view"""
import logging
from typing import Optional, Union

Expand All @@ -20,7 +21,7 @@ class Filters(Schema):
department_id: Optional[conint(ge=0)]


@router.post("/employees", response=StandResponse[DictId])
@router.post("/employees", response=StandResponse[Union[DictId, None]])
def create_employee(request, payload: EmployeeIn):
logger.info(f"input: payload={payload.dict()}")
return employee_service_impl.create_obj(payload, "huacai")
Expand All @@ -40,7 +41,7 @@ def list_employees(request, filters: EmployeeFilters = Query(...)):
return StandResponse(data=objs)


@router.put("/employees/{employee_id}", response=StandResponse[Union[DictId, dict]])
@router.put("/employees/{employee_id}", response=StandResponse[Union[DictId, None]])
def update_employee(request, employee_id: int, payload: EmployeeIn):
payload.department_id = employee_id
logger.info(f"input: payload={payload.dict()}")
Expand Down
20 changes: 10 additions & 10 deletions utils/model_opertion.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@
from django.shortcuts import get_object_or_404
from pydantic import conint

from core.schemas import StandResponse, DictId, ErrorCode
from core.schemas import StandResponse, DictId
from core.model import CoreModel

logger = logging.getLogger('default')
logger = logging.getLogger(__name__)

GenericPayload = TypeVar("GenericPayload")


def create(creator: str, model: CoreModel, payload: GenericPayload) -> StandResponse[Union[DictId, dict]]:
def create(creator: str, model: CoreModel, payload: GenericPayload) -> StandResponse[Union[DictId, None]]:
"""创建对象"""
try:
logger.info(f"input: create={model.__name__}, payload={payload.dict()}")
obj = model.objects.create(creator=creator, **payload.dict())
except Exception as e:
logger.warning(traceback.format_exc())
return StandResponse(err_code=ErrorCode.DuplicateEntry, err_msg=str(e), data={})
logger.error(traceback.format_exc())
return StandResponse(success=False, message=str(e), data=None)
logger.info(f"create {model.__name__} success, id: {obj.id}")
return StandResponse(data=DictId(id=obj.id))

Expand Down Expand Up @@ -49,7 +49,7 @@ def create_obj_with_validate_unique(
return StandResponse(data=DictId(id=obj.id))


def _update(obj, payload: dict, updater: str) -> StandResponse[Union[DictId, dict]]:
def _update(obj, payload: dict, updater: str) -> StandResponse[Union[DictId,None]]:
logger.info(f"input: update={obj.__class__.__name__}, payload={payload}")
obj.updater = updater
for attr, value in payload.items():
Expand All @@ -58,21 +58,21 @@ def _update(obj, payload: dict, updater: str) -> StandResponse[Union[DictId, dic
obj.save()
except Exception as e:
logger.warning(traceback.format_exc())
return StandResponse(err_code=ErrorCode.DuplicateEntry, err_msg=str(e), data={})
return StandResponse(success=False, message=str(e), data=None)
logger.info(f"update {obj.__class__.__name__} success, id: {obj.id}")
return StandResponse(data=DictId(id=obj.id))


def update(updater: str, model: CoreModel, payload: GenericPayload, obj_id: conint(ge=1)) -> StandResponse[Union[DictId, dict]]:
def update(updater: str, model: CoreModel, payload: GenericPayload, obj_id: conint(ge=1)) -> StandResponse[Union[DictId, None]]:
"""更新对象"""
obj = get_object_or_404(model, id=obj_id)
return _update(obj=obj, payload=payload.dict(), updater=updater)


def partial_update(updater: str, model: CoreModel, obj_id: conint(ge=1), **kwargs) -> StandResponse[Union[DictId, dict]]:
def partial_update(updater: str, model: CoreModel, obj_id: conint(ge=1), **kwargs) -> StandResponse[Union[DictId, None]]:
obj = get_object_or_404(model, id=obj_id)
return _update(obj=obj, payload=kwargs, updater=updater)


def update_by_obj(obj: CoreModel, updater: str, **kwargs) -> StandResponse[Union[DictId, dict]]:
def update_by_obj(obj: CoreModel, updater: str, **kwargs) -> StandResponse[Union[DictId, None]]:
return _update(obj=obj, payload=kwargs, updater=updater)

0 comments on commit ba2a85c

Please sign in to comment.