/
agon_tags.py
213 lines (168 loc) · 6.71 KB
/
agon_tags.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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import datetime
from django import template
from django.db.models import Sum
from django.db.models.loading import cache as app_cache
from django.utils.datastructures import SortedDict
from django.contrib.auth.models import User
from agon.models import points_awarded
register = template.Library()
class TopObjectsNode(template.Node):
@classmethod
def handle_token(cls, parser, token):
bits = token.split_contents()
time_unit = None
time_num = None
limit = None
if len(bits) not in [4, 6, 7, 9]:
"""
4: No optional params
6: limit N
7: timeframe N UNITS
9: limit N timeframe N UNITS --or-- timeframe N UNITS limit N
"""
raise template.TemplateSyntaxError(
"%r takes exactly three, five, six, or eight arguments (second"
" argument must be 'as')" % str(bits[0])
)
if bits[2] != "as":
raise template.TemplateSyntaxError(
"Second argument to %r must be 'as'" % str(bits[0])
)
if len(bits) == 6 or len(bits) == 9:
if "limit" not in [bits[4], bits[7]]:
raise template.TemplateSyntaxError(
"4th or 7th argument to %r must be 'limit'" % bits[0]
)
if len(bits) == 6 or bits[4] == "limit":
limit = bits[5]
else:
limit = bits[8]
if len(bits) == 7 or len(bits) == 9:
if "timeframe" not in [bits[4], bits[6]]:
raise template.TemplateSyntaxError(
"4th or 6th argument to %r must be 'timeframe'" % bits[0]
)
if len(bits) == 7 or bits[4] == "timeframe":
time_num, time_unit = bits[5], bits[6]
else:
time_num, time_unit = bits[7], bits[8]
return cls(bits[1], bits[3], limit, time_num, time_unit)
def __init__(self, model, context_var, limit, time_num, time_unit):
self.model = template.Variable(model)
self.context_var = context_var
if limit is None:
self.limit = None
else:
self.limit = template.Variable(limit)
if time_num is None or time_unit is None:
self.time_limit = None
else:
self.time_limit = datetime.timedelta(**{
time_unit: int(time_num) # @@@ doing this means can't express "7 days" as variables
})
def render(self, context):
limit = None
model_lookup = self.model.resolve(context)
incorrect_value = ValueError(
"'%s' does not result in a model. Is it correct?" % model_lookup
)
try:
model = app_cache.get_model(*model_lookup.split("."))
except TypeError:
raise incorrect_value
else:
if model is None:
raise incorrect_value
queryset = model.objects.all()
if self.time_limit is None:
if issubclass(model, User):
queryset = queryset.annotate(num_points=Sum("targetstat_targets__points"))
else:
queryset = queryset.extra(
select = SortedDict([
("num_points", "SELECT NULL")
])
)
else:
since = datetime.datetime.now() - self.time_limit
if issubclass(model, User):
queryset = queryset.filter(
awardedpointvalue_targets__timestamp__gte=since
).annotate(
num_points=Sum("awardedpointvalue_targets__points")
)
else:
queryset = queryset.extra(
select = SortedDict([
("num_points", "SELECT NULL")
])
)
queryset = queryset.order_by("-num_points")
if self.limit is not None:
limit = self.limit.resolve(context)
queryset = queryset[:limit]
context[self.context_var] = queryset
return u""
@register.tag
def top_objects(parser, token):
"""
Usage::
{% top_objects "auth.User" as top_users limit 10 %}
or::
{% top_objects "auth.User" as top_users %}
or::
{% top_objects "auth.User" as top_users limit 10 timeframe 7 days %}
All variations return a queryset of the model passed in with points annotated.
"""
return TopObjectsNode.handle_token(parser, token)
class PointsForObjectNode(template.Node):
@classmethod
def handle_token(cls, parser, token):
bits = token.split_contents()
if len(bits) == 2:
return cls(bits[1])
elif len(bits) == 4:
# len(bits) == 7 will support interval timeframing
if bits[2] != "as":
raise template.TemplateSyntaxError("Second argument to '%s' "
"should be 'as'" % bits[0])
return cls(bits[1], context_var=bits[3])
elif len(bits) == 7:
if bits[2] != "limit" and bits[5] != "as":
raise template.TemplateSyntaxError("Second argument to '%s' "
"should be 'as' and fifth argument should be 'limit" % bits[0])
return cls(
bits[1],
limit_num=bits[3],
limit_unit=bits[4],
context_var=bits[6]
)
raise template.TemplateSyntaxError("'%s' takes 1, 3, or 6 arguments." % bits[0])
def __init__(self, obj, context_var=None, limit_num=None, limit_unit=None):
self.obj = template.Variable(obj)
self.context_var = context_var
self.limit_num = limit_num
self.limit_unit = limit_unit
def render(self, context):
obj = self.obj.resolve(context)
since = None
if self.limit_num is not None and self.limit_unit is not None:
since = datetime.datetime.now() - datetime.timedelta(
**{self.limit_unit: int(self.limit_num)}
)
points = points_awarded(obj, since=since)
if self.context_var is not None:
context[self.context_var] = points
return ""
return unicode(points)
@register.tag
def points_for_object(parser, token):
"""
Gets the current points for an object, usage:
{% points_for_object user %}
or
{% points_for_object user as points %}
or
{% points_for_object user limit 7 days as points %}
"""
return PointsForObjectNode.handle_token(parser, token)