本文整理汇总了Python中events.models.Feed类的典型用法代码示例。如果您正苦于以下问题:Python Feed类的具体用法?Python Feed怎么用?Python Feed使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Feed类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: push_to_social_media_rss
def push_to_social_media_rss(request):
import django.contrib.syndication.views
from events.models import Feed
from events.templatetags.events_utils import render_event
import re
feedlist = [Feed.from_name("misc:comingup"), Feed.from_name('misc:enactedbills')]
class DjangoFeed(django.contrib.syndication.views.Feed):
title = "GovTrack.us Is Tracking Congress"
link = "/"
description = "GovTrack tracks the activities of the United States Congress. We push this feed to our Twitter and Facebook accounts."
def items(self):
events = [render_event(item, feedlist) for item in Feed.get_events_for(feedlist, 25)]
return [e for e in events if e != None]
def item_title(self, item):
return re.sub(r"^Legislation ", "", item["type"]) + ": " + item["title"]
def item_description(self, item):
return item["body_text"]
def item_link(self, item):
return settings.SITE_ROOT_URL + item["url"]# + "?utm_campaign=govtrack_push&utm_source=govtrack_push"
def item_guid(self, item):
return "http://www.govtrack.us/events/guid/" + item["guid"]
def item_pubdate(self, item):
return item["date"] if isinstance(item["date"], datetime) or item["date"] is None else datetime.combine(item["date"], time.min)
return DjangoFeed()(request)
示例2: build_info
def build_info():
# feeds about all legislation that we offer the user to subscribe to
feeds = [f for f in Feed.get_simple_feeds() if f.category == "federal-bills"]
# info about bills by status
groups = [
( g[0], # title
g[1], # text 1
g[2], # text 2
"/congress/bills/browse?status=" + ",".join(str(s) for s in g[4]) + "&sort=-current_status_date", # link
load_bill_status_qs(g[4]).count(), # count in category
load_bill_status_qs(g[4]).order_by('-current_status_date')[0:6], # top 6 in this category
)
for g in bill_status_groups ]
# legislation coming up
dhg_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, docs_house_gov_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=10)).filter(docs_house_gov_postdate__gt=F('current_status_date'))
sfs_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, senate_floor_schedule_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=5)).filter(senate_floor_schedule_postdate__gt=F('current_status_date'))
coming_up = list(dhg_bills | sfs_bills)
coming_up.sort(key = lambda b : b.docs_house_gov_postdate if (b.docs_house_gov_postdate and (not b.senate_floor_schedule_postdate or b.senate_floor_schedule_postdate < b.docs_house_gov_postdate)) else b.senate_floor_schedule_postdate, reverse=True)
# top tracked bills
top_bills = Feed.objects\
.filter(feedname__startswith='bill:')\
.filter(feedname__regex='^bill:[hs][jcr]?%d-' % CURRENT_CONGRESS)
top_bills = top_bills\
.annotate(count=Count('tracked_in_lists'))\
.order_by('-count')\
.values('feedname', 'count')\
[0:25]
top_bills = [(Bill.from_feed(Feed.from_name(bf["feedname"])), bf["count"]) for bf in top_bills]
# current congrss years
start, end = get_congress_dates(CURRENT_CONGRESS)
end_year = end.year if end.month > 1 else end.year-1 # count January finishes as the prev year
current_congress_years = '%d-%d' % (start.year, end.year)
current_congress = ordinal(CURRENT_CONGRESS)
return {
"feeds": feeds,
"total": Bill.objects.filter(congress=CURRENT_CONGRESS).count(),
"current_congress_years": current_congress_years,
"current_congress": current_congress,
"groups": groups,
"coming_up": coming_up,
"top_tracked_bills": top_bills,
"subjects": subject_choices(),
"BILL_STATUS_INTRO": (BillStatus.introduced, BillStatus.referred, BillStatus.reported),
}
示例3: build_info
def build_info():
# feeds about all legislation that we offer the user to subscribe to
feeds = [f for f in Feed.get_simple_feeds() if f.category == "federal-bills"]
# info about bills by status
groups = [
( g[0], # title
g[1], # text 1
g[2], # text 2
"/congress/bills/browse?status=" + ",".join(str(s) for s in g[4]) + "&sort=-current_status_date", # link
load_bill_status_qs(g[4]).count(), # count in category
load_bill_status_qs(g[4]).order_by('-current_status_date')[0:6], # top 6 in this category
)
for g in bill_status_groups ]
# legislation coming up
dhg_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, docs_house_gov_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=10)).filter(docs_house_gov_postdate__gt=F('current_status_date'))
sfs_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, senate_floor_schedule_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=5)).filter(senate_floor_schedule_postdate__gt=F('current_status_date'))
coming_up = list((dhg_bills | sfs_bills).order_by('scheduled_consideration_date'))
# top tracked bills
top_bills = Feed.objects\
.filter(feedname__startswith='bill:')\
.filter(feedname__regex='^bill:[hs][jcr]?%d-' % CURRENT_CONGRESS)
top_bills = top_bills\
.annotate(count=Count('tracked_in_lists'))\
.order_by('-count')\
.values('feedname', 'count')\
[0:25]
top_bills = [(Bill.from_feed(Feed.from_name(bf["feedname"])), bf["count"]) for bf in top_bills]
# trending bills
trf = Feed.get_trending_feeds()
trf = [Feed.objects.get(id=f) for f in trf]
trending_bill_feeds = [f for f in trf if f.feedname.startswith("bill:")]
return {
"feeds": feeds,
"total": Bill.objects.filter(congress=CURRENT_CONGRESS).count(),
"current_congress": CURRENT_CONGRESS,
"current_congress_dates": get_congress_dates(CURRENT_CONGRESS),
"groups": groups,
"coming_up": coming_up,
"top_tracked_bills": top_bills,
"trending_bill_feeds": trending_bill_feeds,
"subjects": subject_choices(),
"BILL_STATUS_INTRO": (BillStatus.introduced, BillStatus.reported),
}
示例4: index
def index(request):
twitter_feed = cache.get("our_twitter_feed")
if twitter_feed == None:
try:
import twitter
twitter_api = twitter.Api()
twitter_feed = twitter_api.GetUserTimeline("govtrack", since_id=0, count=3)
# replace links
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
re_url = re.compile(r"(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))")
for item in twitter_feed:
item.text = re_url.sub(lambda m : "<a target=\"_blank\" href=\"" + m.group(0) + "\">" + m.group(0) + "</a>", conditional_escape(item.text))
cache.set("our_twitter_feed", twitter_feed, 60*30) # 30 minutes
except:
twitter_feed = []
cache.set("our_twitter_feed", twitter_feed, 60*2) # 2 minutes
blog_feed = cache.get("our_blog_feed")
if not blog_feed:
blog_feed = get_blog_items()[0:2]
cache.set("our_blog_feed", blog_feed, 60*30) # 30 min
events_feed = cache.get("frontpage_events_feed")
if not events_feed:
events_feed = Feed.get_events_for([fn for fn in ("misc:activebills2", "misc:billsummaries", "misc:allvotes") if Feed.objects.filter(feedname=fn).exists()], 6)
cache.set("frontpage_events_feed", events_feed, 60*15) # 15 minutes
return {
'events': events_feed,
'tweets': twitter_feed,
'blog': blog_feed,
}
示例5: build_info
def build_info():
feeds = [f for f in Feed.get_simple_feeds() if f.category == "federal-bills"]
groups = [
( g[0], # title
g[1], # text 1
g[2], # text 2
"/congress/bills/browse?status=" + ",".join(str(s) for s in g[4]), # link
load_bill_status_qs(g[4]).count(), # count in category
load_bill_status_qs(g[4]).order_by('-current_status_date')[0:6], # top 6 in this category
)
for g in bill_status_groups ]
dhg_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, docs_house_gov_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=10)).filter(docs_house_gov_postdate__gt=F('current_status_date'))
sfs_bills = Bill.objects.filter(congress=CURRENT_CONGRESS, senate_floor_schedule_postdate__gt=datetime.datetime.now() - datetime.timedelta(days=5)).filter(senate_floor_schedule_postdate__gt=F('current_status_date'))
coming_up = list(dhg_bills | sfs_bills)
coming_up.sort(key = lambda b : b.docs_house_gov_postdate if (b.docs_house_gov_postdate and (not b.senate_floor_schedule_postdate or b.senate_floor_schedule_postdate < b.docs_house_gov_postdate)) else b.senate_floor_schedule_postdate, reverse=True)
start, end = get_congress_dates(CURRENT_CONGRESS)
end_year = end.year if end.month > 1 else end.year-1 # count January finishes as the prev year
current_congress_years = '%d-%d' % (start.year, end.year)
current_congress = ordinal(CURRENT_CONGRESS)
return {
"feeds": feeds,
"total": Bill.objects.filter(congress=CURRENT_CONGRESS).count(),
"current_congress_years": current_congress_years,
"current_congress": current_congress,
"groups": groups,
"coming_up": coming_up,
"subjects": subject_choices(),
"BILL_STATUS_INTRO": (BillStatus.introduced, BillStatus.referred, BillStatus.reported),
}
示例6: homepage_summary
def homepage_summary(request):
# parse & validate parameters
try:
state = request.GET["district"][0:2]
district = int(request.GET["district"][2:])
if state not in statenames: raise Exception()
except:
return None
from django.contrib.humanize.templatetags.humanize import ordinal
# view
people = Person.from_state_and_district(state, district)
feeds = [p.get_feed() for p in people]
events = Feed.get_events_for(feeds, 6)
from events.templatetags.events_utils import render_event
for i in range(len(events)):
events[i] = render_event(events[i], feeds)
if not isinstance(events[i]["date"], str):
events[i]["date"] = events[i]["date"].strftime('%B %d, %Y') # can't JSON-serialize a datetime anyway, TODO handle date_has_no_time
for k in list(events[i]): # remove anything else in case it is not JSON-serializable
if k not in ('type', 'date', 'title', 'body_html', 'url'):
del events[i][k]
# form output
return {
"state": state,
"district": district,
"state_name": statenames[state],
"district_ordinal": ordinal(district),
"reps": [ { "link": p.get_absolute_url(), "name": p.name_and_title(), "title": p.role.get_description(), "photo": p.get_photo_url() } for p in people],
"events": events,
}
示例7: export_panel_user_data
def export_panel_user_data(request, panel_id, download):
import csv, io
from django.utils.text import slugify
from website.models import UserPosition
from bill.models import Bill
from events.models import Feed
panel = get_object_or_404(Panel, id=panel_id, admins=request.user)
buf = io.StringIO()
w = csv.writer(buf)
if download == "members":
# Download the panel's membership, with one row per member.
w.writerow(["id", "email", "joined", "invitation_code", "notes"])
for mbr in PanelMembership.objects.filter(panel=panel).order_by('created').select_related("user"):
w.writerow([
str(mbr.id),
mbr.user.email,
mbr.created.isoformat(),
mbr.invitation_code,
mbr.extra.get("notes", ""),
])
elif download == "positions":
# Download the positions panel members have taken on legislation,
# with one row per member-position.
members = dict(PanelMembership.objects.filter(panel=panel).values_list("user_id", "id"))
w.writerow(["position_id", "member_id", "member_email", "position_created", "bill_id", "bill_title", "bill_link", "likert_score", "reason_text"])
for upos in UserPosition.objects.filter(user__in=members)\
.order_by('created')\
.select_related("user"):
w.writerow([
str(upos.id),
members[upos.user.id],
upos.user.email,
upos.created.isoformat(),
Bill.from_feed(Feed.from_name(upos.subject)).congressproject_id,
upos.get_subject_title(),
"https://www.govtrack.us" + upos.get_subject_link(),
str(upos.likert),
upos.reason,
])
else:
return HttpResponse("invalid")
ret = HttpResponse(buf.getvalue())
if True: # disable to make debugging easier
ret["Content-Type"] = "text/csv"
ret["Content-Disposition"] = "attachment;filename=%s_%s.csv" % (
slugify(panel.title),
download
)
else:
ret["Content-Type"] = "text/plain"
return ret
示例8: handle
def handle(self, *args, **options):
# get feeds, across all congresses
top_bills = Feed.objects.annotate(count=Count('tracked_in_lists'))\
.filter(feedname__startswith='bill:')\
.filter(feedname__regex='^bill:[hs][jcr]?%d-' % settings.CURRENT_CONGRESS)\
.order_by('-count')\
.values('feedname', 'count')\
[0:25]
print "users \t url \t bill title"
for bf in top_bills:
b = Feed.from_name(bf["feedname"]).bill()
print bf["count"], "\t", b.get_absolute_url(), "\t", b
示例9: index
def index(request):
blog_feed = cache.get("our_blog_feed")
if not blog_feed:
blog_feed = get_blog_items()[0:4]
cache.set("our_blog_feed", blog_feed, 60*30) # 30 min
events_feed = cache.get("frontpage_events_feed")
if not events_feed:
events_feed = Feed.get_events_for([fn for fn in ("misc:activebills2", "misc:billsummaries", "misc:allvotes") if Feed.objects.filter(feedname=fn).exists()], 6)
cache.set("frontpage_events_feed", events_feed, 60*15) # 15 minutes
return {
'events': events_feed,
'blog': blog_feed,
}
示例10: show_stats
def show_stats(self, recent_users_only):
# get feeds, across all congresses
top_bills = Feed.objects\
.filter(feedname__startswith='bill:')\
.filter(feedname__regex='^bill:[hs][jcr]?%d-' % settings.CURRENT_CONGRESS)
if recent_users_only:
top_bills = top_bills.filter(tracked_in_lists__user__date_joined__gt=datetime.datetime.now()-datetime.timedelta(days=14))
top_bills = top_bills\
.annotate(count=Count('tracked_in_lists'))\
.order_by('-count')\
.values('feedname', 'count')\
[0:25]
print "users \t url \t bill title"
for bf in top_bills:
b = Feed.from_name(bf["feedname"]).bill()
print bf["count"], "\t", b.get_absolute_url(), "\t", b
示例11: update_userposition
def update_userposition(request):
from website.models import UserPosition
if request.method != "POST": raise HttpResponseBadRequest()
# just validate
f = Feed.from_name(request.POST.get("subject", ""))
f.title
qs = UserPosition.objects.filter(user=request.user, subject=request.POST["subject"])
if not request.POST.get("likert") and not request.POST.get("reason"):
# Nothing to save - delete any existing.
qs.delete()
else:
# Update.
upos, _ = qs.get_or_create(user=request.user, subject=request.POST["subject"])
upos.likert = int(request.POST["likert"]) if request.POST.get("likert") else None
upos.reason = request.POST["reason"]
upos.save()
return HttpResponse(json.dumps({ "status": "ok" }), content_type="application/json")
示例12: bill_search_feed_title
def bill_search_feed_title(q):
from search import bill_search_manager
return "Bill Search - " + bill_search_manager().describe_qs(q)
def bill_search_feed_execute(q):
from search import bill_search_manager
from settings import CURRENT_CONGRESS
bills = bill_search_manager().execute_qs(q, overrides={'congress': CURRENT_CONGRESS}).order_by("-current_status_date")[0:100] # we have to limit to make this reasonably fast
def make_feed_name(bill):
return "bill:" + BillType.by_value(bill.bill_type).xml_code + str(bill.congress) + "-" + str(bill.number)
return Feed.objects.filter(feedname__in=[make_feed_name(bill) for bill in bills if bill != None]) # batch load
Feed.register_feed(
"billsearch:",
title = lambda feed : bill_search_feed_title(feed.feedname.split(":", 1)[1]),
link = lambda feed : "/congress/bills/browse?" + feed.feedname.split(":", 1)[1],
includes = lambda feed : bill_search_feed_execute(feed.feedname.split(":", 1)[1]),
meta = True,
)
# Summaries
class BillSummary(models.Model):
bill = models.OneToOneField(Bill, related_name="oursummary", on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
content = models.TextField(blank=True)
def plain_text(self):
import re
content = re.sub("<br>|<li>", " \n ", self.content, re.I)
示例13: template_context_processor
def template_context_processor(request):
# These are good to have in a context processor and not middleware
# because they won't be evaluated until template evaluation, which
# might have user-info blocked already for caching (a good thing).
context = dict(base_context) # clone
#if hasattr(request, 'user') and request.user.is_authenticated() and BouncedEmail.objects.filter(user=request.user).exists(): context["user_has_bounced_mail"] = True
# Add top-tracked feeds.
from events.models import Feed
global trending_feeds
if settings.DEBUG and False:
trending_feeds = [None, []]
elif not trending_feeds or trending_feeds[0] < datetime.datetime.now()-datetime.timedelta(hours=2):
trf = cache.get("trending_feeds")
if not trf:
trf = Feed.get_trending_feeds()
cache.set("trending_feeds", trf, 60*60*2)
trending_feeds = (datetime.datetime.now(), [Feed.objects.get(id=f) for f in trf])
context["trending_feeds"] = trending_feeds[1]
context["trending_bill_feeds"] = [f for f in trending_feeds[1] if f.feedname.startswith("bill:")]
# Add site-wide tracked events.
all_tracked_events = cache.get("all_tracked_events")
if not all_tracked_events:
all_tracked_events = Feed.get_events_for([fn for fn in ("misc:activebills2", "misc:billsummaries", "misc:allvotes") if Feed.objects.filter(feedname=fn).exists()], 6)
cache.set("all_tracked_events", all_tracked_events, 60*15) # 15 minutes
context["all_tracked_events"] = all_tracked_events
# Get our latest Medium posts.
medium_posts = cache.get("medium_posts")
if not medium_posts:
from website.models import MediumPost
medium_posts = MediumPost.objects.order_by('-published')[0:6]
cache.set("medium_posts", medium_posts, 60*15) # 15 minutes
context["medium_posts"] = medium_posts
# Get a campaign from if.then.fund.
itf_active_campaign = 50
if_then_fund_campaign = cache.get("if_then_fund_campaign")
if not if_then_fund_campaign and itf_active_campaign:
try:
if_then_fund_campaign = json.load(urllib2.urlopen("https://if.then.fund/a/%d.json" % itf_active_campaign))
except:
if_then_fund_campaign = "UHM" # something that is truthy otherwise we'll ping on every request
cache.set("if_then_fund_campaign", if_then_fund_campaign, 60*45) # 45 minutes
context["if_then_fund_campaign"] = if_then_fund_campaign
# Add context variables for whether the user is in the
# House or Senate netblocks.
def ip_to_quad(ip):
return [int(s) for s in ip.split(".")]
def compare_ips(ip1, ip2):
return cmp(ip_to_quad(ip1), ip_to_quad(ip2))
def is_ip_in_range(ip, block):
return compare_ips(ip, block[0]) >= 0 and compare_ips(ip, block[1]) <= 0
def is_ip_in_any_range(ip, blocks):
for block in blocks:
if is_ip_in_range(ip, block):
return True
return False
try:
ip = request.META["REMOTE_ADDR"]
ip = ip.replace("::ffff:", "") # ipv6 wrapping ipv4
if is_ip_in_any_range(ip, HOUSE_NET_RANGES):
context["remote_net_house"] = True
request._track_this_user = True
if is_ip_in_any_range(ip, SENATE_NET_RANGES):
context["remote_net_senate"] = True
request._track_this_user = True
if is_ip_in_any_range(ip, EOP_NET_RANGES):
context["remote_net_eop"] = True
request._track_this_user = True
except:
pass
# Add a context variable for if the user is near DC geographically.
user_loc = None
try:
if settings.GEOIP_DB_PATH and not request.path.startswith("/api/") and False:
user_loc = geo_ip_db.geos(ip)
context["is_dc_local"] = user_loc.distance(washington_dc) < .5
except:
pass
if not hasattr(request, 'user') or not request.user.is_authenticated():
# Have we put the user's district in a cookie?
try:
cong_dist = json.loads(request.COOKIES["cong_dist"])
x = cong_dist["state"] # validate fields are present
x = int(cong_dist["district"]) # ...and valid
except:
cong_dist = None
# Geolocate to a congressional district if not known and save it in
#.........这里部分代码省略.........
示例14: template_context_processor
def template_context_processor(request):
# These are good to have in a context processor and not middleware
# because they won't be evaluated until template evaluation, which
# might have user-info blocked already for caching (a good thing).
context = dict(base_context) # clone
# Add top-tracked feeds.
from events.models import Feed
global trending_feeds
if settings.DEBUG and False:
trending_feeds = [None, []]
elif not trending_feeds or trending_feeds[0] < datetime.datetime.now()-datetime.timedelta(hours=2):
trf = cache.get("trending_feeds")
if not trf:
trf = Feed.get_trending_feeds()
cache.set("trending_feeds", trf, 60*60*2)
trending_feeds = (datetime.datetime.now(), [Feed.objects.get(id=f) for f in trf])
context["trending_feeds"] = trending_feeds[1]
context["trending_bill_feeds"] = [f for f in trending_feeds[1] if f.feedname.startswith("bill:")]
# Add site-wide tracked events.
all_tracked_events = cache.get("all_tracked_events")
if not all_tracked_events:
all_tracked_events = Feed.get_events_for([fn for fn in ("misc:activebills2", "misc:billsummaries", "misc:allvotes") if Feed.objects.filter(feedname=fn).exists()], 6)
cache.set("all_tracked_events", all_tracked_events, 60*15) # 15 minutes
context["all_tracked_events"] = all_tracked_events
# Get our latest Medium posts.
medium_posts = cache.get("medium_posts")
if not medium_posts:
from website.models import MediumPost
medium_posts = MediumPost.objects.order_by('-published')[0:6]
cache.set("medium_posts", medium_posts, 60*15) # 15 minutes
context["medium_posts"] = medium_posts
# Add context variables for whether the user is in the
# House or Senate netblocks.
def ip_to_quad(ip):
return [int(s) for s in ip.split(".")]
def compare_ips(ip1, ip2):
return cmp(ip_to_quad(ip1), ip_to_quad(ip2))
def is_ip_in_range(ip, block):
return compare_ips(ip, block[0]) >= 0 and compare_ips(ip, block[1]) <= 0
def is_ip_in_any_range(ip, blocks):
for block in blocks:
if is_ip_in_range(ip, block):
return True
return False
try:
ip = request.META["REMOTE_ADDR"]
ip = ip.replace("::ffff:", "") # ipv6 wrapping ipv4
if is_ip_in_any_range(ip, HOUSE_NET_RANGES):
context["remote_net_house"] = True
request._track_this_user = True
if is_ip_in_any_range(ip, SENATE_NET_RANGES):
context["remote_net_senate"] = True
request._track_this_user = True
if is_ip_in_any_range(ip, EOP_NET_RANGES):
context["remote_net_eop"] = True
request._track_this_user = True
except:
pass
return context
示例15: template_context_processor
def template_context_processor(request):
# These are good to have in a context processor and not middleware
# because they won't be evaluated until template evaluation, which
# might have user-info blocked already for caching (a good thing).
context = {
"SITE_ROOT_URL": settings.SITE_ROOT_URL,
"GOOGLE_ANALYTICS_KEY": settings.GOOGLE_ANALYTICS_KEY
}
if request.user.is_authenticated() and BouncedEmail.objects.filter(user=request.user).exists(): context["user_has_bounced_mail"] = True
# Add top-tracked feeds.
global trending_feeds
if not trending_feeds or trending_feeds[0] < datetime.datetime.now()-datetime.timedelta(hours=2):
from events.models import Feed
trf = cache.get("trending_feeds")
if not trf:
trf = Feed.get_trending_feeds()
cache.set("trending_feeds", trf, 60*60*2)
trending_feeds = (datetime.datetime.now(), [Feed.objects.get(id=f) for f in trf])
context["trending_feeds"] = trending_feeds[1]
# Add context variables for whether the user is in the
# House or Senate netblocks.
def ip_to_quad(ip):
return [int(s) for s in ip.split(".")]
def compare_ips(ip1, ip2):
return cmp(ip_to_quad(ip1), ip_to_quad(ip2))
def is_ip_in_range(ip, block):
return compare_ips(ip, block[0]) >= 0 and compare_ips(ip, block[1]) <= 0
def is_ip_in_any_range(ip, blocks):
for block in blocks:
if is_ip_in_range(ip, block):
return True
return False
try:
ip = request.META["REMOTE_ADDR"]
ip = ip.replace("::ffff:", "") # ipv6 wrapping ipv4
if is_ip_in_any_range(ip, HOUSE_NET_RANGES):
context["remote_net_house"] = True
request._track_this_user = True
if is_ip_in_any_range(ip, SENATE_NET_RANGES):
context["remote_net_senate"] = True
request._track_this_user = True
if is_ip_in_any_range(ip, EOP_NET_RANGES):
context["remote_net_eop"] = True
request._track_this_user = True
try:
cong_dist = json.loads(request.COOKIES["cong_dist"])
except:
cong_dist = None
if settings.GEOIP_DB_PATH:
user_loc = geo_ip_db.geos(ip)
context["is_dc_local"] = user_loc.distance(washington_dc) < .5
# geolocate to a congressional district if not known
if not cong_dist and False:
from person.views import do_district_lookup
cong_dist = do_district_lookup(*user_loc.coords)
cong_dist["queried"] = True
if cong_dist and "error" not in cong_dist:
from person.models import PersonRole, RoleType, Gender
import random
def get_key_vote(p):
from vote.models import Vote
v = 113340
descr = "CISPA"
v = Vote.objects.get(id=v)
try:
return {
"link": v.get_absolute_url(),
"description": descr,
"option": p.votes.get(vote=v).option.key,
}
except:
return None
def fmt_role(r):
return {
"id": r.person.id,
"name": r.person.name_and_title(),
"link": r.person.get_absolute_url(),
"type": RoleType.by_value(r.role_type).key,
"pronoun": Gender.by_value(r.person.gender).pronoun,
"key_vote": get_key_vote(r.person),
}
qs = PersonRole.objects.filter(current=True).select_related("person")
cong_dist["reps"] = [fmt_role(r) for r in
qs.filter(role_type=RoleType.representative, state=cong_dist["state"], district=cong_dist["district"])
| qs.filter(role_type=RoleType.senator, state=cong_dist["state"])]
if settings.DEBUG:
#.........这里部分代码省略.........