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