Coverage for audoma/drf/viewsets.py: 41%
22 statements
« prev ^ index » next coverage.py v6.4.2, created at 2022-08-08 06:12 +0000
« prev ^ index » next coverage.py v6.4.2, created at 2022-08-08 06:12 +0000
1import random
2from typing import List
4from rest_framework import viewsets
5from rest_framework.pagination import PageNumberPagination
6from rest_framework.response import Response
8from audoma.drf.generics import GenericAPIView
11class AudomaPagination(PageNumberPagination):
12 """
13 A simple page number based style that supports page numbers as
14 query parameters.
16 Note:
17 If this won't be used it'll cause less explicit pagination documentation.
18 This class does not provide any additional functionality.
20 Args:
21 page_size (int) - number of items per page - by default this is set to 25
22 max_page_size (int) - maximum number of items per page - by default this is set to 2000
23 """
25 page_size = 25
26 max_page_size = 2000
28 def get_paginated_response_schema(self, schema: List[dict]) -> dict:
29 """
30 Simple method to add pagination information to the schema.
32 Args:
33 schema (List[dict]) - list of schema items
34 Returns:
35 Dictionary with pagination information including examples
36 """
37 return {
38 "type": "object",
39 "properties": {
40 "count": {"type": "integer", "example": random.randint(1, 100)},
41 "message": {
42 "type": "string",
43 "nullable": True,
44 },
45 "next": {
46 "type": "string",
47 "nullable": True,
48 "format": "uri",
49 "example": "http://api.example.org/accounts/?page=4",
50 },
51 "previous": {
52 "type": "string",
53 "nullable": True,
54 "format": "uri",
55 "example": "http://api.example.org/accounts/?page=2",
56 },
57 "results": schema,
58 },
59 }
62class GenericViewSet(viewsets.ViewSetMixin, GenericAPIView):
63 pagination_class = AudomaPagination
65 def handle_exception(self, exc: Exception) -> Response:
66 response = super().handle_exception(exc)
67 if isinstance(response.data, dict):
68 if response.status_code != 418:
69 for k in response.data:
70 if isinstance(response.data[k], list):
71 response.data[k] = " ".join(response.data[k])
72 response.data = {"errors": response.data}
73 return response