snakelet.storage.paginator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 36
dl 0
loc 63
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Paginator.__iter__() 0 6 1
B Paginator.__next__() 0 22 6
A Paginator.__init__() 0 28 1
1
from .query import Query
2
3
4
class Paginator(Query):
5
    def __init__(self, collection,
6
                 find: dict = None,
7
                 offset: int = 0,
8
                 size: int = 30,
9
                 sort: str = None,
10
                 start: int = 0):
11
        """
12
        Args:
13
            collection:
14
            find (dict):
15
            offset (int):
16
            size (int):
17
            sort (str):
18
            start (int):
19
        """
20
21
        super().__init__(None)
22
23
        # database
24
        self.objectify = collection.objectify
25
        self.collection = collection.collection
26
27
        # parameters
28
        self.current = start
29
        self.find = find
30
        self.offset = offset
31
        self.sort = sort
32
        self.size = size
33
34
    def __iter__(self):
35
        """
36
        Returns:
37
38
        """
39
        return self
40
41
    def __next__(self):
42
        """
43
        Returns:
44
45
        """
46
        # FIXME: This should be a local value with a find to ensure we get an accurate count
47
        limit = self.collection.count() - self.offset
48
        pages = limit // self.size
49
        if self.current > pages:
50
            raise StopIteration
51
        page = self.collection
52
        page = page.find() if not self.find else page.find(self.find)
53
        if self.sort:
54
            key, value = self.sort
55
            page = page.sort(key, value)
56
        page = page.limit(self.size)
57
        if self.current > 0:
58
            page = page.skip(self.offset + (self.current * self.size))
59
        elif self.offset > 0:
60
            page = page.skip(self.offset)
61
        self.current += 1
62
        return [self.objectify(document) for document in page]
63