1
|
|
|
from .document import Document |
2
|
|
|
from .paginator import Paginator |
3
|
|
|
|
4
|
|
|
|
5
|
|
|
class Collection: |
6
|
|
|
def __init__(self, manager, document): |
7
|
|
|
""" |
8
|
|
|
Args: |
9
|
|
|
manager: |
10
|
|
|
document: |
11
|
|
|
""" |
12
|
|
|
self.manager = manager |
13
|
|
|
self.document = document |
14
|
|
|
self.collection_name = self.manager.collection_name.encode(self.document.__name__) |
15
|
|
|
self.collection = self.manager.db[self.collection_name] |
16
|
|
|
|
17
|
|
|
def find(self, *args, **kwargs): |
18
|
|
|
""" |
19
|
|
|
Args: |
20
|
|
|
*args: |
21
|
|
|
**kwargs: |
22
|
|
|
|
23
|
|
|
Returns: |
24
|
|
|
|
25
|
|
|
""" |
26
|
|
|
# return Query(self.collection.find(*args, **kwargs)) |
27
|
|
|
return [self.objectify(document) for document in self.collection.find(*args, **kwargs)] |
28
|
|
|
|
29
|
|
|
def find_one(self, *args, **kwargs): |
30
|
|
|
""" |
31
|
|
|
Args: |
32
|
|
|
*args: |
33
|
|
|
**kwargs: |
34
|
|
|
|
35
|
|
|
Returns: |
36
|
|
|
|
37
|
|
|
""" |
38
|
|
|
return self.objectify(self.collection.find_one(*args, **kwargs)) |
39
|
|
|
|
40
|
|
|
def save(self, *args): |
41
|
|
|
""" |
42
|
|
|
Args: |
43
|
|
|
*args: One or more documents |
44
|
|
|
""" |
45
|
|
|
for document in args: |
46
|
|
|
if not isinstance(document, Document): |
47
|
|
|
continue |
48
|
|
|
if '_id' not in document: |
49
|
|
|
self.collection.insert(document) |
50
|
|
|
else: |
51
|
|
|
self.collection.update({ |
52
|
|
|
"_id": document['_id'] |
53
|
|
|
}, document, upsert=True) |
54
|
|
|
|
55
|
|
|
def refresh(self, *args): |
56
|
|
|
""" |
57
|
|
|
Args: |
58
|
|
|
*args: One or more documents |
59
|
|
|
""" |
60
|
|
|
for document in args: |
61
|
|
|
if not isinstance(document, Document) or '_id' not in document: |
62
|
|
|
continue |
63
|
|
|
document.update(self.collection.find_one(document['_id'])) |
64
|
|
|
|
65
|
|
|
def remove(self, *args): |
66
|
|
|
""" |
67
|
|
|
Args: |
68
|
|
|
*args: One or more documents |
69
|
|
|
""" |
70
|
|
|
for document in args: |
71
|
|
|
if not isinstance(document, Document) or '_id' not in document: |
72
|
|
|
continue |
73
|
|
|
self.collection.remove({"_id": document['_id']}) |
74
|
|
|
document.clear() |
75
|
|
|
|
76
|
|
|
def paginate(self, **kwargs): |
77
|
|
|
""" |
78
|
|
|
Args: |
79
|
|
|
**kwargs: |
80
|
|
|
|
81
|
|
|
Returns: |
82
|
|
|
Paginator: |
83
|
|
|
""" |
84
|
|
|
return Paginator(self, **kwargs) |
85
|
|
|
|
86
|
|
|
def objectify(self, document): |
87
|
|
|
""" |
88
|
|
|
Args: |
89
|
|
|
document: |
90
|
|
|
|
91
|
|
|
Returns: |
92
|
|
|
Document: |
93
|
|
|
""" |
94
|
|
|
if not callable(self.document): |
95
|
|
|
raise LookupError('Unable to associate Document in Collection.') |
96
|
|
|
prototype = self.document() |
97
|
|
|
prototype.update(document) |
98
|
|
|
return prototype |
99
|
|
|
|