2015-09-29 19:53:38 +00:00
|
|
|
from flask import request
|
|
|
|
from app import get_app_url
|
2016-02-09 22:25:33 +00:00
|
|
|
from util.pagination import encrypt_page_token, decrypt_page_token
|
|
|
|
import urllib
|
|
|
|
import logging
|
2015-09-29 19:53:38 +00:00
|
|
|
|
2016-02-09 22:25:33 +00:00
|
|
|
_MAX_RESULTS_PER_PAGE = 50
|
2015-09-29 19:53:38 +00:00
|
|
|
|
|
|
|
def add_pagination(query, url):
|
|
|
|
""" Adds optional pagination to the given query by looking for the Docker V2 pagination request
|
2016-02-09 22:25:33 +00:00
|
|
|
args.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
requested_limit = int(request.args.get('n', _MAX_RESULTS_PER_PAGE))
|
|
|
|
except ValueError:
|
|
|
|
requested_limit = 0
|
2015-09-29 19:53:38 +00:00
|
|
|
|
2016-02-09 22:25:33 +00:00
|
|
|
limit = max(min(requested_limit, _MAX_RESULTS_PER_PAGE), 1)
|
|
|
|
next_page_token = request.args.get('next_page', None)
|
2015-09-29 19:53:38 +00:00
|
|
|
|
2016-02-09 22:25:33 +00:00
|
|
|
# Decrypt the next page token, if any.
|
|
|
|
offset = 0
|
|
|
|
page_info = decrypt_page_token(next_page_token)
|
|
|
|
if page_info is not None:
|
|
|
|
# Note: we use offset here instead of ID >= n because one of the V2 queries is a UNION.
|
|
|
|
offset = page_info.get('offset', 0)
|
|
|
|
query = query.offset(offset)
|
|
|
|
|
|
|
|
query = query.limit(limit + 1)
|
2015-09-29 19:53:38 +00:00
|
|
|
url = get_app_url() + url
|
2016-02-09 22:25:33 +00:00
|
|
|
|
|
|
|
results = list(query)
|
|
|
|
if len(results) <= limit:
|
|
|
|
return None, results
|
|
|
|
|
|
|
|
# Add a link to the next page of results.
|
|
|
|
page_info = dict(offset=limit + offset)
|
|
|
|
next_page_token = encrypt_page_token(page_info)
|
|
|
|
|
|
|
|
link = url + '?' + urllib.urlencode(dict(n=limit, next_page=next_page_token))
|
|
|
|
link = link + '; rel="next"'
|
|
|
|
return link, results[0:-1]
|