44import uuid
55from abc import ABCMeta
66from collections import ChainMap
7- from typing import Any , List , Match , Optional , Tuple , Type , Union
7+ from typing import Any , Match , Optional , Tuple , Type
88
9- from django .db import models
109from django .http import HttpRequest
1110from ninja import ModelSchema
1211from ninja_extra import ControllerBase , http_delete , http_get , http_patch , http_put
1312from ninja_extra .pagination import paginate
1413
14+ from easy .controller .meta_conf import ModelOptions
1515from easy .domain .orm import CrudModel
1616from easy .response import BaseApiResponse
1717from easy .services import BaseService
2020logger = logging .getLogger (__name__ )
2121
2222
23- class APIControllerBase (ControllerBase ):
24- """Reserved for customization"""
25-
26- ...
27-
28-
2923class CrudAPI (CrudModel ):
3024 # Never add type note to service, it will cause injection error
3125 def __init__ (self , service = None ): # type: ignore
3226 # Critical to set __Meta
3327 self .service = service
3428 if self .service :
3529 self .model = self .service .model
36- _meta = getattr (self , "Meta" , None )
37- if self .model and _meta :
38- setattr (
39- self .model ,
40- "__Meta" ,
41- {
42- "generate_crud" : getattr (_meta , "generate_crud" , True ),
43- "model_exclude" : getattr (_meta , "model_exclude" , None ),
44- "model_fields" : getattr (_meta , "model_fields" , "__all__" ),
45- "model_recursive" : getattr (_meta , "model_recursive" , False ),
46- "model_join" : getattr (_meta , "model_join" , True ),
47- "sensitive_fields" : getattr (
48- _meta , "model_sensitive_fields" , ["password" , "token" ]
49- ),
50- },
51- )
30+
31+ _model_opts : ModelOptions = ModelOptions .get_model_options (self .__class__ )
32+ if self .model and _model_opts :
33+ ModelOptions .set_model_meta (self .model , _model_opts )
34+
5235 if not service :
5336 self .service = BaseService (model = self .model )
5437 super ().__init__ (model = self .model )
@@ -70,17 +53,8 @@ def is_private_attrs(attr_name: str) -> Optional[Match[str]]:
7053 base_cls_attrs .update (parent_attrs )
7154
7255 # Get configs from Meta
73- temp_cls : Type = super ().__new__ (mcs , name , (object ,), base_cls_attrs )
74- temp_opts : ModelOptions = ModelOptions (getattr (temp_cls , "Meta" , None ))
75- opts_model : Optional [Type [models .Model ]] = temp_opts .model
76- opts_generate_crud : Optional [bool ] = temp_opts .generate_crud
77- opts_fields_exclude : Optional [str ] = temp_opts .model_exclude
78- opts_fields : Optional [str ] = temp_opts .model_fields
79- opts_recursive : Optional [bool ] = temp_opts .model_recursive
80- opts_join : Optional [bool ] = temp_opts .model_join
81- opts_sensitive_fields : Optional [
82- Union [str , List [str ]]
83- ] = temp_opts .sensitive_fields
56+ _temp_cls : Type = super ().__new__ (mcs , name , (object ,), base_cls_attrs )
57+ model_opts : ModelOptions = ModelOptions .get_model_options (_temp_cls )
8458
8559 # Define Controller APIs for auto generation
8660 async def get_obj (self , request : HttpRequest , id : int ) -> Any : # type: ignore
@@ -118,7 +92,7 @@ async def get_objs(self, request: HttpRequest, filters: str = None) -> Any: # t
11892 return await self .service .get_objs (** json .loads (filters ))
11993 return await self .service .get_objs ()
12094
121- if opts_generate_crud and opts_model :
95+ if model_opts . generate_crud and model_opts . model :
12296 base_cls_attrs .update (
12397 {
12498 "get_obj" : http_get ("/{id}" , summary = "Get a single object" )(
@@ -135,14 +109,18 @@ async def get_objs(self, request: HttpRequest, filters: str = None) -> Any: # t
135109
136110 class DataSchema (ModelSchema ):
137111 class Config :
138- model = opts_model
139- if opts_fields_exclude :
140- model_exclude = opts_fields_exclude
112+ model = model_opts . model
113+ if model_opts . model_exclude :
114+ model_exclude = model_opts . model_exclude
141115 else :
142- if opts_fields == "__all__" :
116+ if model_opts . model_fields == "__all__" :
143117 model_fields = "__all__"
144118 else :
145- model_fields = opts_fields if opts_fields else "__all__"
119+ model_fields = (
120+ model_opts .model_fields
121+ if model_opts .model_fields
122+ else "__all__"
123+ )
146124
147125 async def add_obj ( # type: ignore
148126 self , request : HttpRequest , data : DataSchema
@@ -170,7 +148,7 @@ async def patch_obj( # type: ignore
170148 return BaseApiResponse ("Update Failed" , errno = 400 )
171149
172150 DataSchema .__name__ = (
173- f"{ opts_model .__name__ } __AutoSchema({ str (uuid .uuid4 ())[:4 ]} )"
151+ f"{ model_opts . model .__name__ } __AutoSchema({ str (uuid .uuid4 ())[:4 ]} )"
174152 )
175153
176154 base_cls_attrs .update (
@@ -188,49 +166,14 @@ async def patch_obj( # type: ignore
188166 mcs ,
189167 name ,
190168 (
191- APIControllerBase ,
169+ ControllerBase ,
192170 CrudAPI ,
193171 ),
194172 base_cls_attrs ,
195173 )
196174
197- if opts_model :
198- setattr (
199- opts_model ,
200- "__Meta" ,
201- {
202- "generate_crud" : opts_generate_crud ,
203- "model_exclude" : opts_fields_exclude ,
204- "model_fields" : opts_fields ,
205- "model_recursive" : opts_recursive ,
206- "model_join" : opts_join ,
207- "sensitive_fields" : opts_sensitive_fields ,
208- },
209- )
210- setattr (new_cls , "model" , opts_model )
175+ if model_opts .model :
176+ ModelOptions .set_model_meta (model_opts .model , model_opts )
177+ setattr (new_cls , "model" , model_opts .model )
211178
212179 return new_cls
213-
214-
215- class ModelOptions :
216- def __init__ (self , options : object = None ):
217- """
218- Configuration reader
219- """
220- self .model : Optional [Type [models .Model ]] = getattr (options , "model" , None )
221- self .generate_crud : Optional [Union [bool ]] = getattr (
222- options , "generate_crud" , True
223- )
224- self .model_exclude : Optional [Union [str ]] = getattr (
225- options , "model_exclude" , None
226- )
227- self .model_fields : Optional [Union [str ]] = getattr (
228- options , "model_fields" , "__all__"
229- )
230- self .model_join : Optional [Union [bool ]] = getattr (options , "model_join" , True )
231- self .model_recursive : Optional [Union [bool ]] = getattr (
232- options , "model_recursive" , False
233- )
234- self .sensitive_fields : Optional [Union [str , List [str ]]] = getattr (
235- options , "sensitive_fields" , ["token" , "password" ]
236- )
0 commit comments