4
4
import uuid
5
5
from abc import ABCMeta
6
6
from collections import ChainMap
7
- from typing import Any , List , Match , Optional , Tuple , Type , Union
7
+ from typing import Any , Match , Optional , Tuple , Type
8
8
9
- from django .db import models
10
9
from django .http import HttpRequest
11
10
from ninja import ModelSchema
12
11
from ninja_extra import ControllerBase , http_delete , http_get , http_patch , http_put
13
12
from ninja_extra .pagination import paginate
14
13
14
+ from easy .controller .meta_conf import ModelOptions
15
15
from easy .domain .orm import CrudModel
16
16
from easy .response import BaseApiResponse
17
17
from easy .services import BaseService
20
20
logger = logging .getLogger (__name__ )
21
21
22
22
23
- class APIControllerBase (ControllerBase ):
24
- """Reserved for customization"""
25
-
26
- ...
27
-
28
-
29
23
class CrudAPI (CrudModel ):
30
24
# Never add type note to service, it will cause injection error
31
25
def __init__ (self , service = None ): # type: ignore
32
26
# Critical to set __Meta
33
27
self .service = service
34
28
if self .service :
35
29
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
+
52
35
if not service :
53
36
self .service = BaseService (model = self .model )
54
37
super ().__init__ (model = self .model )
@@ -70,17 +53,8 @@ def is_private_attrs(attr_name: str) -> Optional[Match[str]]:
70
53
base_cls_attrs .update (parent_attrs )
71
54
72
55
# 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 )
84
58
85
59
# Define Controller APIs for auto generation
86
60
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
118
92
return await self .service .get_objs (** json .loads (filters ))
119
93
return await self .service .get_objs ()
120
94
121
- if opts_generate_crud and opts_model :
95
+ if model_opts . generate_crud and model_opts . model :
122
96
base_cls_attrs .update (
123
97
{
124
98
"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
135
109
136
110
class DataSchema (ModelSchema ):
137
111
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
141
115
else :
142
- if opts_fields == "__all__" :
116
+ if model_opts . model_fields == "__all__" :
143
117
model_fields = "__all__"
144
118
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
+ )
146
124
147
125
async def add_obj ( # type: ignore
148
126
self , request : HttpRequest , data : DataSchema
@@ -170,7 +148,7 @@ async def patch_obj( # type: ignore
170
148
return BaseApiResponse ("Update Failed" , errno = 400 )
171
149
172
150
DataSchema .__name__ = (
173
- f"{ opts_model .__name__ } __AutoSchema({ str (uuid .uuid4 ())[:4 ]} )"
151
+ f"{ model_opts . model .__name__ } __AutoSchema({ str (uuid .uuid4 ())[:4 ]} )"
174
152
)
175
153
176
154
base_cls_attrs .update (
@@ -188,49 +166,14 @@ async def patch_obj( # type: ignore
188
166
mcs ,
189
167
name ,
190
168
(
191
- APIControllerBase ,
169
+ ControllerBase ,
192
170
CrudAPI ,
193
171
),
194
172
base_cls_attrs ,
195
173
)
196
174
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 )
211
178
212
179
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