From 4b80bd61d346849c09b3e6bf06e318d52ee7cac4 Mon Sep 17 00:00:00 2001 From: borzechof99 <borzechof99@mi.fu-berlin.de> Date: Fri, 18 Jun 2021 21:11:37 +0200 Subject: [PATCH] Try Hand at Pagination --- unisportomat/quiz/pagination.py | 36 +++++++++++++++++++++++++++ unisportomat/unisportomat/settings.py | 23 ++++++++++++++--- 2 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 unisportomat/quiz/pagination.py diff --git a/unisportomat/quiz/pagination.py b/unisportomat/quiz/pagination.py new file mode 100644 index 0000000..4c97001 --- /dev/null +++ b/unisportomat/quiz/pagination.py @@ -0,0 +1,36 @@ +from collections import OrderedDict +from rest_framework.response import Response +from rest_framework.pagination import PageNumberPagination + + +class ReactAdminPagination(PageNumberPagination): + page_query_param = "page" + page_size_query_param = "perPage" + + def get_paginated_response(self, data): + count = self.page.paginator.count + item_starting_index = self.page.start_index() - 1 + item_ending_index = self.page.end_index() - 1 + + content_range = "items {0}-{1}/{2}".format( + item_starting_index, item_ending_index, count + ) + + # headers = {"Content-Range": content_range} + headers = {"x-total-count": count} + + return Response( + OrderedDict( + [ + ("x-total-count", count), + ("next", self.get_next_link()), + ("previous", self.get_previous_link()), + ("results", data), + ] + ), + headers=headers, + ) + + +class PageNumberWithPageSizePagination(PageNumberPagination): + page_size_query_param = "page_size" diff --git a/unisportomat/unisportomat/settings.py b/unisportomat/unisportomat/settings.py index 803efec..1850ecf 100644 --- a/unisportomat/unisportomat/settings.py +++ b/unisportomat/unisportomat/settings.py @@ -32,6 +32,8 @@ ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ + "corsheaders", + "rest_framework", # "quiz.apps.QuizConfig", "django.contrib.admin", "django.contrib.auth", @@ -39,12 +41,11 @@ INSTALLED_APPS = [ "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", - "rest_framework", - "corsheaders", "quiz", ] MIDDLEWARE = [ + "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", @@ -52,9 +53,25 @@ MIDDLEWARE = [ "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", - "corsheaders.middleware.CorsMiddleware", ] +# CORS_ALLOW_HEADERS = [ +# "x-total-count", +# "accept-encoding", +# "authorization", +# "content-type", +# "dnt", +# "origin", +# "user-agent", +# "x-csrftoken", +# "x-requested-with", +# ] + +REST_FRAMEWORK = { + "DEFAULT_PAGINATION_CLASS": "quiz.pagination.PageNumberWithPageSizePagination", + "PAGE_SIZE": 10, +} + ROOT_URLCONF = "unisportomat.urls" TEMPLATES = [ -- GitLab