Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add caching to get_promotion_list and use namedtuple.

  • Loading branch information...
commit ecea06bf90a28fe7104c254be99868a0e0020130 1 parent d578e3a
@bsimpson63 bsimpson63 authored
Showing with 29 additions and 26 deletions.
  1. +29 −26 r2/r2/lib/promote.py
View
55 r2/r2/lib/promote.py
@@ -40,6 +40,7 @@
inventory,
)
from r2.lib.db.queries import set_promote_status
+from r2.lib.memoize import memoize
from r2.lib.organic import keep_fresh_links
from r2.lib.strings import strings
from r2.lib.template_helpers import get_domain
@@ -784,6 +785,26 @@ def make_daily_promotions(offset=0, test=False):
"promotions: %r" % error_campaigns)
+def randomized_promotion_list(user, site):
+ promos = get_promotion_list(user, site)
+ # no promos, no problem
+ if not promos:
+ return []
+ # more than two: randomize
+ elif len(promos) > 1:
+ n = random.uniform(0, 1)
+ for i, (l, w, cid) in enumerate(promos):
+ n -= w
+ if n < 0:
+ promos = promos[i:] + promos[:i]
+ break
+ # fall thru for the length 1 case here as well
+ return [(l, cid) for l, w, cid in promos]
+
+
+PromoTuple = namedtuple('PromoTuple', ['link', 'weight', 'campaign'])
+
+
def get_promotion_list(user, site):
# site is specified, pick an ad from that site
if not isinstance(site, FakeSubreddit):
@@ -797,10 +818,12 @@ def get_promotion_list(user, site):
else:
srids = set(Subreddit.user_subreddits(None, True) + [""])
- return get_promotions_cached(srids)
+ tuples = get_promotion_list_cached(srids)
+ return [PromoTuple(*t) for t in tuples]
-def get_promotions_cached(sites):
+@memoize('promotion_list', time=60)
+def get_promotion_list_cached(sites):
weights = get_live_promotions(sites)
if not weights:
return []
@@ -818,26 +841,6 @@ def get_promotions_cached(sites):
for link, weight, campaign in promos]
-def randomized_promotion_list(user, site):
- promos = get_promotion_list(user, site)
- # no promos, no problem
- if not promos:
- return []
- # more than two: randomize
- elif len(promos) > 1:
- n = random.uniform(0, 1)
- for i, (l, w, cid) in enumerate(promos):
- n -= w
- if n < 0:
- promos = promos[i:] + promos[:i]
- break
- # fall thru for the length 1 case here as well
- return [(l, cid) for l, w, cid in promos]
-
-
-PromoTuple = namedtuple('PromoTuple', ['link', 'weight', 'campaign'])
-
-
def sample_promoted_links(user, site, n=10):
"""Return a random selection of promoted links.
@@ -845,11 +848,11 @@ def sample_promoted_links(user, site, n=10):
"""
- promos = get_promotion_list(user, site)
- if n >= len(promos):
- return [PromoTuple(*p) for p in promos]
+ promo_tuples = get_promotion_list(user, site)
+ if n >= len(promo_tuples):
+ return promo_tuples
else:
- return [PromoTuple(*p) for p in random.sample(promos, n)]
+ return random.sample(promo_tuples, n)
def get_total_run(link):
Please sign in to comment.
Something went wrong with that request. Please try again.