e7b738f6792318a0b6d655a22a22fabf33d6e53c
[pti/o2.git] / o2common / views / pagination_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 from urllib.parse import urlparse
16 from flask import abort
17
18 from o2common.helper import o2logging
19 logger = o2logging.get_logger(__name__)
20
21 PAGE_PARAM = 'nextpage_opaque_marker'
22
23
24 def link_header(full_path: str, ret):
25     base_url = urlparse(full_path)
26     count = ret.pop('count')
27     page_total = ret.pop('page_total')
28     page_current = ret.pop('page_current')
29
30     if page_current > page_total:
31         abort(400, "Page size {} bad request.".format(page_current))
32
33     if 0 == count:
34         return [], {'X-Total-Count': count}
35
36     query = "&".join(["{}".format(q) for q in base_url.query.split(
37         '&') if q.split('=')[0] != PAGE_PARAM])
38     if query != '':
39         query = query + '&'
40     logger.warning(query)
41
42     link_list = []
43     if (page_current > 1):
44         parsed = base_url._replace(query=query + PAGE_PARAM + '=1')
45         link_list.append('<' + parsed.geturl() + '>; rel="first"')
46     if (page_current > 1):
47         parsed = base_url._replace(
48             query=query + PAGE_PARAM + '=' + str(page_current - 1))
49         link_list.append('<' + parsed.geturl() + '>; rel="prev"')
50     if (page_current < page_total):
51         parsed = base_url._replace(
52             query=query + PAGE_PARAM + '=' + str(page_current + 1))
53         link_list.append('<' + parsed.geturl() + '>; rel="next"')
54     if (page_current < page_total):
55         parsed = base_url._replace(
56             query=query + PAGE_PARAM + '=' + str(page_total))
57         link_list.append('<' + parsed.geturl() + '>; rel="last"')
58     if 0 == len(link_list):
59         return ret.pop('results'), {'X-Total-Count': count}
60     link = ','.join(link_list)
61     return ret.pop('results'), {'X-Total-Count': count, 'Link': link}