/
__init__.py
169 lines (131 loc) · 4.39 KB
/
__init__.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import collections
from pymongo import MongoClient, ReturnDocument
from pymongo.errors import ConfigurationError
from thingy import classproperty, DatabaseThingy, registry
from mongo_thingy.cursor import Cursor
class Thingy(DatabaseThingy):
"""Represents a document in a collection"""
_client = None
_collection = None
_collection_name = None
_cursor_cls = Cursor
@classproperty
def _table(cls):
return cls._collection
@classproperty
def _table_name(cls):
return cls._collection_name
@classproperty
def table_name(cls):
return cls.collection_name
@classproperty
def collection(cls):
return cls.get_collection()
@classproperty
def collection_name(cls):
return cls.get_table_name()
@classproperty
def client(cls):
return cls.get_client()
@classmethod
def _get_client(cls, database):
return database.client
@classmethod
def _get_database(cls, collection, name):
if collection:
return collection.database
if cls._client and name:
return cls._client[name]
raise AttributeError("Undefined database.")
@classmethod
def _get_table(cls, database, table_name):
return database[table_name]
@classmethod
def _get_database_name(cls, database):
return database.name
@classmethod
def _get_table_name(cls, table):
return table.name
@classmethod
def get_client(cls):
if cls._client:
return cls._client
return cls._get_client(cls.database)
@classmethod
def get_collection(cls):
return cls.get_table()
@classmethod
def add_index(cls, keys, **kwargs):
kwargs.setdefault("background", True)
if not hasattr(cls, "_indexes"):
cls._indexes = []
cls._indexes.append((keys, kwargs))
@classmethod
def count(cls, *args, **kwargs):
return cls.collection.count(*args, **kwargs)
@classmethod
def connect(cls, *args, **kwargs):
cls._client = MongoClient(*args, **kwargs)
try:
cls._database = cls._client.get_default_database()
except ConfigurationError:
pass
@classmethod
def create_index(cls, keys, **kwargs):
cls.add_index(keys, **kwargs)
cls.collection.create_index(keys, **kwargs)
@classmethod
def create_indexes(cls):
if hasattr(cls, "_indexes"):
for keys, kwargs in cls._indexes:
cls.collection.create_index(keys, **kwargs)
@classmethod
def disconnect(cls, *args, **kwargs):
cls.client.close()
cls._client = None
cls._database = None
@classmethod
def distinct(cls, *args, **kwargs):
return cls.collection.distinct(*args, **kwargs)
@classmethod
def find(cls, *args, **kwargs):
return cls._cursor_cls(cls.collection, thingy_cls=cls, *args, **kwargs)
@classmethod
def find_one(cls, filter=None, *args, **kwargs):
if filter is not None and not isinstance(filter, collections.Mapping):
filter = {"_id": filter}
max_time_ms = kwargs.pop("max_time_ms", None)
cursor = cls.find(filter, *args, **kwargs).max_time_ms(max_time_ms)
return cursor.first()
@classmethod
def find_one_and_replace(cls, *args, **kwargs):
kwargs.setdefault("return_document", ReturnDocument.AFTER)
result = cls.collection.find_one_and_replace(*args, **kwargs)
if result is not None:
return cls(result)
@property
def id(self):
return self.__dict__.get("id") or self._id
@id.setter
def id(self, value):
if "id" in self.__dict__:
self.__dict__["id"] = value
else:
self._id = value
def save(self, force_insert=False):
data = self.__dict__
if self.id is not None and not force_insert:
self.get_collection().update({"_id": self.id}, data, upsert=True)
else:
self.get_collection().insert(data)
return self
def delete(self):
return self.get_collection().remove({"_id": self.id})
connect = Thingy.connect
disconnect = Thingy.disconnect
def create_indexes():
"""Create indexes registered on all :class:`Thingy`"""
for cls in registry:
if issubclass(cls, Thingy):
cls.create_indexes()
__all__ = ["Thingy", "connect", "create_indexes"]