Last active
December 2, 2016 09:50
-
-
Save itsmunim/d40164f96cf69a655275987929a7bd6d to your computer and use it in GitHub Desktop.
A simple paginated DJango view implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def chunks(data, n): | |
"""Yield successive n-sized chunks from data.""" | |
for i in range(0, len(data), n): | |
yield data[i:i + n] | |
def get_page_number_from_request(request): | |
"""The `page` param will be from 1, 2, 3 ....so on, so we will have to translate it to | |
an index that makes sense for an array""" | |
page_no = request.GET.get('page') - 1 | |
return page_no if page_no > 0 else 0 | |
def get_error_list(start, end): | |
response = requests.get(apiUrl + "failed?start=" + start + "&end=" + end) | |
response.raise_for_status() | |
return response.json() | |
class ErrorListDateFilter(APIView): | |
def get(self, request, start, end): | |
try: | |
data = get_error_list(start, end) | |
page_no = get_page_number_from_request(request) | |
page_size = request.GET.get('size') | |
data_chunks = list(chunks(data, page_size)) | |
max_pages = len(data_chunks) | |
if page_no > max_pages - 1: | |
return Response({'message': '`page` number should be within 1-%d' % max_pages}) | |
return Response({'total': len(data), 'page': page_no + 1, 'size': page_size, 'data': data_chunks[page_no]}) | |
except Exception as ex: | |
return Response({'message': 'Internal server error. Reason: %s' % ex.message}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment