This repository has been archived by the owner on Feb 20, 2022. It is now read-only.
forked from milesrichardson/ParsePy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.py
187 lines (149 loc) · 6.03 KB
/
query.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
import copy
import collections
class QueryError(Exception):
'''Query error base class'''
def __init__(self, message, status_code=None):
super(QueryError, self).__init__(message)
if status_code:
self.status_code = status_code
class QueryResourceDoesNotExist(QueryError):
'''Query returned no results'''
pass
class QueryResourceMultipleResultsReturned(QueryError):
'''Query was supposed to return unique result, returned more than one'''
pass
class QueryManager(object):
def __init__(self, model_class):
self.model_class = model_class
def _fetch(self, **kw):
klass = self.model_class
uri = self.model_class.ENDPOINT_ROOT
return [klass(**it) for it in klass.GET(uri, **kw).get('results')]
def _count(self, **kw):
kw.update({"count": 1})
return self.model_class.GET(self.model_class.ENDPOINT_ROOT, **kw).get('count')
def all(self):
return Queryset(self)
def filter(self, **kw):
return self.all().filter(**kw)
def fetch(self):
return self.all().fetch()
def get(self, **kw):
return self.filter(**kw).get()
class Queryset(object):
OPERATORS = [
'lt', 'lte', 'gt', 'gte', 'ne', 'in', 'nin', 'exists', 'select', 'dontSelect', 'all', 'relatedTo', 'nearSphere'
]
@staticmethod
def convert_to_parse(value):
from parse_rest.datatypes import ParseType
return ParseType.convert_to_parse(value, as_pointer=True)
@classmethod
def extract_filter_operator(cls, parameter):
for op in cls.OPERATORS:
underscored = '__%s' % op
if parameter.endswith(underscored):
return parameter[:-len(underscored)], op
return parameter, None
def __init__(self, manager):
self._manager = manager
self._where = collections.defaultdict(dict)
self._select_related = []
self._options = {}
self._result_cache = None
def __deepcopy__(self, memo):
q = self.__class__(self._manager)
q._where = copy.deepcopy(self._where, memo)
q._options = copy.deepcopy(self._options, memo)
q._select_related.extend(self._select_related)
return q
def __iter__(self):
return iter(self._fetch())
def __len__(self):
#don't use count query for len operator
#count doesn't return real size of result in all cases (eg if query contains skip option)
return len(self._fetch())
def __getitem__(self, key):
if isinstance(key, slice):
raise AttributeError("Slice is not supported for now.")
return self._fetch()[key]
def _fetch(self, count=False):
if self._result_cache is not None:
return len(self._result_cache) if count else self._result_cache
"""
Return a list of objects matching query, or if count == True return
only the number of objects matching.
"""
options = dict(self._options) # make a local copy
if self._where:
# JSON encode WHERE values
options['where'] = json.dumps(self._where)
if self._select_related:
options['include'] = ','.join(self._select_related)
if count:
return self._manager._count(**options)
self._result_cache = self._manager._fetch(**options)
return self._result_cache
def filter(self, **kw):
q = copy.deepcopy(self)
for name, value in kw.items():
parse_value = Queryset.convert_to_parse(value)
attr, operator = Queryset.extract_filter_operator(name)
if operator is None:
q._where[attr] = parse_value
elif operator == 'relatedTo':
q._where['$' + operator] = {'object': parse_value, 'key': attr}
else:
if not isinstance(q._where[attr], dict):
q._where[attr] = {}
q._where[attr]['$' + operator] = parse_value
return q
def limit(self, value):
q = copy.deepcopy(self)
q._options['limit'] = int(value)
return q
def skip(self, value):
q = copy.deepcopy(self)
q._options['skip'] = int(value)
return q
def order_by(self, order, descending=False):
q = copy.deepcopy(self)
# add a minus sign before the order value if descending == True
q._options['order'] = descending and ('-' + order) or order
return q
def select_related(self, *fields):
q = copy.deepcopy(self)
q._select_related.extend(fields)
return q
def count(self):
return self._fetch(count=True)
def exists(self):
return bool(self)
def get(self):
results = self._fetch()
if len(results) == 0:
error_message = 'Query against %s returned no results' % (
self._manager.model_class.ENDPOINT_ROOT)
raise QueryResourceDoesNotExist(error_message,
status_code=404)
if len(results) >= 2:
error_message = 'Query against %s returned multiple results' % (
self._manager.model_class.ENDPOINT_ROOT)
raise QueryResourceMultipleResultsReturned(error_message,
status_code=404)
return results[0]
def __repr__(self):
return repr(self._fetch())