-
Notifications
You must be signed in to change notification settings - Fork 722
/
actions.py
78 lines (62 loc) · 2.22 KB
/
actions.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
from datetime import date, datetime
from django.contrib.auth.models import User
from celery.task import task
from statsd import statsd
import waffle
from karma.manager import KarmaManager
from karma.models import Points
class ClassProperty(property):
"""Like @property but class based.
Only supports get.
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class KarmaAction(object):
"""Abstract base class for karma actions."""
action_type = None # For example 'first-answer'.
default_points = 0 # Default number of points the action is worth.
def __init__(self, user, day=date.today()):
if not waffle.switch_is_active('karma'):
return
if isinstance(user, User):
self.userid = user.id
else:
self.userid = user
if isinstance(day, datetime): # Gracefully handle a datetime.
self.date = day.date()
else:
self.date = day
@ClassProperty
@classmethod
def points(cls):
"""Return the number of points for the action."""
return Points.get_points(cls)
def save(self, async=True, redis=None):
"""Save the action information to redis.
:arg async: save in a celery task
:arg redis: used by init task to reuse the redis connection
"""
if waffle.switch_is_active('karma'):
if async:
self._save.delay(self)
else:
# Passing self below is required because the method is a @task
self._save(self, redis)
def delete(self, async=True):
"""Remove an action from redis.
:arg async: save in a celery task
"""
if waffle.switch_is_active('karma'):
if async:
self._delete.delay(self)
else:
# Passing self below is required because the method is a @task
self._delete(self)
@task
def _save(self, redis=None):
statsd.incr('karma.{t}'.format(t=self.action_type))
KarmaManager(redis).save_action(self)
@task
def _delete(self):
statsd.incr('karma.delete.{t}'.format(t=self.action_type))
KarmaManager().delete_action(self)