Login

Simple Response with Pagination for API REST

Author:
aguilarpgc
Posted:
July 24, 2015
Language:
Python
Version:
1.7
Score:
1 (after 1 ratings)

Pagination in REST response: - optional page

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def get_page_in_request_data(request_data):
	try:
		page = request_data["page"]
	except Exception, e:
		page = 1

	return page

def get_pagination_values(list_length, page, num_per_page):
	"""
		-> (number, number, number, number)
		Return:
		- number total of pages
		- current page
		- start of range
		- end of range
	"""
	# There are objects
	if list_length > 0:
		total_pages    = ((list_length - 1) / num_per_page) + 1

		# Validation
		if page > total_pages:
			page = total_pages

		if page < 1:
			page = 1

		start = (page - 1) * num_per_page
		end   = start + num_per_page
	else:
		total_pages = 1
		page        = 1
		start = 0
		end   = 0

	return (total_pages, page, start, end)

def response_success_object(dic, a_object=None):
	#if a_object:
	dic["object"]  = a_object
	dic["success"] = True

def response_success_object_pagination(dic, object_list, request_data, num_per_page=10):

	page = get_page_in_request_data(request_data)
	total_pages, page, start, end = get_pagination_values(len(object_list), page, num_per_page)

	dic["pagination"] = {
		"current" : page,
		"pages"   : total_pages
	}

	# Normal response success
	response_success_object(dic, object_list[start:end])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.