c595d9f96c31b578f7f895f875e07f3c48ab1bad
[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
41     link_list = []
42     if (page_current > 1):
43         parsed = base_url._replace(query=query + PAGE_PARAM + '=1')
44         link_list.append('<' + parsed.geturl() + '>; rel="first"')
45     if (page_current > 1):
46         parsed = base_url._replace(
47             query=query + PAGE_PARAM + '=' + str(page_current - 1))
48         link_list.append('<' + parsed.geturl() + '>; rel="prev"')
49     if (page_current < page_total):
50         parsed = base_url._replace(
51             query=query + PAGE_PARAM + '=' + str(page_current + 1))
52         link_list.append('<' + parsed.geturl() + '>; rel="next"')
53     if (page_current < page_total):
54         parsed = base_url._replace(
55             query=query + PAGE_PARAM + '=' + str(page_total))
56         link_list.append('<' + parsed.geturl() + '>; rel="last"')
57     if 0 == len(link_list):
58         return ret.pop('results'), {'X-Total-Count': count}
59     link = ','.join(link_list)
60     return ret.pop('results'), {'X-Total-Count': count, 'Link': link}