mirror of
https://github.com/fastapi-practices/fastapi-best-architecture.git
synced 2026-09-21 05:02:49 +00:00
Update the code generator to plugin (#578)
* Update the code generator to plugin * Fix get all tables return type
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
|
||||
from backend.app.{{ app_name }}.schema.{{ table_name_en }} import Create{{ schema_name }}Param, Get{{ schema_name }}Detail, Update{{ schema_name }}Param
|
||||
from backend.app.{{ app_name }}.service.{{ table_name_en }}_service import {{ table_name_en }}_service
|
||||
from backend.common.pagination import DependsPagination, PageData, paging_data
|
||||
from backend.common.response.response_schema import ResponseModel, ResponseSchemaModel, response_base
|
||||
from backend.common.security.jwt import DependsJwtAuth
|
||||
from backend.common.security.permission import RequestPermission
|
||||
from backend.common.security.rbac import DependsRBAC
|
||||
from backend.database.db import CurrentSession
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get('/{pk}', summary='获取{{ table_simple_name_zh }}详情', dependencies=[DependsJwtAuth])
|
||||
async def get_{{ table_name_en }}(pk: Annotated[int, Path(description='{{ table_simple_name_zh }} ID')]) -> ResponseSchemaModel[Get{{ schema_name }}Detail]:
|
||||
{{ table_name_en }} = await {{ table_name_en }}_service.get(pk=pk)
|
||||
return response_base.success(data={{ table_name_en }})
|
||||
|
||||
|
||||
@router.get(
|
||||
'',
|
||||
summary='分页获取所有{{ table_simple_name_zh }}',
|
||||
dependencies=[
|
||||
DependsJwtAuth,
|
||||
DependsPagination,
|
||||
],
|
||||
)
|
||||
async def get_pagination_{{ table_name_en }}s(db: CurrentSession) -> ResponseSchemaModel[PageData[Get{{ schema_name }}Detail]]:
|
||||
{{ table_name_en }}_select = await {{ table_name_en }}_service.get_select()
|
||||
page_data = await paging_data(db, {{ table_name_en }}_select)
|
||||
return response_base.success(data=page_data)
|
||||
|
||||
|
||||
@router.post(
|
||||
'',
|
||||
summary='创建{{ table_simple_name_zh }}',
|
||||
dependencies=[
|
||||
Depends(RequestPermission('{{ permission }}:add')),
|
||||
DependsRBAC,
|
||||
],
|
||||
)
|
||||
async def create_{{ table_name_en }}(obj: Create{{ schema_name }}Param) -> ResponseModel:
|
||||
await {{ table_name_en }}_service.create(obj=obj)
|
||||
return response_base.success()
|
||||
|
||||
|
||||
@router.put(
|
||||
'/{pk}',
|
||||
summary='更新{{ table_simple_name_zh }}',
|
||||
dependencies=[
|
||||
Depends(RequestPermission('{{ permission }}:edit')),
|
||||
DependsRBAC,
|
||||
],
|
||||
)
|
||||
async def update_{{ table_name_en }}(pk: Annotated[int, Path(description='{{ table_simple_name_zh }} ID')], obj: Update{{ schema_name }}Param) -> ResponseModel:
|
||||
count = await {{ table_name_en }}_service.update(pk=pk, obj=obj)
|
||||
if count > 0:
|
||||
return response_base.success()
|
||||
return response_base.fail()
|
||||
|
||||
|
||||
@router.delete(
|
||||
'',
|
||||
summary='批量删除{{ table_simple_name_zh }}',
|
||||
dependencies=[
|
||||
Depends(RequestPermission('{{ permission }}:del')),
|
||||
DependsRBAC,
|
||||
],
|
||||
)
|
||||
async def delete_{{ table_name_en }}(pk: Annotated[list[int], Query(description='{{ table_simple_name_zh }} ID 列表')]) -> ResponseModel:
|
||||
count = await {{ table_name_en }}_service.delete(pk=pk)
|
||||
if count > 0:
|
||||
return response_base.success()
|
||||
return response_base.fail()
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
from typing import Sequence
|
||||
|
||||
from sqlalchemy import Select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy_crud_plus import CRUDPlus
|
||||
|
||||
from backend.app.{{ app_name }}.model import {{ table_name_class }}
|
||||
from backend.app.{{ app_name }}.schema.{{ table_name_en }} import Create{{ schema_name }}Param, Update{{ schema_name }}Param
|
||||
|
||||
|
||||
class CRUD{{ table_name_class }}(CRUDPlus[{{ schema_name }}]):
|
||||
async def get(self, db: AsyncSession, pk: int) -> {{ table_name_class }} | None:
|
||||
"""
|
||||
获取{{ table_name_zh }}
|
||||
|
||||
:param db: 数据库会话
|
||||
:param pk: {{ table_simple_name_zh }} ID
|
||||
:return:
|
||||
"""
|
||||
return await self.select_model(db, pk)
|
||||
|
||||
async def get_list(self) -> Select:
|
||||
"""获取{{ table_name_zh }}列表"""
|
||||
return await self.select_order('created_time', 'desc')
|
||||
|
||||
async def get_all(self, db: AsyncSession) -> Sequence[{{ table_name_class }}]:
|
||||
"""
|
||||
获取所有{{ table_name_zh }}
|
||||
|
||||
:param db: 数据库会话
|
||||
:return:
|
||||
"""
|
||||
return await self.select_models(db)
|
||||
|
||||
async def create(self, db: AsyncSession, obj: Create{{ schema_name }}Param) -> None:
|
||||
"""
|
||||
创建{{ table_name_zh }}
|
||||
|
||||
:param db: 数据库会话
|
||||
:param obj: 创建{{ table_simple_name_zh }} 参数
|
||||
:return:
|
||||
"""
|
||||
await self.create_model(db, obj)
|
||||
|
||||
async def update(self, db: AsyncSession, pk: int, obj: Update{{ schema_name }}Param) -> int:
|
||||
"""
|
||||
更新{{ table_name_zh }}
|
||||
|
||||
:param db: 数据库会话
|
||||
:param pk: {{ table_simple_name_zh }} ID
|
||||
:param obj: 更新 {{ table_simple_name_zh }} 参数
|
||||
:return:
|
||||
"""
|
||||
return await self.update_model(db, pk, obj)
|
||||
|
||||
async def delete(self, db: AsyncSession, pk: list[int]) -> int:
|
||||
"""
|
||||
删除{{ table_name_zh }}
|
||||
|
||||
:param db: 数据库会话
|
||||
:param pk: {{ table_simple_name_zh }} ID
|
||||
:return:
|
||||
"""
|
||||
return await self.delete_model_by_column(db, allow_multiple=True, id__in=pk)
|
||||
|
||||
|
||||
{{ table_name_en }}_dao: CRUD{{ table_name_class }} = CRUD{{ table_name_class }}({{ table_name_class }})
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
{% if database_type == 'mysql' -%}
|
||||
from sqlalchemy.dialects import mysql
|
||||
{% else -%}
|
||||
from sqlalchemy.dialects import postgresql
|
||||
{% endif -%}
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from backend.common.model import {% if default_datetime_column %}Base{% else %}MappedBase{% endif %}, id_key
|
||||
|
||||
|
||||
class {{ table_name_class }}({% if default_datetime_column %}Base{% else %}MappedBase{% endif %}):
|
||||
"""{{ table_name_zh }}"""
|
||||
|
||||
__tablename__ = '{{ table_name_en }}'
|
||||
|
||||
id: Mapped[id_key] = mapped_column(init=False)
|
||||
{% for model in models %}
|
||||
{{ model.name }}:
|
||||
{%- if model.is_nullable %} Mapped[{{ model.pd_type }} | None]
|
||||
{%- else %} Mapped[{{ model.pd_type }}]
|
||||
{%- endif %} = mapped_column(
|
||||
{%- if model.type in ['NVARCHAR', 'String', 'Unicode', 'VARCHAR'] -%}
|
||||
sa.String({{ model.length }})
|
||||
{%- elif database_type == 'mysql' and model.type in ['BIT', 'ENUM', 'LONGBLOB', 'LONGTEXT', 'MEDIUMBLOB',
|
||||
'MEDIUMINT', 'MEDIUMTEXT', 'SET', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'YEAR'] -%}
|
||||
mysql.{{ model.type }}()
|
||||
{%- elif database_type == 'postgresql' and model.type in [
|
||||
'ARRAY', 'BIT', 'BYTEA', 'CIDR', 'CITEXT', 'DATEMULTIRANGE', 'DATERANGE', 'DOMAIN', 'ENUM', 'HSTORE', 'INET',
|
||||
'INT4MULTIRANGE', 'INT4RANGE', 'INT8MULTIRANGE', 'INT8RANGE', 'INTERVAL', 'JSONB', 'JSONPATH', 'MACADDR',
|
||||
'MACADDR8', 'MONEY', 'NUMMULTIRANGE', 'NUMRANGE', 'OID', 'REGCLASS', 'REGCONFIG', 'TSMULTIRANGE', 'TSQUERY',
|
||||
'TSRANGE', 'TSTZMULTIRANGE', 'TSTZRANGE', 'TSVECTOR'] -%}
|
||||
{%- else -%}
|
||||
sa.{{ model.type }}()
|
||||
{%- endif -%}, default=
|
||||
{%- if model.is_nullable and model.default == None -%}
|
||||
None
|
||||
{%- else -%}
|
||||
{%- if model.default != None -%}
|
||||
'{{ model.default }}'
|
||||
{%- else -%}
|
||||
{%- if model.pd_type == 'str' -%}
|
||||
''
|
||||
{%- elif model.pd_type == 'int' -%}
|
||||
0
|
||||
{%- elif model.pd_type == 'bytes' -%}
|
||||
b''
|
||||
{%- elif model.pd_type == 'bool' -%}
|
||||
True
|
||||
{%- elif model.pd_type == 'float' -%}
|
||||
0.0
|
||||
{%- elif model.pd_type == 'dict' -%}
|
||||
{}
|
||||
{%- elif model.pd_type == 'date' or model.pd_type == 'datetime' -%}
|
||||
timezone.now()
|
||||
{%- elif model.pd_type == 'list[str]' -%}
|
||||
()
|
||||
{%- else -%}
|
||||
''
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- endif -%}{% if model.sort != 0 %}, sort_order={{ model.sort }}{% endif %}, comment=
|
||||
{%- if model.comment != None -%}
|
||||
'{{ model.comment }}')
|
||||
{% else -%}
|
||||
None)
|
||||
{%- endif -%}
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from backend.common.schema import SchemaBase
|
||||
|
||||
|
||||
class {{ schema_name }}SchemaBase(SchemaBase):
|
||||
"""{{ table_simple_name_zh }}基础模型"""
|
||||
{% for model in models %}
|
||||
{{ model.name }}: {% if model.nullable %}{{ model.pd_type }} | None = Field(None, description='{{ model.comment }}'){% else %}{{ model.pd_type }} = Field(description='{{ model.comment }}'){% endif %}
|
||||
|
||||
{% endfor %}
|
||||
|
||||
|
||||
class Create{{ schema_name }}Param({{ schema_name }}SchemaBase):
|
||||
"""创建{{ table_simple_name_zh }}参数"""
|
||||
|
||||
|
||||
class Update{{ schema_name }}Param({{ schema_name }}SchemaBase):
|
||||
"""更新{{ table_simple_name_zh }}参数"""
|
||||
|
||||
|
||||
class Get{{ schema_name }}Detail({{ schema_name }}SchemaBase):
|
||||
"""{{ table_simple_name_zh }}详情"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
{% if default_datetime_column %}
|
||||
created_time: datetime
|
||||
updated_time: datetime | None = None
|
||||
{% endif %}
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
from typing import Sequence
|
||||
|
||||
from sqlalchemy import Select
|
||||
|
||||
from backend.app.{{ app_name }}.crud.crud_{{ table_name_en }} import {{ table_name_en }}_dao
|
||||
from backend.app.{{ app_name }}.model import {{ table_name_class }}
|
||||
from backend.app.{{ app_name }}.schema.{{ table_name_en }} import Create{{ schema_name }}Param, Update{{ schema_name }}Param
|
||||
from backend.common.exception import errors
|
||||
from backend.database.db import async_db_session
|
||||
|
||||
|
||||
class {{ table_name_class }}Service:
|
||||
@staticmethod
|
||||
async def get(*, pk: int) -> {{ table_name_class }}:
|
||||
"""
|
||||
获取{{ table_simple_name_zh }}
|
||||
|
||||
:param pk: {{ table_simple_name_zh }} ID
|
||||
:return:
|
||||
"""
|
||||
async with async_db_session() as db:
|
||||
{{ table_name_en }} = await {{ table_name_en }}_dao.get(db, pk)
|
||||
if not {{ table_name_en }}:
|
||||
raise errors.NotFoundError(msg='{{ table_simple_name_zh }}不存在')
|
||||
return {{ table_name_en }}
|
||||
|
||||
@staticmethod
|
||||
async def get_select() -> Select:
|
||||
"""获取{{ table_simple_name_zh }}查询对象"""
|
||||
return await {{ table_name_en }}_dao.get_list()
|
||||
|
||||
@staticmethod
|
||||
async def get_all() -> Sequence[{{ table_name_class }}]:
|
||||
"""获取所有{{ table_simple_name_zh }}"""
|
||||
async with async_db_session() as db:
|
||||
{{ table_name_en }}s = await {{ table_name_en }}_dao.get_all(db)
|
||||
return {{ table_name_en }}s
|
||||
|
||||
@staticmethod
|
||||
async def create(*, obj: Create{{ schema_name }}Param) -> None:
|
||||
"""
|
||||
创建{{ table_simple_name_zh }}
|
||||
|
||||
:param obj: 创建{{ table_simple_name_zh }}参数
|
||||
:return:
|
||||
"""
|
||||
async with async_db_session.begin() as db:
|
||||
await {{ table_name_en }}_dao.create(db, obj)
|
||||
|
||||
@staticmethod
|
||||
async def update(*, pk: int, obj: Update{{ schema_name }}Param) -> int:
|
||||
"""
|
||||
更新{{ table_simple_name_zh }}
|
||||
|
||||
:param pk: {{ table_simple_name_zh }} ID
|
||||
:param obj: 更新{{ table_simple_name_zh }}参数
|
||||
:return:
|
||||
"""
|
||||
async with async_db_session.begin() as db:
|
||||
count = await {{ table_name_en }}_dao.update(db, pk, obj)
|
||||
return count
|
||||
|
||||
@staticmethod
|
||||
async def delete(*, pk: list[int]) -> int:
|
||||
"""
|
||||
删除{{ table_simple_name_zh }}
|
||||
|
||||
:param pk: {{ table_simple_name_zh }} ID 列表
|
||||
:return:
|
||||
"""
|
||||
async with async_db_session.begin() as db:
|
||||
count = await {{ table_name_en }}_dao.delete(db, pk)
|
||||
return count
|
||||
|
||||
|
||||
{{ table_name_en }}_service: {{ table_name_class }}Service = {{ table_name_class }}Service()
|
||||
Reference in New Issue
Block a user