Update opMulti operations of the filter
[pti/o2.git] / o2common / views / pagination_view.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 import math
16 from typing import List, Tuple
17
18 from o2common.domain.base import Serializer
19
20 from o2common.helper import o2logging
21 logger = o2logging.get_logger(__name__)
22
23
24 class Pagination:
25     def __init__(self, **kwargs) -> None:
26         # filter key should be the same with database name
27         self.pagination_kwargs = {}
28         self.limit = int(kwargs['per_page']) if 'per_page' in kwargs else 30
29         self.page = int(kwargs['page']) if 'page' in kwargs else 1
30         if self.page < 1:
31             self.page = 1
32         self.start = (self.page - 1) * self.limit
33         self.pagination_kwargs['limit'] = self.limit
34         self.pagination_kwargs['start'] = self.start
35
36     def get_pagination(self):
37         return self.pagination_kwargs
38
39     def get_result(self, ret: Tuple[int, List[Serializer]]):
40         count = ret[0]
41         logger.info('List count: {}'.format(count))
42         ret_list = ret[1]
43         page_total = int(math.ceil(count/self.limit)
44                          ) if count > self.limit else 1
45         result = {
46             "count": count,
47             "page_total": page_total,
48             "page_current": self.page,
49             "per_page": self.limit,
50             "results": [r.serialize() for r in ret_list]
51         }
52         return result