1
1
from datetime import timedelta
2
2
3
+ from django .core .cache import cache
3
4
from django .db .models import Count
4
5
from django .http import HttpRequest
5
6
from django .utils import timezone
6
7
7
8
from activities .models import Hashtag , Post
8
9
from api import schemas
9
10
from api .decorators import scope_required
11
+ from core .models import Config
10
12
from hatchway import api_view
11
13
12
14
15
17
def trends_tags (
16
18
request : HttpRequest ,
17
19
limit : int = 10 ,
18
- offset : int | None = None ,
20
+ offset : int = 0 ,
19
21
) -> list [schemas .Tag ]:
20
- if limit > 40 :
21
- limit = 40
22
+ popular_tags = cache .get ("trends_tags" , None )
23
+ if popular_tags is None :
24
+ popular_tags = Hashtag .popular (limit = 100 , offset = 0 )
25
+ cache .set ("trends_tags" , popular_tags , Config .system .cache_timeout_trends )
22
26
return schemas .Tag .map_from_hashtags (
23
- Hashtag . popular ( limit = limit , offset = offset ) ,
27
+ popular_tags [ offset : offset + limit ] ,
24
28
domain = request .domain ,
25
29
identity = request .identity ,
26
30
)
@@ -31,19 +35,28 @@ def trends_tags(
31
35
def trends_statuses (
32
36
request : HttpRequest ,
33
37
limit : int = 10 ,
34
- offset : int | None = None ,
38
+ offset : int = 0 ,
35
39
) -> list [schemas .Status ]:
36
- if limit > 40 :
37
- limit = 40
38
- if offset is None :
39
- offset = 0
40
- since = timezone .now ().date () - timedelta (days = 7 )
40
+ popular_post_ids = cache .get ("trends_statuses" , None )
41
+ if popular_post_ids is None :
42
+ since = timezone .now ().date () - timedelta (days = 7 )
43
+ popular_post_ids = list (
44
+ Post .objects .not_hidden ()
45
+ .public ()
46
+ .filter (author__discoverable = True )
47
+ .filter (published__gte = since )
48
+ .annotate (num_interactions = Count ("interactions" ))
49
+ .filter (num_interactions__gte = 1 )
50
+ .order_by ("-num_interactions" , "-published" )
51
+ .values_list ("id" , flat = True )[:100 ]
52
+ )
53
+ cache .set (
54
+ "trends_statuses" , popular_post_ids , Config .system .cache_timeout_trends
55
+ )
41
56
posts = (
42
57
Post .objects .not_hidden ()
43
- .visible_to (request .identity )
44
- .filter (published__gte = since )
45
- .annotate (num_interactions = Count ("interactions" ))
46
- .order_by ("-num_interactions" , "-published" )[offset : offset + limit ]
58
+ .filter (id__in = popular_post_ids [offset : offset + limit ])
59
+ .order_by ("-published" )
47
60
)
48
61
return schemas .Status .map_from_post (list (posts ), request .identity )
49
62
0 commit comments