1 # Copyright (C) 2021-2022 Wind River Systems, Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # -*- coding: utf-8 -*-
16 from __future__ import unicode_literals
18 # from collections import OrderedDict
19 from functools import wraps
20 # from six import iteritems
22 from flask import request
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
33 from o2common.views.route_exception import BadRequestException
35 from o2common.helper import o2logging
36 logger = o2logging.get_logger(__name__)
39 class O2Namespace(Namespace):
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)
47 self, fields, as_list=False, code=HTTPStatus.OK, description=None,
51 A decorator specifying the fields to use for serialization.
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
63 str(code): (description, [fields], kwargs)
65 else (description, fields, kwargs)
67 "__mask__": kwargs.get(
69 ), # Mask values can't be determined outside app context
71 func.__apidoc__ = merge(getattr(func, "__apidoc__", {}), doc)
72 return o2_marshal_with(fields, ordered=self.ordered,
78 class o2_marshal_with(marshal_with):
80 self, fields, envelope=None, skip_none=False, mask=None, ordered=False
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
89 self.envelope = envelope
90 self.skip_none = skip_none
91 self.ordered = ordered
92 self.mask = Mask(mask, skip=True)
94 def __call__(self, f):
96 def wrapper(*args, **kwargs):
97 resp = f(*args, **kwargs)
99 req_args = request.args
100 mask = self._gen_mask_from_selector(**req_args)
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)
123 resp, self.fields, self.envelope, self.skip_none, mask,
129 def _gen_mask_from_selector(self, **kwargs) -> str:
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(
139 mask_val = self.__gen_mask_from_selector(selector)
141 elif 'fields' in kwargs and kwargs['fields'] != '':
142 fields_without_space = kwargs['fields'].replace(" ", "")
144 # filters = fields_without_space.split(',')
149 # a = self.__gen_mask_tree(f)
150 # mask_val_list.append(a)
152 # mask_val_list.append(f)
153 # mask_val = '{%s}' % ','.join(mask_val_list)
156 self.__update_selector_value(selector, fields_without_space, True)
157 self.__set_default_mask(selector)
159 mask_val = self.__gen_mask_from_selector(selector)
161 elif 'exclude_fields' in kwargs and kwargs['exclude_fields'] != '':
162 exclude_fields_without_space = kwargs['exclude_fields'].replace(
165 selector = self.__gen_selector_from_model_with_value(
168 self.__update_selector_value(
169 selector, exclude_fields_without_space, False)
170 self.__set_default_mask(selector)
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(
176 exclude_default = exclude_default_without_space.lower()
177 if 'true' == exclude_default:
185 def __gen_mask_tree(self, field: str) -> str:
187 f = field.split('/', 1)
189 s = self.__gen_mask_tree(f[1])
190 return '%s%s' % (f[0], s)
194 def __gen_selector_from_model_with_value(
195 self, model: Model, default_val: bool = True) -> dict:
198 if type(model[i]) is List:
199 if type(model[i].container) is String:
200 selector[i] = default_val
202 selector[i] = self.__gen_selector_from_model_with_value(
203 model[i].container.model, default_val)
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
211 def __update_selector_value(self, selector: dict, filter: str,
213 fields = filter.split(',')
216 self.__update_selector_tree_value(selector, f, val)
218 if f not in self.fields:
219 raise BadRequestException(
220 'Selector attribute {} not found'.format(f))
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)
231 m[filter_list[0]] = val
233 def __gen_mask_from_selector(self, fields: dict) -> str:
235 for k, v in fields.items():
237 s = self.__gen_mask_from_selector(v)
238 mask_li.append('%s%s' % (k, s))
243 return '{%s}' % ','.join(mask_li)
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)