def event(request, abbr, event_id): ''' Context: - abbr - metadata - event - sources - gcal_info - gcal_string - nav_active Templates: - billy/web/public/event.html ''' event = db.events.find_one({'_id': event_id}) if event is None: raise Http404 return render(request, templatename('event'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), events=[event], event=event, event_template=templatename('_event'), events_list_template=templatename('events-pjax'), nav_active='events'))
def committee(request, abbr, committee_id): ''' Context: - committee - abbr - metadata - sources - nav_active - events Tempaltes: - billy/web/public/committee.html - billy/web/public/developer_committee.html ''' committee = db.committees.find_one({'_id': committee_id}) if committee is None: raise Http404 events = db.events.find({ settings.LEVEL_FIELD: abbr, "participants.id": committee_id }).sort("when", -1) events = list(events) if len(events) > EVENT_PAGE_COUNT: events = events[:EVENT_PAGE_COUNT] popularity.counter.inc('committees', committee_id, abbr=abbr) return render(request, templatename('committee'), dict(committee=committee, abbr=abbr, metadata=Metadata.get_object(abbr), sources=committee['sources'], nav_active='committees', events=events))
def bill(request, abbr, session, bill_id): # get fixed version fixed_bill_id = fix_bill_id(bill_id) # redirect if URL's id isn't fixed id without spaces if fixed_bill_id.replace(' ', '') != bill_id: return redirect('bill', abbr=abbr, session=session, bill_id=fixed_bill_id.replace(' ', '')) bill = db.bills.find_one({'state': abbr, 'session': session, 'bill_id': fixed_bill_id}) if bill is None: raise Http404('no bill found {0} {1} {2}'.format(abbr, session, bill_id)) events = db.events.find({ "state": abbr, "related_bills.bill_id": bill['_id'] }).sort("when", -1) popularity.counter.inc('bills', bill['_id'], abbr=abbr, session=session) show_all_sponsors = request.GET.get('show_all_sponsors') if show_all_sponsors: sponsors = bill.sponsors_manager else: sponsors = bill.sponsors_manager.first_fifteen return render(request, templatename('bill'), dict(vote_preview_row_template=templatename('vote_preview_row'), abbr=abbr, metadata=Metadata.get_object(abbr), bill=bill, events=events, show_all_sponsors=show_all_sponsors, sponsors=sponsors, sources=bill['sources'], statenav_active='bills'))
def state_not_active_yet(request, args, kwargs): return render_to_response( template_name=templatename('state_not_active_yet'), dictionary=dict( metadata=Metadata.get_object(kwargs['abbr']), statenav_active=None), context_instance=RequestContext(request, default_context))
def event(request, abbr, event_id): event = db.events.find_one({'_id': event_id}) if event is None: raise Http404 fmt = "%Y%m%dT%H%M%SZ" start_date = event['when'].strftime(fmt) duration = dt.timedelta(hours=1) ed = (event['when'] + duration) end_date = ed.strftime(fmt) gcal_info = { "action": "TEMPLATE", "text": event['description'], "dates": "%s/%s" % (start_date, end_date), "details": "", "location": event['location'].encode('utf-8'), "trp": "false", "sprop": "http://openstates.org/%s/events/%s/" % ( abbr, event_id ), "sprop": "name:Open States Event" } gcal_string = urllib.urlencode(gcal_info) return render(request, templatename('event'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), event=event, sources=event['sources'], gcal_info=gcal_info, gcal_string=gcal_string, statenav_active='events'))
def events(request, abbr): year = request.GET.get("year") month = request.GET.get("month") if year and month: if month == "0": month = 1 month = int(month) display_date = datetime.datetime(year=int(year), month=month, day=1) else: display_date = datetime.datetime.now() # Compensate for js dates. events = _get_events(abbr, display_date.year, display_date.month - 1) return TemplateResponse( request, templatename("events"), dict( abbr=abbr, display_date=display_date, metadata=Metadata.get_object(abbr), events=events, event_template=templatename("_event"), events_list_template=templatename("events-pjax"), nav_active="events", ), )
def recent_actions(abbr): state = Metadata.get_object(abbr) bills = state.bills({'session': state.most_recent_session, '$or': [{'actions.type': 'bill:passed'}, {'actions.type': 'bill:introduced'}], 'type': 'bill'}) bills_by_action = defaultdict(list) for bill in bills: for action in bill['actions']: actor = re.search(r'(upper|lower)', action['actor']) if actor: actor = actor.group() else: continue for type_ in action['type']: if type_ in ['bill:passed', 'bill:introduced']: bills_by_action[(type_, actor)].append( (action['date'], bill)) def f(type_, chamber): bills = list(sorted(bills_by_action[(type_, chamber)], reverse=True, key=itemgetter(0)))[:2] return map(itemgetter(1), bills) res = dict( passed_upper=f('bill:passed', 'upper'), passed_lower=f('bill:passed', 'lower'), introduced_upper=f('bill:introduced', 'upper'), introduced_lower=f('bill:introduced', 'lower')) return res
def bill(request, abbr, session, bill_id): ''' Context: - vote_preview_row_template - abbr - metadata - bill - events - show_all_sponsors - sponsors - sources - nav_active Templates: - billy/web/public/bill.html - billy/web/public/vote_preview_row.html ''' # get fixed version fixed_bill_id = fix_bill_id(bill_id) # redirect if URL's id isn't fixed id without spaces if fixed_bill_id.replace(' ', '') != bill_id: return redirect('bill', abbr=abbr, session=session, bill_id=fixed_bill_id.replace(' ', '')) _bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, 'session': session, 'bill_id': fixed_bill_id}) if _bill is None: raise Http404( u'no bill found {0} {1} {2}'.format(abbr, session, bill_id)) events = db.events.find({ settings.LEVEL_FIELD: abbr, "related_bills.bill_id": _bill['_id'] }).sort("when", -1) events = list(events) if len(events) > EVENT_PAGE_COUNT: events = events[:EVENT_PAGE_COUNT] popularity.counter.inc('bills', _bill['_id'], abbr=abbr, session=session) show_all_sponsors = request.GET.get('show_all_sponsors') if show_all_sponsors: sponsors = _bill.sponsors_manager else: sponsors = _bill.sponsors_manager.first_fifteen return render( request, templatename('bill'), dict(vote_preview_row_template=templatename('vote_preview_row'), abbr=abbr, metadata=Metadata.get_object(abbr), bill=_bill, events=events, show_all_sponsors=show_all_sponsors, sponsors=sponsors, sources=_bill['sources'], nav_active='bills'))
def not_active_yet(request, args, kwargs): try: metadata = Metadata.get_object(kwargs['abbr']) except DoesNotExist: raise Http404 return render(request, templatename('state_not_active_yet'), dict(metadata=metadata, statenav_active=None))
def state(request, abbr): report = db.reports.find_one({'_id': abbr}) try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 # count legislators legislators = meta.legislators({'active': True}, {'party': True, 'chamber': True}) # Maybe later, mapreduce instead? party_counts = defaultdict(lambda: defaultdict(int)) for leg in legislators: if 'chamber' in leg: # if statement to exclude lt. governors party_counts[leg['chamber']][leg['party']] += 1 chambers = [] for chamber in ('upper', 'lower'): res = {} # chamber metadata res['type'] = chamber res['title'] = meta[chamber + '_chamber_title'] res['name'] = meta[chamber + '_chamber_name'] # legislators res['legislators'] = { 'count': sum(party_counts[chamber].values()), 'party_counts': dict(party_counts[chamber]), } # committees res['committees_count'] = meta.committees({'chamber': chamber}).count() res['latest_bills'] = meta.bills({'chamber': chamber}).sort([('action_dates.first', -1)]).limit(2) res['passed_bills'] = meta.bills({'chamber': chamber}).sort([('action_dates.passed_' + chamber, -1)]).limit(2) chambers.append(res) joint_committee_count = meta.committees({'chamber': 'joint'}).count() # add bill counts to session listing sessions = meta.sessions() for s in sessions: try: s['bill_count'] = ( report['bills']['sessions'][s['id']]['upper_count'] + report['bills']['sessions'][s['id']]['lower_count']) except KeyError: # there's a chance that the session had no bills s['bill_count'] = 0 return render(request, templatename('state'), dict(abbr=abbr, metadata=meta, sessions=sessions, chambers=chambers, joint_committee_count=joint_committee_count, statenav_active='home'))
def event(request, abbr, event_id): event = db.events.find_one({'_id': event_id}) if event is None: raise Http404 return render(request, templatename('event'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), event=event, sources=event['sources'], statenav_active='events'))
def bill(request, abbr, session, bill_id): ''' Context: - vote_preview_row_template - abbr - metadata - bill - events - show_all_sponsors - sponsors - sources - nav_active Templates: - billy/web/public/bill.html - billy/web/public/vote_preview_row.html ''' # get fixed version fixed_bill_id = fix_bill_id(bill_id) # redirect if URL's id isn't fixed id without spaces if fixed_bill_id.replace(' ', '') != bill_id: return redirect('bill', abbr=abbr, session=session, bill_id=fixed_bill_id.replace(' ', '')) bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, 'session': session, 'bill_id': fixed_bill_id}) if bill is None: raise Http404(u'no bill found {0} {1} {2}'.format(abbr, session, bill_id)) events = db.events.find({ settings.LEVEL_FIELD: abbr, "related_bills.bill_id": bill['_id'] }).sort("when", -1) events = list(events) if len(events) > EVENT_PAGE_COUNT: events = events[:EVENT_PAGE_COUNT] popularity.counter.inc('bills', bill['_id'], abbr=abbr, session=session) show_all_sponsors = request.GET.get('show_all_sponsors') if show_all_sponsors: sponsors = bill.sponsors_manager else: sponsors = bill.sponsors_manager.first_fifteen return render( request, templatename('bill'), dict(vote_preview_row_template=templatename('vote_preview_row'), abbr=abbr, metadata=Metadata.get_object(abbr), bill=bill, events=events, show_all_sponsors=show_all_sponsors, sponsors=sponsors, sources=bill['sources'], nav_active='bills'))
def committee(request, abbr, committee_id): committee = db.committees.find_one({'_id': committee_id}) if committee is None: raise Http404 return render(request, templatename('committee'), dict(committee=committee, abbr=abbr, metadata=Metadata.get_object(abbr), sources=committee['sources'], statenav_active='committees'))
def speeches(request, abbr): events = db.events.find({ settings.LEVEL_FIELD: abbr, }).sort('when') return render(request, templatename('speeches'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), speeches=speeches, events=events))
def speeches(request, abbr): events = db.events.find({ settings.LEVEL_FIELD: abbr, }) return render(request, templatename('speeches'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), speeches=speeches, events=events))
def vote(request, abbr, _id): vote = db.votes.find_one(_id) if vote is None: raise Http404 bill = vote.bill() return render(request, templatename('vote'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), bill=bill, vote=vote, statenav_active='bills'))
def bill(request, abbr, session, bill_id): """ Context: - vote_preview_row_template - abbr - metadata - bill - events - show_all_sponsors - sponsors - sources - nav_active Templates: - billy/web/public/bill.html - billy/web/public/vote_preview_row.html """ # get fixed version fixed_bill_id = fix_bill_id(bill_id) # redirect if URL's id isn't fixed id without spaces if fixed_bill_id.replace(" ", "") != bill_id: return redirect("bill", abbr=abbr, session=session, bill_id=fixed_bill_id.replace(" ", "")) bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, "session": session, "bill_id": fixed_bill_id}) if bill is None: raise Http404(u"no bill found {0} {1} {2}".format(abbr, session, bill_id)) events = db.events.find({settings.LEVEL_FIELD: abbr, "related_bills.bill_id": bill["_id"]}).sort("when", -1) events = list(events) if len(events) > EVENT_PAGE_COUNT: events = events[:EVENT_PAGE_COUNT] popularity.counter.inc("bills", bill["_id"], abbr=abbr, session=session) show_all_sponsors = request.GET.get("show_all_sponsors") if show_all_sponsors: sponsors = bill.sponsors_manager else: sponsors = bill.sponsors_manager.first_fifteen return render( request, templatename("bill"), dict( vote_preview_row_template=templatename("vote_preview_row"), abbr=abbr, metadata=Metadata.get_object(abbr), bill=bill, events=events, show_all_sponsors=show_all_sponsors, sponsors=sponsors, sources=bill["sources"], nav_active="bills", ), )
def filter_bills(request, abbr): metadata = Metadata.get_object(abbr) FilterBillsForm = get_filter_bills_form(metadata) form = FilterBillsForm(request.GET) chambers = form.data.getlist('chambers') subjects = form.data.getlist('subjects') sponsored = form.data.getlist('sponsored') actions = form.data.getlist('actions') bill_types = form.data.getlist('bill_types') raise NotImplementedError('Search is in the works')
def get_region_select_form(data): abbrs = [('', '')] for abbr in sorted(settings.ACTIVE_STATES): try: obj = Metadata.get_object(abbr) abbrs.append((obj['_id'], obj['name'])) except DoesNotExist: # ignore missing pass class RegionSelectForm(forms.Form): abbr = forms.ChoiceField(choices=abbrs, label="abbr") return RegionSelectForm(data)
def get_state_select_form(data): state_abbrs = [('', '')] for state in sorted(settings.ACTIVE_STATES): try: obj = Metadata.get_object(state) state_abbrs.append((obj['_id'], obj['name'])) except DoesNotExist: # ignore missing states pass class StateSelectForm(forms.Form): abbr = forms.ChoiceField(choices=state_abbrs, label="state") return StateSelectForm(data)
def committees(request, abbr): try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 chamber = request.GET.get('chamber', 'both') if chamber in ('upper', 'lower'): chamber_name = meta['%s_chamber_name' % chamber] spec = {'chamber': chamber} show_chamber_column = False else: chamber = 'both' spec = {} show_chamber_column = True chamber_name = '' fields = ['committee', 'subcommittee', 'members', 'state', 'chamber'] fields = dict(zip(fields, repeat1)) sort_key = 'committee' sort_order = 1 sort_key = request.GET.get('key', 'committee') sort_order = int(request.GET.get('order', 1)) committees = meta.committees(spec, fields=fields, sort=[(sort_key, sort_order)]) sort_order = {1: -1, -1: 1}[sort_order] chamber_select_form = ChamberSelectForm.unbound(meta, chamber) return render_to_response( template_name=templatename('committees_chamber'), dictionary=dict( chamber=chamber, committees=committees, abbr=abbr, metadata=meta, chamber_name=chamber_name, chamber_select_form=chamber_select_form, chamber_select_template=templatename('chamber_select_form'), committees_table_template=templatename('committees_table'), chamber_select_collection='committees', show_chamber_column=show_chamber_column, sort_order=sort_order, statenav_active='committees'), context_instance=RequestContext(request, default_context))
def bills(request, abbr): try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 return render_to_response( template_name=templatename('bills'), dictionary=dict( committee=committee, abbr=abbr, metadata=meta, statenav_active='bills'), context_instance=RequestContext(request, default_context))
def vote(request, abbr, bill_id, vote_index): bill = db.bills.find_one({'_id': bill_id}) if bill is None: raise Http404 return render_to_response( template_name=templatename('vote'), dictionary=dict( abbr=abbr, state=Metadata.get_object(abbr), bill=bill, vote=nth(bill.votes_manager, int(vote_index)), statenav_active='bills'), context_instance=RequestContext(request, default_context))
def func(request, abbr, session, bill_id, key): # get fixed version fixed_bill_id = fix_bill_id(bill_id) # redirect if URL's id isn't fixed id without spaces if fixed_bill_id.replace(" ", "") != bill_id: return redirect("bill", abbr=abbr, session=session, bill_id=fixed_bill_id.replace(" ", "")) bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, "session": session, "bill_id": fixed_bill_id}) if bill is None: raise Http404("no bill found {0} {1} {2}".format(abbr, session, bill_id)) return render( request, templatename("bill_all_%s" % key), dict(abbr=abbr, metadata=Metadata.get_object(abbr), bill=bill, sources=bill["sources"], nav_active="bills"), )
def chamber(abbr, chamber): ''' 2-12-2012 Per wireframes/spec, provide this info: - leg'r count - party breakdown - committee count - joint committee count - bill count ''' res = {} state = Metadata.get_object(abbr) # Legislators legislators = state.legislators({ 'chamber': chamber, 'active': True }, {'party': True}) legislators = list(legislators) # Maybe later, mapreduce instead party_counts = defaultdict(int) for leg in legislators: party_counts[leg['party']] += 1 # chamber metadata res['type'] = chamber res['title'] = state[chamber + '_chamber_title'] res['name'] = state[chamber + '_chamber_name'] res['legislators'] = { 'count': len(legislators), 'party_counts': dict(party_counts), } # Committees res['committees'] = { 'count': state.committees({ 'chamber': chamber }).count(), 'joint_count': state.committees({ 'chamber': 'joint' }).count(), } res['bills_count'] = state.bills({'chamber': chamber}).count() return res
def committee(request, abbr, committee_id): committee = db.committees.find_one({'_id': committee_id}) if committee is None: raise Http404 return render_to_response( template_name=templatename('committee'), dictionary=dict( committee=committee, abbr=abbr, metadata=Metadata.get_object(abbr), sources=committee['sources'], statenav_active='committees'), context_instance=RequestContext(request, default_context))
def committees(request, abbr): try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 chamber = request.GET.get('chamber', 'both') if chamber in ('upper', 'lower'): chamber_name = meta['%s_chamber_name' % chamber] spec = {'chamber': chamber} show_chamber_column = False elif chamber == 'joint': chamber_name = 'Joint' spec = {'chamber': 'joint'} show_chamber_column = False else: chamber = 'both' spec = {} show_chamber_column = True chamber_name = '' chambers = {'upper': meta['upper_chamber_name'], } if meta.committees({'chamber': 'joint'}).count(): chambers['joint'] = 'Joint' if 'lower_chamber_name' in meta: chambers['lower'] = meta['lower_chamber_name'] fields = mongo_fields('committee', 'subcommittee', 'members', 'state', 'chamber') sort_key = request.GET.get('key', 'committee') sort_order = int(request.GET.get('order', 1)) committees = meta.committees_legislators(spec, fields=fields, sort=[(sort_key, sort_order)]) sort_order = -sort_order return TemplateResponse(request, templatename('committees'), dict(chamber=chamber, committees=committees, abbr=abbr, metadata=meta, chamber_name=chamber_name, chamber_select_template=templatename('chamber_select_form'), chamber_select_collection='committees', chamber_select_chambers=chambers, committees_table_template=templatename('committees_table'), show_chamber_column=show_chamber_column, sort_order=sort_order, statenav_active='committees'))
def speeches_by_event(request, abbr, event_id): event = db.events.find_one({ '_id': event_id, settings.LEVEL_FIELD: abbr }) speeches = db.speeches.find({ "event_id": event_id, settings.LEVEL_FIELD: abbr }).sort("sequence", 1) return render(request, templatename('speeches_by_event'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), speeches=speeches, event=event))
def not_active_yet(request, args, kwargs): ''' Context: - metadata - nav_active Tempaltes: - billy/web/public/state_not_active_yet.html ''' try: metadata = Metadata.get_object(kwargs['abbr']) except DoesNotExist: raise Http404 return render(request, templatename('state_not_active_yet'), dict(metadata=metadata, nav_active=None))
def func(request, abbr, session, bill_id, key): # get fixed version fixed_bill_id = fix_bill_id(bill_id) # redirect if URL's id isn't fixed id without spaces if fixed_bill_id.replace(' ', '') != bill_id: return redirect('bill', abbr=abbr, session=session, bill_id=fixed_bill_id.replace(' ', '')) bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, 'session': session, 'bill_id': fixed_bill_id}) if bill is None: raise Http404('no bill found {0} {1} {2}'.format(abbr, session, bill_id)) return render(request, templatename('bill_all_%s' % key), dict(abbr=abbr, metadata=Metadata.get_object(abbr), bill=bill, sources=bill['sources'], nav_active='bills'))
def get_context_data(self, *args, **kwargs): super(ListViewBase, self).get_context_data(*args, **kwargs) context = {} context.update(**default_context) context.update(column_headers=self.column_headers, rowtemplate_name=self.rowtemplate_name, description_template=self.description_template, object_list=self.get_queryset(), statenav_active=self.statenav_active, abbr=self.kwargs['abbr'], metadata=Metadata.get_object(self.kwargs['abbr']), url=self.request.path, use_table=getattr(self, 'use_table', False)) # Include the kwargs to enable references to url paramaters. context.update(**kwargs) return context
def legislator(request, abbr, _id, slug): try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 legislator = db.legislators.find_one({'_id': _id}) if legislator is None: raise Http404('No legislator was found with led_id = %r' % _id) if not legislator['active']: return legislator_inactive(request, abbr, legislator) qurl = "%sdistricts/%s/?apikey=%s" % ( billy_settings.API_BASE_URL, abbr, billy_settings.SUNLIGHT_API_KEY ) f = urllib2.urlopen(qurl) districts = json.load(f) district_id = None for district in districts: legs = [x['leg_id'] for x in district['legislators']] if legislator['leg_id'] in legs: district_id = district['boundary_id'] break sponsored_bills = legislator.sponsored_bills( limit=5, sort=[('action_dates.first', pymongo.DESCENDING)]) # Note to self: Another slow query legislator_votes = legislator.votes_5_sorted() has_votes = bool(legislator_votes) return render(request, templatename('legislator'), dict( feed_entry_template=templatename('feed_entry'), vote_preview_row_template=templatename('vote_preview_row'), roles=legislator.roles_manager, abbr=abbr, district_id=district_id, metadata=meta, legislator=legislator, sources=legislator['sources'], sponsored_bills=sponsored_bills, legislator_votes=legislator_votes, has_votes=has_votes, statenav_active='legislators'))
def event(request, abbr, event_id): ''' Context: - abbr - metadata - event - sources - gcal_info - gcal_string - nav_active Templates: - billy/web/public/event.html ''' event = db.events.find_one({'_id': event_id}) if event is None: raise Http404 fmt = "%Y%m%dT%H%M%SZ" start_date = event['when'].strftime(fmt) duration = dt.timedelta(hours=1) ed = (event['when'] + duration) end_date = ed.strftime(fmt) gcal_info = { "action": "TEMPLATE", "text": event['description'].encode('utf-8'), "dates": "%s/%s" % (start_date, end_date), "details": "", "location": event['location'].encode('utf-8'), "trp": "false", "sprop": "http://%s/" % Site.objects.all()[0].domain, "sprop": "name:billy" } gcal_string = urllib.urlencode(gcal_info) return render(request, templatename('event'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), event=event, sources=event['sources'], gcal_info=gcal_info, gcal_string=gcal_string, nav_active='events'))
def process_view(self, request, func, args, kw): # Skip API or admin views. for path in ['/admin', '/api']: if request.path.startswith(path): return func(request, *args, **kw) # For public views, make sure the state is active. if 'abbr' in kw: if kw['abbr'] not in settings.ACTIVE_STATES + ['all']: try: metadata = Metadata.get_object(kw['abbr']) except DoesNotExist: raise Http404 return render(request, templatename('state_not_active_yet'), dict(metadata=metadata, nav_active=None)) else: return func(request, *args, **kw)
def bill(request, abbr, bill_id): bill = db.bills.find_one({'_id': bill_id}) if bill is None: raise Http404 show_all_sponsors = request.GET.get('show_all_sponsors') return render_to_response( template_name=templatename('bill'), dictionary=dict( vote_preview_row_template=templatename('vote_preview_row'), bill_progress_template=templatename('bill_progress_template'), abbr=abbr, state=Metadata.get_object(abbr), bill=bill, show_all_sponsors=show_all_sponsors, sources=bill['sources'], statenav_active='bills'), context_instance=RequestContext(request, default_context))
def committees_chamber(request, abbr, chamber): try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 chamber_name = meta['%s_chamber_name' % chamber] # Query params spec = {'chamber': chamber} fields = ['committee', 'subcommittee', 'members'] fields = dict(zip(fields, repeat1)) sort_key = 'committee' sort_order = 1 if request.GET: sort_key = request.GET['key'] sort_order = int(request.GET['order']) committees = meta.committees(spec, fields=fields, sort=[(sort_key, sort_order)]) sort_order = {1: -1, -1: 1}[sort_order] chamber_select_form = ChamberSelectForm.unbound(meta, chamber) return render_to_response( template_name=templatename('committees_chamber'), dictionary=dict( committees=committees, abbr=abbr, metadata=meta, chamber_name=chamber_name, chamber_select_form=chamber_select_form, chamber_select_template=templatename('chamber_select_form'), committees_table_template=templatename('committees_table'), chamber_select_collection='committees', sort_order=sort_order, statenav_active='committees'), context_instance=RequestContext(request, default_context))
def get_context_data(self, *args, **kwargs): super(ListViewBase, self).get_context_data(*args, **kwargs) abbr = self.kwargs['abbr'] if abbr == 'all': metadata = None else: metadata = Metadata.get_object(abbr) context = {} context.update(column_headers_tmplname=self.column_headers_tmplname, rowtemplate_name=self.rowtemplate_name, description_template=self.description_template, object_list=self.get_queryset(), nav_active=self.nav_active, abbr=abbr, metadata=metadata, url=self.request.path, use_table=getattr(self, 'use_table', False)) # Include the kwargs to enable references to url paramaters. context.update(**kwargs) # Get the formatted page title and description. # Wait to render until get_object has been called in subclasses. if not getattr(self, 'defer_rendering_title', False): for attr in ('title', 'description'): if attr not in context: context[attr] = self._render(attr, context, request=self.request) # Add the correct path to paginated links. Yuck. if self.request.GET: params = dict(self.request.GET.items()) if 'page' in params: del params['page'] for k, v in params.items(): params[k] = unicode(v).encode('utf8') context.update(get_params=urllib.urlencode(params)) return context
def state(request, abbr): report = db.reports.find_one({'_id': abbr}) try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 chambers = [ overview.chamber(abbr, 'upper'), overview.chamber(abbr, 'lower'), ] return render_to_response( template_name=templatename('state'), dictionary=dict(abbr=abbr, metadata=meta, sessions=report.session_link_data(), chambers=chambers, recent_actions=overview.recent_actions(abbr), statenav_active=None), context_instance=RequestContext(request, default_context))
def events(request, abbr): year = request.GET.get('year') month = request.GET.get('month') if year and month: if month == "0": month = 1 month = int(month) display_date = datetime.datetime(year=int(year), month=month, day=1) else: display_date = datetime.datetime.now() # Compensate for js dates. events = _get_events(abbr, display_date.year, display_date.month - 1) return TemplateResponse( request, templatename('events'), dict(abbr=abbr, display_date=display_date, metadata=Metadata.get_object(abbr), events=events, event_template=templatename('_event'), events_list_template=templatename('events-pjax'), nav_active='events'))
def vote(request, abbr, vote_id): ''' Context: - abbr - metadata - bill - vote - nav_active Templates: - vote.html ''' vote = db.votes.find_one(vote_id) if vote is None: raise Http404('no such vote: {0}'.format(vote_id)) bill = vote.bill() return render(request, templatename('vote'), dict(abbr=abbr, metadata=Metadata.get_object(abbr), bill=bill, vote=vote, nav_active='bills'))
def recent_actions(abbr): state = Metadata.get_object(abbr) bills = state.bills({ 'session': state.most_recent_session, '$or': [{ 'actions.type': 'bill:passed' }, { 'actions.type': 'bill:introduced' }], 'type': 'bill' }) bills_by_action = defaultdict(list) for bill in bills: for action in bill['actions']: actor = re.search(r'(upper|lower)', action['actor']) if actor: actor = actor.group() else: continue for type_ in action['type']: if type_ in ['bill:passed', 'bill:introduced']: bills_by_action[(type_, actor)].append( (action['date'], bill)) def f(type_, chamber): bills = list( sorted(bills_by_action[(type_, chamber)], reverse=True, key=itemgetter(0)))[:2] return map(itemgetter(1), bills) res = dict(passed_upper=f('bill:passed', 'upper'), passed_lower=f('bill:passed', 'lower'), introduced_upper=f('bill:introduced', 'upper'), introduced_lower=f('bill:introduced', 'lower')) return res
def legislator(request, abbr, leg_id): ''' Note - changes needed before we can display "sessions served" info. ''' try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 legislator = db.legislators.find_one({'_id': leg_id}) if legislator is None: raise Http404('No legislator was found with led_id = %r' % leg_id) if not legislator['active']: return legislator_inactive(request, abbr, legislator) # Note to self: Slow query sponsored_bills = legislator.sponsored_bills( limit=5, sort=[('actions.1.date', pymongo.DESCENDING)]) # Note to self: Another slow query legislator_votes = legislator.votes_3_sorted() has_votes = bool(legislator_votes) return render_to_response( template_name=templatename('legislator'), dictionary=dict( feed_entry_template=templatename('feed_entry'), vote_preview_row_template=templatename('vote_preview_row'), roles=legislator.roles_manager, abbr=abbr, metadata=meta, legislator=legislator, sources=legislator['sources'], sponsored_bills=sponsored_bills, legislator_votes=legislator_votes, has_votes=has_votes, statenav_active='legislators'), context_instance=RequestContext(request, default_context))
def get_queryset(self): abbr = self.kwargs['abbr'] if abbr != 'all': metadata = Metadata.get_object(abbr) else: metadata = None FilterBillsForm = get_filter_bills_form(metadata) # start with the spec spec = {} if abbr != 'all': spec['abbr'] = abbr # Setup the paginator. get = self.request.GET.get show_per_page = getattr(self, 'show_per_page', 10) show_per_page = int(get('show_per_page', show_per_page)) try: page = int(get('page', 1)) except ValueError: raise Http404('no such page') if show_per_page > 100: show_per_page = 100 # If search params are given: form = FilterBillsForm(self.request.GET) search_text = form.data.get('search_text') if form.data: form_abbr = form.data.get('abbr') if form_abbr: spec['abbr'] = form_abbr chamber = form.data.get('chamber') if chamber: spec['chamber'] = chamber subjects = form.data.getlist('subjects') if subjects: spec['subjects'] = subjects sponsor_id = form.data.get('sponsor__leg_id') if sponsor_id: spec['sponsor_id'] = sponsor_id if 'status' in form.data: status_choices = form.data.getlist('status') spec['status'] = status_choices type_ = form.data.get('type') if type_: spec['type_'] = type_ session = form.data.get('session') if session: spec['session'] = session sort = self.request.GET.get('sort', 'last') result = Bill.search(search_text, sort=sort, **spec) return self.paginator(result, page=page, show_per_page=show_per_page)
def legislators(request, abbr): ''' Context: - metadata - chamber - chamber_title - chamber_select_template - chamber_select_collection - chamber_select_chambers - show_chamber_column - abbr - legislators - sort_order - sort_key - legislator_table - nav_active Templates: - billy/web/public/legislators.html - billy/web/public/chamber_select_form.html - billy/web/public/legislator_table.html ''' try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 spec = {'active': True, 'district': {'$exists': True}} chambers = dict((k, v['name']) for k, v in meta['chambers'].iteritems()) chamber = request.GET.get('chamber', 'both') if chamber in chambers: spec['chamber'] = chamber chamber_title = meta['chambers'][chamber]['title'] + 's' else: chamber = 'both' chamber_title = 'Legislators' fields = mongo_fields('leg_id', 'full_name', 'photo_url', 'district', 'party', 'first_name', 'last_name', 'chamber', billy_settings.LEVEL_FIELD, 'last_name') sort_key = 'district' sort_order = 1 if request.GET: sort_key = request.GET.get('key', sort_key) sort_order = int(request.GET.get('order', sort_order)) legislators = meta.legislators(extra_spec=spec, fields=fields) def sort_by_district(obj): matchobj = re.search(r'\d+', obj.get('district', '') or '') if matchobj: return int(matchobj.group()) else: return obj.get('district', '') legislators = sorted(legislators, key=sort_by_district) if sort_key != 'district': legislators = sorted(legislators, key=operator.itemgetter(sort_key), reverse=(sort_order == -1)) else: legislators = sorted(legislators, key=sort_by_district, reverse=bool(0 > sort_order)) sort_order = {1: -1, -1: 1}[sort_order] legislators = list(legislators) return TemplateResponse( request, templatename('legislators'), dict(metadata=meta, chamber=chamber, chamber_title=chamber_title, chamber_select_template=templatename('chamber_select_form'), chamber_select_collection='legislators', chamber_select_chambers=chambers, show_chamber_column=True, abbr=abbr, legislators=legislators, sort_order=sort_order, sort_key=sort_key, legislator_table=templatename('legislator_table'), nav_active='legislators'))
def search(request, abbr): ''' Context: - search_text - abbr - metadata - found_by_id - bill_results - more_bills_available - legislators_list - nav_active Tempaltes: - billy/web/public/search_results_no_query.html - billy/web/public/search_results_bills_legislators.html - billy/web/public/bills_list_row_with_abbr_and_session.html ''' if not request.GET: return render(request, templatename('search_results_no_query'), {'abbr': abbr}) search_text = unicode(request.GET['search_text']).encode('utf8') # First try to get by bill_id. if re.search(r'\d', search_text): url = '/%s/bills?' % abbr url += urllib.urlencode([('search_text', search_text)]) return redirect(url) else: found_by_id = False kwargs = {} if abbr != 'all': kwargs['abbr'] = abbr bill_results = Bill.search(search_text, sort='last', **kwargs) # Limit the bills if it's a search. bill_result_count = len(bill_results) more_bills_available = (bill_result_count > 5) bill_results = bill_results[:5] # See if any legislator names match. First split up name to avoid # the Richard S. Madaleno problem. See Jira issue OS-32. textbits = search_text.split() textbits = filter(lambda s: 2 < len(s), textbits) textbits = filter(lambda s: '.' not in s, textbits) andspec = [] for text in textbits: andspec.append({'full_name': {'$regex': text, '$options': 'i'}}) if andspec: spec = {'$and': andspec} else: spec = {'full_name': {'$regex': search_text, '$options': 'i'}} # Run the query. if abbr != 'all': spec[settings.LEVEL_FIELD] = abbr legislator_results = list( db.legislators.find(spec).sort([('active', -1)])) if abbr != 'all': metadata = Metadata.get_object(abbr) else: metadata = None return render( request, templatename('search_results_bills_legislators'), dict( search_text=search_text, abbr=abbr, metadata=metadata, found_by_id=found_by_id, bill_results=bill_results, bill_result_count=bill_result_count, more_bills_available=more_bills_available, legislators_list=legislator_results, column_headers_tmplname=None, # not used rowtemplate_name=templatename('bills_list_row_with' '_abbr_and_session'), show_chamber_column=True, nav_active=None))
def region(request, abbr): ''' Context: - abbr - metadata - sessions - chambers - joint_committee_count - nav_active Templates: - bill/web/public/region.html ''' report = db.reports.find_one({'_id': abbr}) try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 # count legislators legislators = meta.legislators({'active': True}, { 'party': True, 'chamber': True }) # Maybe later, mapreduce instead? party_counts = defaultdict(lambda: defaultdict(int)) for leg in legislators: if 'chamber' in leg: # exclude lt. governors party_counts[leg['chamber']][leg['party']] += 1 chambers = [] for chamber_type, chamber in meta['chambers'].items(): res = {} # chamber metadata res['type'] = chamber_type res['title'] = chamber['title'] res['name'] = chamber['name'] # legislators res['legislators'] = { 'count': sum(party_counts[chamber_type].values()), 'party_counts': dict(party_counts[chamber_type]), } # committees res['committees_count'] = meta.committees({ 'chamber': chamber_type }).count() res['latest_bills'] = meta.bills({ 'chamber': chamber_type }).sort([('action_dates.first', -1)]).limit(2) res['passed_bills'] = meta.bills({ 'chamber': chamber_type }).sort([('action_dates.passed_' + chamber_type, -1)]).limit(2) chambers.append(res) joint_committee_count = meta.committees({'chamber': 'joint'}).count() # add bill counts to session listing sessions = meta.sessions() for s in sessions: try: s['bill_count'] = ( report['bills']['sessions'][s['id']]['upper_count'] + report['bills']['sessions'][s['id']]['lower_count']) except KeyError: # there's a chance that the session had no bills s['bill_count'] = 0 return render( request, templatename('region'), dict(abbr=abbr, metadata=meta, sessions=sessions, chambers=chambers, joint_committee_count=joint_committee_count, nav_active='home'))
def legislators(request, abbr): try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 spec = {'active': True} chamber = request.GET.get('chamber', 'both') if chamber in ('upper', 'lower'): spec['chamber'] = chamber else: chamber = 'both' fields = ['leg_id', 'full_name', 'photo_url', 'district', 'party', 'chamber', 'state', 'last_name'] fields = dict(zip(fields, repeat1)) sort_key = 'district' sort_order = 1 if request.GET: sort_key = request.GET.get('key', sort_key) sort_order = int(request.GET.get('order', sort_order)) legislators = meta.legislators(extra_spec=spec, fields=fields) def sort_by_district(obj): matchobj = re.search(r'\d+', obj['district']) if matchobj: return int(matchobj.group()) else: return obj['district'] legislators = sorted(legislators, key=sort_by_district) if sort_key != 'district': legislators = sorted(legislators, key=itemgetter(sort_key), reverse=(sort_order == -1)) else: legislators = sorted(legislators, key=sort_by_district, reverse=bool(0 > sort_order)) sort_order = {1: -1, -1: 1}[sort_order] legislators = list(legislators) initial = {'key': 'district', 'chamber': chamber} chamber_select_form = ChamberSelectForm.unbound(meta, initial=initial) return render_to_response( template_name=templatename('legislators_chamber'), dictionary=dict( metadata=meta, chamber=chamber, chamber_select_form=chamber_select_form, chamber_select_template=templatename('chamber_select_form'), chamber_select_collection='legislators', show_chamber_column=True, abbr=abbr, legislators=legislators, sort_order=sort_order, sort_key=sort_key, legislator_table=templatename('legislator_table'), statenav_active='legislators', ), context_instance=RequestContext(request, default_context))
def committees(request, abbr): ''' Context: chamber committees abbr metadata chamber_name chamber_select_template chamber_select_collection chamber_select_chambers committees_table_template show_chamber_column sort_order nav_active Templates: - billy/web/public/committees.html - billy/web/public/committees-pjax.html - billy/web/public/chamber_select_form.html - billy/web/public/committees_table.html ''' try: meta = Metadata.get_object(abbr) except DoesNotExist: raise Http404 chamber = request.GET.get('chamber', 'both') if chamber in ('upper', 'lower'): chamber_name = meta['chambers'][chamber]['name'] spec = {'chamber': chamber} show_chamber_column = False elif chamber == 'joint': chamber_name = 'Joint' spec = {'chamber': 'joint'} show_chamber_column = False else: chamber = 'both' spec = {} show_chamber_column = True chamber_name = '' chambers = dict((k, v['name']) for k, v in meta['chambers'].items()) if meta.committees({'chamber': 'joint'}).count(): chambers['joint'] = 'Joint' fields = mongo_fields('committee', 'subcommittee', 'members', settings.LEVEL_FIELD, 'chamber') sort_key = request.GET.get('key', 'committee') sort_order = int(request.GET.get('order', 1)) committees = meta.committees_legislators(spec, fields=fields, sort=[(sort_key, sort_order)]) sort_order = -sort_order return TemplateResponse( request, templatename('committees'), dict(chamber=chamber, committees=committees, abbr=abbr, metadata=meta, chamber_name=chamber_name, chamber_select_template=templatename('chamber_select_form'), chamber_select_collection='committees', chamber_select_chambers=chambers, committees_table_template=templatename('committees_table'), show_chamber_column=show_chamber_column, sort_order=sort_order, nav_active='committees'))