Skip to content

Instantly share code, notes, and snippets.

@Fluxx
Created January 9, 2013 00:32
Show Gist options
  • Select an option

  • Save Fluxx/4489442 to your computer and use it in GitHub Desktop.

Select an option

Save Fluxx/4489442 to your computer and use it in GitHub Desktop.
from contextlib import contextmanager
from models import User
@contextmanager
def maybe(thing, check=lambda thing: thing):
if check(thing):
yield thing
# Rather than this
def filter_ads_for_thread(ads, thread):
blacklisted_ads = set(BlackListedForumsModel.objects.using('default.slave').filter(
advertisement__in=ads,
forum=thread.forum,
).values_list('advertisement_id', flat=True))
if blacklisted_ads:
ads = [ad for ad in ads if ad.id not in blacklisted_ads]
publisher_info = thread.forum.get_publisher_info()
if publisher_info:
for domain in publisher_info.blacklisted_domains:
ads = [ad for ad in ads if not domain_match(ad.parsed_url, domain)]
return ads
# You can do this
def filter_ads_for_thread(ads, thread):
blacklisted_ads = BlackListedForumsModel.objects.using('default.slave').filter(
advertisement__in=ads,
forum=thread.forum,
).values_list('advertisement_id', flat=True)
with maybe(blacklisted_ads) as blacklist_result:
ads = [ad for ad in ads if ad.id not in blacklist_result]
with maybe(thread.forum.get_publisher_info()) as publisher_info:
for domain in publisher_info.blacklisted_domains:
ads = [ad for ad in ads if not domain_match(ad.parsed_url, domain)]
return ads
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment