9366a3218e182af424684796893ef4aff4bd0586
[pti/o2.git] / o2common / views / route.py
1 # Copyright (C) 2021-2022 Wind River Systems, Inc.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14
15 # -*- coding: utf-8 -*-
16 from __future__ import unicode_literals
17
18 # from collections import OrderedDict
19 from functools import wraps
20 # from six import iteritems
21
22 from flask import request
23
24 from flask_restx import Namespace
25 from flask_restx._http import HTTPStatus
26 from flask_restx.marshalling import marshal_with, marshal
27 from flask_restx.utils import merge
28 from flask_restx.mask import Mask  # , apply as apply_mask
29 from flask_restx.model import Model
30 from flask_restx.fields import List, Nested, String
31 from flask_restx.utils import unpack
32
33 from o2common.views.route_exception import BadRequestException
34
35 from o2common.helper import o2logging
36 logger = o2logging.get_logger(__name__)
37
38
39 class O2Namespace(Namespace):
40
41     def __init__(self, name, description=None, path=None, decorators=None,
42                  validate=None, authorizations=None, ordered=False, **kwargs):
43         super().__init__(name, description, path, decorators,
44                          validate, authorizations, ordered, **kwargs)
45
46     def marshal_with(
47         self, fields, as_list=False, code=HTTPStatus.OK, description=None,
48         **kwargs
49     ):
50         """
51         A decorator specifying the fields to use for serialization.
52
53         :param bool as_list: Indicate that the return type is a list \
54             (for the documentation)
55         :param int code: Optionally give the expected HTTP response \
56             code if its different from 200
57
58         """
59
60         def wrapper(func):
61             doc = {
62                 "responses": {
63                     str(code): (description, [fields], kwargs)
64                     if as_list
65                     else (description, fields, kwargs)
66                 },
67                 "__mask__": kwargs.get(
68                     "mask", True
69                 ),  # Mask values can't be determined outside app context
70             }
71             func.__apidoc__ = merge(getattr(func, "__apidoc__", {}), doc)
72             return o2_marshal_with(fields, ordered=self.ordered,
73                                    **kwargs)(func)
74
75         return wrapper
76
77
78 class o2_marshal_with(marshal_with):
79     def __init__(
80         self, fields, envelope=None, skip_none=False, mask=None, ordered=False
81     ):
82         """
83         :param fields: a dict of whose keys will make up the final
84                        serialized response output
85         :param envelope: optional key that will be used to envelop the
86                        serialized response
87         """
88         self.fields = fields
89         self.envelope = envelope
90         self.skip_none = skip_none
91         self.ordered = ordered
92         self.mask = Mask(mask, skip=True)
93
94     def __call__(self, f):
95         @wraps(f)
96         def wrapper(*args, **kwargs):
97             resp = f(*args, **kwargs)
98
99             req_args = request.args
100             mask = self._gen_mask_from_selector(**req_args)
101             if mask == '':
102                 mask = self.mask
103
104             # if has_request_context():
105             # mask_header = current_app.config["RESTX_MASK_HEADER"]
106             # mask = request.headers.get(mask_header) or mask
107             if isinstance(resp, tuple):
108                 data, code, headers = unpack(resp)
109                 return (
110                     marshal(
111                         data,
112                         self.fields,
113                         self.envelope,
114                         self.skip_none,
115                         mask,
116                         self.ordered,
117                     ),
118                     code,
119                     headers,
120                 )
121             else:
122                 return marshal(
123                     resp, self.fields, self.envelope, self.skip_none, mask,
124                     self.ordered
125                 )
126
127         return wrapper
128
129     def _gen_mask_from_selector(self, **kwargs) -> str:
130         mask_val = ''
131         if 'all_fields' in kwargs:
132             all_fields_without_space = kwargs['all_fields'].replace(" ", "")
133             logger.info('all_fields selector value is {}'.format(
134                 all_fields_without_space))
135             # all_fields = all_fields_without_space.lower()
136             # if 'true' == all_fields:
137             selector = self.__gen_selector_from_model_with_value(
138                 self.fields)
139             mask_val = self.__gen_mask_from_selector(selector)
140
141         elif 'fields' in kwargs and kwargs['fields'] != '':
142             fields_without_space = kwargs['fields'].replace(" ", "")
143
144             # filters = fields_without_space.split(',')
145
146             # mask_val_list = []
147             # for f in filters:
148             #     if '/' in f:
149             #         a = self.__gen_mask_tree(f)
150             #         mask_val_list.append(a)
151             #         continue
152             #     mask_val_list.append(f)
153             # mask_val = '{%s}' % ','.join(mask_val_list)
154             selector = {}
155
156             self.__update_selector_value(selector, fields_without_space, True)
157             self.__set_default_mask(selector)
158
159             mask_val = self.__gen_mask_from_selector(selector)
160
161         elif 'exclude_fields' in kwargs and kwargs['exclude_fields'] != '':
162             exclude_fields_without_space = kwargs['exclude_fields'].replace(
163                 " ", "")
164
165             selector = self.__gen_selector_from_model_with_value(
166                 self.fields)
167
168             self.__update_selector_value(
169                 selector, exclude_fields_without_space, False)
170             self.__set_default_mask(selector)
171
172             mask_val = self.__gen_mask_from_selector(selector)
173         elif 'exclude_default' in kwargs and kwargs['exclude_default'] != '':
174             exclude_default_without_space = kwargs['exclude_default'].replace(
175                 " ", "")
176             exclude_default = exclude_default_without_space.lower()
177             if 'true' == exclude_default:
178                 mask_val = '{}'
179
180         else:
181             mask_val = ''
182
183         return mask_val
184
185     def __gen_mask_tree(self, field: str) -> str:
186
187         f = field.split('/', 1)
188         if len(f) > 1:
189             s = self.__gen_mask_tree(f[1])
190             return '%s%s' % (f[0], s)
191         else:
192             return '{%s}' % f[0]
193
194     def __gen_selector_from_model_with_value(
195             self, model: Model, default_val: bool = True) -> dict:
196         selector = dict()
197         for i in model:
198             if type(model[i]) is List:
199                 if type(model[i].container) is String:
200                     selector[i] = default_val
201                     continue
202                 selector[i] = self.__gen_selector_from_model_with_value(
203                     model[i].container.model, default_val)
204                 continue
205             elif type(model[i]) is Nested:
206                 selector[i] = self.__gen_selector_from_model_with_value(
207                     model[i].model, default_val)
208             selector[i] = default_val
209         return selector
210
211     def __update_selector_value(self, selector: dict, filter: str,
212                                 val: bool):
213         fields = filter.split(',')
214         for f in fields:
215             if '/' in f:
216                 self.__update_selector_tree_value(selector, f, val)
217                 continue
218             if f not in self.fields:
219                 raise BadRequestException(
220                     'Selector attribute {} not found'.format(f))
221             selector[f] = val
222
223     def __update_selector_tree_value(self, m: dict, filter: str, val: bool):
224         filter_list = filter.split('/', 1)
225         if filter_list[0] not in m:
226             m[filter_list[0]] = dict()
227         if len(filter_list) > 1:
228             self.__update_selector_tree_value(
229                 m[filter_list[0]], filter_list[1], val)
230             return
231         m[filter_list[0]] = val
232
233     def __gen_mask_from_selector(self, fields: dict) -> str:
234         mask_li = list()
235         for k, v in fields.items():
236             if type(v) is dict:
237                 s = self.__gen_mask_from_selector(v)
238                 mask_li.append('%s%s' % (k, s))
239                 continue
240             if v:
241                 mask_li.append(k)
242
243         return '{%s}' % ','.join(mask_li)
244
245     def __set_default_mask(self, selector: dict, val: bool = True):
246         default_selector = str(getattr(self.fields, "__mask__"))[1:-1]
247         self.__update_selector_value(selector, default_selector, val)