-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy path__init__.py
2161 lines (1962 loc) · 74.9 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import json
import logging
import re
import traceback
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Set,
Tuple,
Type,
TYPE_CHECKING,
Union,
)
import urllib.parse
from apispec import APISpec, yaml_utils
from apispec.exceptions import DuplicateComponentNameError
from flask import Blueprint, current_app, jsonify, make_response, request, Response
from flask_appbuilder.models.sqla import Model
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import lazy_gettext as _
import jsonschema
from marshmallow import Schema, ValidationError
from marshmallow.fields import Field
from marshmallow_sqlalchemy.fields import Related, RelatedList
import prison
from sqlalchemy.exc import IntegrityError
from werkzeug.exceptions import BadRequest
import yaml
from .convert import Model2SchemaConverter
from .schemas import get_info_schema, get_item_schema, get_list_schema
from .._compat import as_unicode
from ..baseviews import AbstractViewApi
from ..const import (
API_ADD_COLUMNS_RES_KEY,
API_ADD_COLUMNS_RIS_KEY,
API_ADD_TITLE_RES_KEY,
API_ADD_TITLE_RIS_KEY,
API_DESCRIPTION_COLUMNS_RES_KEY,
API_DESCRIPTION_COLUMNS_RIS_KEY,
API_EDIT_COLUMNS_RES_KEY,
API_EDIT_COLUMNS_RIS_KEY,
API_EDIT_TITLE_RES_KEY,
API_EDIT_TITLE_RIS_KEY,
API_FILTERS_RES_KEY,
API_FILTERS_RIS_KEY,
API_LABEL_COLUMNS_RES_KEY,
API_LABEL_COLUMNS_RIS_KEY,
API_LIST_COLUMNS_RES_KEY,
API_LIST_COLUMNS_RIS_KEY,
API_LIST_TITLE_RES_KEY,
API_LIST_TITLE_RIS_KEY,
API_ORDER_COLUMN_RIS_KEY,
API_ORDER_COLUMNS_RES_KEY,
API_ORDER_COLUMNS_RIS_KEY,
API_ORDER_DIRECTION_RIS_KEY,
API_PAGE_INDEX_RIS_KEY,
API_PAGE_SIZE_RIS_KEY,
API_PERMISSIONS_RES_KEY,
API_PERMISSIONS_RIS_KEY,
API_RESULT_RES_KEY,
API_SELECT_COLUMNS_RIS_KEY,
API_SELECT_SEL_COLUMNS_RIS_KEY,
API_SHOW_COLUMNS_RES_KEY,
API_SHOW_COLUMNS_RIS_KEY,
API_SHOW_TITLE_RES_KEY,
API_SHOW_TITLE_RIS_KEY,
API_URI_RIS_KEY,
PERMISSION_PREFIX,
)
from ..exceptions import FABException, InvalidOrderByColumnFABException
from ..hooks import get_before_request_hooks, wrap_route_handler_with_hooks
from ..models.filters import Filters
from ..security.decorators import permission_name, protect
from ..utils.limit import Limit
if TYPE_CHECKING:
from flask_appbuilder import AppBuilder
log = logging.getLogger(__name__)
ModelKeyType = Union[str, int]
QueryRelatedFieldsFilters = Dict[str, List[List[Any]]]
def get_error_msg() -> str:
"""
(inspired on Superset code)
:return: (str)
"""
if current_app.config.get("FAB_API_SHOW_STACKTRACE"):
return traceback.format_exc()
return "Fatal error"
def safe(f: Callable[..., Any]) -> Callable[..., Any]:
"""
A decorator that catches uncaught exceptions and
return the response in JSON format (inspired on Superset code)
"""
def wraps(self: "BaseApi", *args: Any, **kwargs: Any) -> Response:
try:
return f(self, *args, **kwargs)
except BadRequest as e:
return self.response_400(message=str(e))
except Exception as e:
log.exception(e)
return self.response_500(message=get_error_msg())
return functools.update_wrapper(wraps, f)
def rison(
schema: Optional[Dict[str, Any]] = None
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""
Use this decorator to parse URI *Rison* arguments to
a python data structure, your method gets the data
structure on kwargs['rison']. Response is HTTP 400
if *Rison* is not correct::
class ExampleApi(BaseApi):
@expose('/risonjson')
@rison()
def rison_json(self, **kwargs):
return self.response(200, result=kwargs['rison'])
You can additionally pass a JSON schema to
validate Rison arguments::
schema = {
"type": "object",
"properties": {
"arg1": {
"type": "integer"
}
}
}
class ExampleApi(BaseApi):
@expose('/risonjson')
@rison(schema)
def rison_json(self, **kwargs):
return self.response(200, result=kwargs['rison'])
"""
def _rison(f: Callable[..., Any]) -> Callable[..., Any]:
def wraps(self: "BaseApi", *args: Any, **kwargs: Any) -> Response:
value = request.args.get(API_URI_RIS_KEY, None)
kwargs["rison"] = dict()
if value:
try:
kwargs["rison"] = prison.loads(value)
except prison.decoder.ParserException:
if current_app.config.get("FAB_API_ALLOW_JSON_QS", True):
# Rison failed try json encoded content
try:
kwargs["rison"] = json.loads(
urllib.parse.parse_qs(f"{API_URI_RIS_KEY}={value}").get(
API_URI_RIS_KEY
)[0]
)
except Exception:
return self.response_400(
message="Not a valid rison/json argument"
)
else:
return self.response_400(message="Not a valid rison argument")
if schema:
try:
jsonschema.validate(instance=kwargs["rison"], schema=schema)
except jsonschema.ValidationError as e:
return self.response_400(message=f"Not a valid rison schema {e}")
return f(self, *args, **kwargs)
return functools.update_wrapper(wraps, f)
return _rison
def expose(url: str = "/", methods: Tuple[str] = ("GET",)) -> Callable[..., Any]:
"""
Use this decorator to expose API endpoints on your API classes.
:param url:
Relative URL for the endpoint
:param methods:
Allowed HTTP methods. By default only GET is allowed.
"""
def wrap(f: Callable[..., Any]) -> Callable[..., Any]:
if not hasattr(f, "_urls"):
f._urls = [] # type: ignore
f._urls.append((url, methods)) # type: ignore
return f
return wrap
def merge_response_func(func: Callable[..., Any], key: str) -> Callable[..., Any]:
"""
Use this decorator to set a new merging
response function to HTTP endpoints
candidate function must have the following signature
and be childs of BaseApi:
```
def merge_some_function(self, response, rison_args):
```
:param func: Name of the merge function where the key is allowed
:param key: The key name for rison selection
:return: None
"""
def wrap(f: Callable[..., Any]) -> Callable[..., Any]:
if not hasattr(f, "_response_key_func_mappings"):
f._response_key_func_mappings = {} # type: ignore
f._response_key_func_mappings[key] = func # type: ignore
return f
return wrap
class BaseApi(AbstractViewApi):
"""
All apis inherit from this class.
it's constructor will register your exposed urls on flask
as a Blueprint.
This class does not expose any urls,
but provides a common base for all APIS.
"""
endpoint: Optional[str] = None
version: Optional[str] = "v1"
"""
Define the Api version for this resource/class
"""
route_base: Optional[str] = None
"""
Define the route base where all methods will suffix from
"""
resource_name: Optional[str] = None
"""
Defines a custom resource name, overrides the inferred from Class name
makes no sense to use it with route base
"""
base_permissions: Optional[List[str]] = None
"""
A list of allowed base permissions::
class ExampleApi(BaseApi):
base_permissions = ['can_get']
"""
class_permission_name: Optional[str] = None
"""
Override class permission name default fallback to self.__class__.__name__
"""
previous_class_permission_name: Optional[str] = None
"""
If set security converge will replace all permissions tuples
with this name by the class_permission_name or self.__class__.__name__
"""
method_permission_name: Optional[Dict[str, str]] = None
"""
Override method permission names, example::
method_permissions_name = {
'get_list': 'read',
'get': 'read',
'put': 'write',
'post': 'write',
'delete': 'write'
}
"""
previous_method_permission_name: Optional[Dict[str, str]] = None
"""
Use same structure as method_permission_name. If set security converge
will replace all method permissions by the new ones
"""
allow_browser_login = False
"""
Will allow flask-login cookie authorization on the API
default is False.
"""
csrf_exempt = True
"""
If using flask-wtf CSRFProtect exempt the API from check
"""
apispec_parameter_schemas: Optional[Dict[str, Dict[str, Any]]] = None
"""
Set your custom Rison parameter schemas here so that
they get registered on the OpenApi spec::
custom_parameter = {
"type": "object"
"properties": {
"name": {
"type": "string"
}
}
}
class CustomApi(BaseApi):
apispec_parameter_schemas = {
"custom_parameter": custom_parameter
}
"""
_apispec_parameter_schemas: Optional[Dict[str, Dict[str, Any]]] = None
openapi_spec_component_schemas: Tuple[Type[Schema], ...] = tuple()
"""
A Tuple containing marshmallow schemas to be registered on the OpenAPI spec
has component schemas, these can be referenced by the endpoint's spec like:
`$ref: '#/components/schemas/MyCustomSchema'` Where MyCustomSchema is the
marshmallow schema class name.
To set your own OpenAPI schema component name, declare your schemas with:
__component_name__
class Schema1(Schema):
__component_name__ = "MyCustomSchema"
id = fields.Integer()
...
"""
responses = {
"400": {
"description": "Bad request",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {"message": {"type": "string"}},
}
}
},
},
"401": {
"description": "Unauthorized",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {"message": {"type": "string"}},
}
}
},
},
"403": {
"description": "Forbidden",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {"message": {"type": "string"}},
}
}
},
},
"404": {
"description": "Not found",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {"message": {"type": "string"}},
}
}
},
},
"422": {
"description": "Could not process entity",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {"message": {"type": "string"}},
}
}
},
},
"500": {
"description": "Fatal error",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {"message": {"type": "string"}},
}
}
},
},
}
"""
Override custom OpenApi responses
"""
exclude_route_methods: Set[str] = set()
"""
Does not register routes for a set of builtin ModelRestApi functions.
example::
class ContactModelView(ModelRestApi):
datamodel = SQLAInterface(Contact)
exclude_route_methods = {"info", "get_list", "get"}
The previous examples will only register the `put`, `post` and `delete` routes
"""
include_route_methods: Optional[Set[str]] = None
"""
If defined will assume a white list setup, where all endpoints are excluded
except those define on this attribute
example::
class ContactModelView(ModelRestApi):
datamodel = SQLAInterface(Contact)
include_route_methods = {"list"}
The previous example will exclude all endpoints except the `list` endpoint
"""
openapi_spec_methods: Dict[str, Any] = {}
"""
Merge OpenAPI spec defined on the method's doc.
For example to merge/override `get_list`::
class GreetingApi(BaseApi):
resource_name = "greeting"
openapi_spec_methods = {
"greeting": {
"get": {
"description": "Override description",
}
}
}
"""
openapi_spec_tag: Optional[str] = None
"""
By default all endpoints will be tagged (grouped) to their class name.
Use this attribute to override the tag name
"""
limits: Optional[List[Limit]] = None
"""
List of limits for this api.
Use it like this if you want to restrict the rate of requests to a view::
class MyView(ModelView):
limits = [Limit("2 per 5 second")]
or use the decorator @limit.
"""
def __init__(self) -> None:
"""
Initialization of base permissions
based on exposed methods and actions
Initialization of extra args
"""
self.appbuilder = None
self.blueprint = None
# Init OpenAPI
self._response_key_func_mappings: Dict[str, Any] = {}
self.apispec_parameter_schemas = self.apispec_parameter_schemas or {}
self._apispec_parameter_schemas = self._apispec_parameter_schemas or {}
self._apispec_parameter_schemas.update(self.apispec_parameter_schemas)
if self.openapi_spec_component_schemas is None:
self.openapi_spec_component_schemas = ()
# Init class permission override attrs
if not self.previous_class_permission_name and self.class_permission_name:
self.previous_class_permission_name = self.__class__.__name__
self.class_permission_name = (
self.class_permission_name or self.__class__.__name__
)
# Init previous permission override attrs
is_collect_previous = False
if not self.previous_method_permission_name and self.method_permission_name:
self.previous_method_permission_name = dict()
is_collect_previous = True
self.method_permission_name = self.method_permission_name or dict()
# Collect base_permissions and infer previous permissions
is_add_base_permissions = False
if self.base_permissions is None:
self.base_permissions = set()
is_add_base_permissions = True
if self.limits is None:
self.limits = []
for attr_name in dir(self):
if hasattr(getattr(self, attr_name), "_limit"):
self.limits.append(getattr(getattr(self, attr_name), "_limit"))
# If include_route_methods is not None white list
if (
self.include_route_methods is not None
and attr_name not in self.include_route_methods
):
continue
# Don't create permission for excluded routes
if attr_name in self.exclude_route_methods:
continue
if hasattr(getattr(self, attr_name), "_permission_name"):
if is_collect_previous:
self.previous_method_permission_name[attr_name] = getattr(
getattr(self, attr_name), "_permission_name"
)
_permission_name = self.get_method_permission(attr_name)
if is_add_base_permissions:
self.base_permissions.add(PERMISSION_PREFIX + _permission_name)
self.base_permissions = list(self.base_permissions)
def create_blueprint(
self,
appbuilder: "AppBuilder",
endpoint: Optional[str] = None,
static_folder: Optional[str] = None,
) -> Blueprint:
# Store appbuilder instance
self.appbuilder = appbuilder
# If endpoint name is not provided, get it from the class name
self.endpoint = endpoint or self.__class__.__name__
self.resource_name = self.resource_name or self.__class__.__name__.lower()
if self.route_base is None:
self.route_base = f"/api/{self.version}/{self.resource_name.lower()}"
self.blueprint = Blueprint(self.endpoint, __name__, url_prefix=self.route_base)
# Exempt API from CSRF protect
if self.csrf_exempt:
csrf = self.appbuilder.app.extensions.get("csrf")
if csrf:
csrf.exempt(self.blueprint)
self._register_urls()
return self.blueprint
def add_api_spec(self, api_spec: APISpec) -> None:
self.add_apispec_components(api_spec)
for attr_name in dir(self):
attr = getattr(self, attr_name)
if hasattr(attr, "_urls"):
for url, methods in attr._urls:
# If include_route_methods is not None white list
if (
self.include_route_methods is not None
and attr_name not in self.include_route_methods
):
continue
if attr_name in self.exclude_route_methods:
log.info("Not registering api spec for method %s", attr_name)
continue
operations = {}
path = self.path_helper(path=url, operations=operations)
self.operation_helper(
path=path, operations=operations, methods=methods, func=attr
)
api_spec.path(path=path, operations=operations)
for operation in operations:
openapi_spec_tag = (
self.openapi_spec_tag or self.__class__.__name__
)
api_spec._paths[path][operation]["tags"] = [openapi_spec_tag]
def add_apispec_components(self, api_spec: APISpec) -> None:
for k, v in self.responses.items():
try:
api_spec.components.response(k, v)
except DuplicateComponentNameError:
pass
for k, v in self._apispec_parameter_schemas.items():
try:
api_spec.components.schema(k, v)
except DuplicateComponentNameError:
pass
for schema in self.openapi_spec_component_schemas:
try:
if hasattr(schema, "__component_name__"):
component_name = schema.__component_name__
elif isinstance(schema, type):
component_name = schema.__name__
else:
component_name = schema.__class__.__name__
api_spec.components.schema(component_name, schema=schema)
except DuplicateComponentNameError:
pass
def _register_urls(self) -> None:
before_request_hooks = get_before_request_hooks(self)
for attr_name in dir(self):
if (
self.include_route_methods is not None
and attr_name not in self.include_route_methods
):
continue
if attr_name in self.exclude_route_methods:
log.info("Not registering route for method %s", attr_name)
continue
attr = getattr(self, attr_name)
if hasattr(attr, "_urls"):
for url, methods in attr._urls:
log.info(
"Registering route %s%s %s",
self.blueprint.url_prefix,
url,
methods,
)
route_handler = wrap_route_handler_with_hooks(
attr_name, attr, before_request_hooks
)
self.blueprint.add_url_rule(
url, attr_name, route_handler, methods=methods
)
def path_helper(
self,
path: str = None,
operations: Optional[Dict[str, Dict]] = None,
**kwargs: Any,
) -> str:
"""
Works like an apispec plugin
May return a path as string and mutate operations dict.
:param str path: Path to the resource
:param dict operations: A `dict` mapping HTTP methods to operation object. See
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
:param kwargs:
:return: Return value should be a string or None. If a string is returned, it
is set as the path.
"""
RE_URL = re.compile(r"<(?:[^:<>]+:)?([^<>]+)>")
path = RE_URL.sub(r"{\1}", path)
return f"{self.route_base}{path}"
def operation_helper(
self,
path: Optional[str] = None,
operations: Dict[str, Any] = None,
methods: List[str] = None,
func: Callable[..., Response] = None,
**kwargs: Any,
) -> None:
"""May mutate operations.
:param str path: Path to the resource
:param dict operations: A `dict` mapping HTTP methods to operation object.
:param list methods: A list of HTTP methods registered for this path
"""
for method in methods:
try:
# Check if method openapi spec is overridden
override_method_spec = self.openapi_spec_methods[func.__name__]
except KeyError:
override_method_spec = {}
yaml_doc_string = yaml_utils.load_operations_from_docstring(func.__doc__)
yaml_doc_string = yaml.safe_load(
str(yaml_doc_string).replace(
"{{self.__class__.__name__}}", self.__class__.__name__
)
)
if yaml_doc_string:
operation_spec = yaml_doc_string.get(method.lower(), {})
# Merge docs spec and override spec
operation_spec.update(override_method_spec.get(method.lower(), {}))
if self.get_method_permission(func.__name__):
operation_spec["security"] = [{"jwt": []}]
operations[method.lower()] = operation_spec
else:
operations[method.lower()] = {}
@staticmethod
def _prettify_name(name: str) -> str:
"""
Prettify pythonic variable name.
For example, 'HelloWorld' will be converted to 'Hello World'
:param name:
Name to prettify.
"""
return re.sub(r"(?<=.)([A-Z])", r" \1", name)
@staticmethod
def _prettify_column(name: str) -> str:
"""
Prettify pythonic variable name.
For example, 'hello_world' will be converted to 'Hello World'
:param name:
Name to prettify.
"""
return re.sub("[._]", " ", name).title()
def get_uninit_inner_views(self) -> List[Type[AbstractViewApi]]:
"""
Will return a list with views that need to be initialized.
Normally related_views from ModelView
"""
return []
def get_init_inner_views(self) -> List[AbstractViewApi]:
"""
Sets initialized inner views
"""
pass # pragma: no cover
def get_method_permission(self, method_name: str) -> str:
"""
Returns the permission name for a method
"""
if self.method_permission_name:
return self.method_permission_name.get(method_name, method_name)
else:
if hasattr(getattr(self, method_name), "_permission_name"):
return getattr(getattr(self, method_name), "_permission_name")
def set_response_key_mappings(
self,
response: Dict[str, Any],
func: Callable[..., Response],
rison_args: Dict[str, Any],
**kwargs: Any,
) -> None:
if not hasattr(func, "_response_key_func_mappings"):
return # pragma: no cover
_keys = rison_args.get("keys", None)
if not _keys:
for k, v in func._response_key_func_mappings.items():
v(self, response, **kwargs)
else:
for k, v in func._response_key_func_mappings.items():
if k in _keys:
v(self, response, **kwargs)
def merge_current_user_permissions(
self, response: Dict[str, Any], **kwargs: Any
) -> None:
response[API_PERMISSIONS_RES_KEY] = [
permission
for permission in self.base_permissions
if self.appbuilder.sm.has_access(permission, self.class_permission_name)
]
@staticmethod
def response(code: int, **kwargs: Any) -> Response:
"""
Generic HTTP JSON response method
:param code: HTTP code (int)
:param kwargs: Data structure for response (dict)
:return: HTTP Json response
"""
_ret_json = jsonify(kwargs)
resp = make_response(_ret_json, code)
resp.headers["Content-Type"] = "application/json; charset=utf-8"
return resp
def response_400(self, message: str = None) -> Response:
"""
Helper method for HTTP 400 response
:param message: Error message (str)
:return: HTTP Json response
"""
message = message or "Arguments are not correct"
return self.response(400, **{"message": message})
def response_422(self, message: str = None) -> Response:
"""
Helper method for HTTP 422 response
:param message: Error message (str)
:return: HTTP Json response
"""
message = message or "Could not process entity"
return self.response(422, **{"message": message})
def response_401(self) -> Response:
"""
Helper method for HTTP 401 response
:param message: Error message (str)
:return: HTTP Json response
"""
return self.response(401, **{"message": "Not authorized"})
def response_403(self) -> Response:
"""
Helper method for HTTP 403 response
:param message: Error message (str)
:return: HTTP Json response
"""
return self.response(403, **{"message": "Forbidden"})
def response_404(self) -> Response:
"""
Helper method for HTTP 404 response
:param message: Error message (str)
:return: HTTP Json response
"""
return self.response(404, **{"message": "Not found"})
def response_500(self, message: str = None) -> Response:
"""
Helper method for HTTP 500 response
:param message: Error message (str)
:return: HTTP Json response
"""
message = message or "Internal error"
return self.response(500, **{"message": message})
class BaseModelApi(BaseApi):
datamodel: Optional[SQLAInterface] = None
"""
Your sqla model you must initialize it like::
class MyModelApi(BaseModelApi):
datamodel = SQLAInterface(MyTable)
"""
search_columns = None
"""
List with allowed search columns, if not provided all possible search
columns will be used. If you want to limit the search (*filter*) columns
possibilities, define it with a list of column names from your model::
class MyView(ModelRestApi):
datamodel = SQLAInterface(MyTable)
search_columns = ['name', 'address']
"""
search_filters = None
"""
Override default search filters for columns
"""
search_exclude_columns = None
"""
List with columns to exclude from search. Search includes all possible
columns by default
"""
label_columns = None
"""
Dictionary of labels for your columns, override this if you want
different pretify labels
example (will just override the label for name column)::
class MyView(ModelRestApi):
datamodel = SQLAInterface(MyTable)
label_columns = {'name':'My Name Label Override'}
"""
base_filters = None
"""
Filter the view use: [['column_name',BaseFilter,'value'],]
example::
def get_user():
return g.user
class MyView(ModelRestApi):
datamodel = SQLAInterface(MyTable)
base_filters = [['created_by', FilterEqualFunction, get_user],
['name', FilterStartsWith, 'a']]
"""
base_order = None
"""
Use this property to set default ordering for lists
('col_name','asc|desc')::
class MyView(ModelRestApi):
datamodel = SQLAInterface(MyTable)
base_order = ('my_column_name','asc')
"""
_base_filters = None
""" Internal base Filter from class Filters will always filter view """
_filters = None
"""
Filters object will calculate all possible filter types
based on search_columns
"""
def __init__(self, **kwargs: Any) -> None:
datamodel = kwargs.get("datamodel", None)
if datamodel:
self.datamodel = datamodel
self._init_properties()
self._init_titles()
super(BaseModelApi, self).__init__()
def _gen_labels_columns(self, list_columns: List[str]) -> None:
"""
Auto generates pretty label_columns from list of columns
"""
for col in list_columns:
if not self.label_columns.get(col):
self.label_columns[col] = self._prettify_column(col)
def _label_columns_json(self, cols: Optional[List[str]] = None) -> Dict[str, Any]:
"""
Prepares dict with labels to be JSON serializable
"""
ret = {}
cols = cols or []
d = {k: v for (k, v) in self.label_columns.items() if k in cols}
for key, value in d.items():
ret[key] = as_unicode(_(value).encode("UTF-8"))
return ret
def _init_properties(self) -> None:
self.label_columns = self.label_columns or {}
self.base_filters = self.base_filters or []
self.search_exclude_columns = self.search_exclude_columns or []
self.search_columns = self.search_columns or []
self._base_filters = self.datamodel.get_filters().add_filter_list(
self.base_filters
)
search_columns = self.datamodel.get_search_columns_list()
if not self.search_columns:
self.search_columns = [
x for x in search_columns if x not in self.search_exclude_columns
]
self._gen_labels_columns(self.datamodel.get_columns_list())
def _init_titles(self) -> None:
pass
class ModelRestApi(BaseModelApi):
list_title = ""
"""
List Title, if not configured the default is
'List ' with pretty model name
"""
show_title: Optional[str] = ""
"""
Show Title , if not configured the default is
'Show ' with pretty model name
"""
add_title: Optional[str] = ""
"""
Add Title , if not configured the default is
'Add ' with pretty model name
"""
edit_title: Optional[str] = ""
"""
Edit Title , if not configured the default is
'Edit ' with pretty model name
"""
list_select_columns: Optional[List[str]] = None
"""
A List of column names that will be included on the SQL select.
This is useful for including all necessary columns that are referenced
by properties listed on `list_columns` without generating N+1 queries.
"""
list_outer_default_load = False
"""
If True, the default load for outer joins will be applied on the get item endpoint.
This is useful for when you want to control the load of the many-to-many and
many-to-one relationships at the model level. Will apply:
https://docs.sqlalchemy.org/en/14/orm/loading_relationships.html#sqlalchemy.orm.Load.defaultload
"""
list_columns: Optional[List[str]] = None
"""
A list of columns (or model's methods) to be displayed on the list view.
Use it to control the order of the display
"""
show_select_columns: Optional[List[str]] = None
"""
A List of column names that will be included on the SQL select.
This is useful for including all necessary columns that are referenced
by properties listed on `show_columns` without generating N+1 queries.