/
weight.py
112 lines (96 loc) · 3.18 KB
/
weight.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
#!/usr/bin/env python
#coding:utf-8
from time import time
from operator import itemgetter
import random
from datetime import datetime
from _redis import redis,redisWeightB
from model import UserModel,EntryModel
from utils import cache
class Entry(object):
_WEIGHT_A_KEY="WEIGHT_A"
_WEIGHT_B_KEY="WEIGHT_B"
_ENTRY_KEY="Entry:%s"
_LOGIN_ENTRY_KEY="LOGIN_ENTRY:%s"
@classmethod
def _add_weight(cls,id,weight):
redis.zincrby(cls._WEIGHT_A_KEY,id,weight)
cls.touch(id)
@classmethod
def _add_weight48(cls,id,weight):
if redisWeightB.exists(cls._LOGIN_ENTRY_KEY%id):
_old_weight=int(redisWeightB.zscore(cls._WEIGHT_B_KEY,id)[:1])
_new_value=(_old_weight+weight)*10**11+time()
redisWeightB.zincrby(cls._WEIGHT_B_KEY,_new_value,id)
redisWeightB.set(cls._LOGIN_ENTRY_KEY%id,time())
@classmethod
def exists24(cls,id):
return redis.get(cls._ENTRY_KEY%id)
@classmethod
def add(cls,uid,id):
redis.setex(cls._ENTRY_KEY%id,86400,time())
#redis.zadd(cls._ENTRY_KEY%uid,time(),id)
@classmethod
def touch(cls,id):
redis.set(cls._ENTRY_KEY%id,time())
@classmethod
def favor(cls,id):
'''喜欢过的'''
if cls.exists24(id):
cls._add_weight(id,1)
else:
cls._add_weight48(id,1)
@classmethod
def comment(cls,id):
'''评论过的'''
if cls.exists24(id):
uid=EntryModel.uid_by_eid(id)
weight=1
if UserModel.has_pet(uid):
weight=1.5
cls._add_weight(id,weight)
else:
cls._add_weight48(id,2)
@classmethod
def _time_line_a(cls):
#withscores=True
_entry_kvs=dict(redis.zrangebyscore(cls._WEIGHT_A_KEY,0,"+inf",start=0,num=100,withscores=True))
if len(_entry_kvs)<1:
return []
_entry_ks=map(lambda eid:cls._ENTRY_KEY%eid,_entry_kvs.keys())
_entry_time=redis.mget(_entry_ks)
weightA=[]
for i,k in enumerate(_entry_kvs.keys()):
weightA.append([k,_entry_kvs[k],_entry_time[i]])
return weightA
@classmethod
def _time_line_b(cls,size=15):
min_score=2*10**11+time()-3600*24
_entry_kvs=redisWeightB.zrangebyscore(cls._WEIGHT_B_KEY,min_score,"+inf",withscores=True)
if len(_entry_kvs)<1:
return []
weightB=set()
for i in range(size):
eid,value=random.choice(_entry_kvs)
_entry_kvs.remove((eid,value))
weight,t=value[:1],value[1:]
_weightB.add([eid,weight,t])
return list(weightB)
@classmethod
@cache(300)
def time_line(cls):
weightA=cls._time_line_a()
weightB=cls._time_line_b()
weight=weightA+weightB
return sorted(weight,key=itemgetter(2))
class User:
@classmethod
def login(self,uid):
entries=UserEntry.entries_by_uid_createtime(uid,time()-86400)#
for e in entries:
redisWeightB.setex(Entry._LOGIN_ENTRY_KEY%id,17200,0)
redisWeightB.zadd(Entry._WEIGHT_B_KEY,time(),id)
def main():
pass
if __name__=='__main__':
print Entry.time_line()