sunlight-1.1.5/0000775000175000017500000000000011773413356012737 5ustar tagtag00000000000000sunlight-1.1.5/examples/0000775000175000017500000000000011773413356014555 5ustar tagtag00000000000000sunlight-1.1.5/examples/cross-api/0000775000175000017500000000000011773413356016455 5ustar tagtag00000000000000sunlight-1.1.5/examples/cross-api/free_market_lovers0000775000175000017500000000105211754226063022253 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import capitolwords from sunlight import congress for person in capitolwords.phrases_by_entity( "legislator", phrase="free market", sort="count", ): n = congress.legislators( bioguide_id=person['legislator'], all_legislators="true" ) if len(n) >= 1: n = n[0] print( "%s %s %s (%s)" % ( n['title'], n['firstname'], n['lastname'], n['party'] )) else: print( "Missing data on %s" % person['legislator'] ) sunlight-1.1.5/examples/cross-api/death-metal0000775000175000017500000000235311754226063020567 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012, BSD-3 clause, Sunlight Labs from sunlight import capitolwords from sunlight import congress phrase = "death metal" # Today, we'll be printing out the Twitter IDs of all legislators that use # this phrase most in the congressional record. for cw_record in capitolwords.phrases_by_entity( "legislator", # We're getting all legislators sort="count", # sorted by how much they say phrase=phrase, # this word )[:6]: # We'll just try the top 5 legislators legislator = congress.legislators( bioguide_id=cw_record['legislator'], # Look up this biogude (unique ID) # for every fed. legislator all_legislators="true" # search retired legislators ) if len(legislator) >= 1: # If we were able to find the legislator legislator = legislator[0] # (this is a search, so it's a list) if legislator['twitter_id'] != "": # and they have a Twitter ID print "%s. %s (@%s) said %s %s times" % ( legislator['title'], legislator['lastname'], legislator['twitter_id'], phrase, int(cw_record['count']) ) # Print it to output :) sunlight-1.1.5/examples/openstates/0000775000175000017500000000000011773413356016742 5ustar tagtag00000000000000sunlight-1.1.5/examples/openstates/ca_bill_lookup0000775000175000017500000000050411754226063021641 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file from __future__ import print_function from sunlight import openstates bill = openstates.bill_detail( 'ca', '20092010', 'AB 667') print( "%s - %s" % ( bill['bill_id'], bill['+short_title'] )) sunlight-1.1.5/examples/openstates/tx_events0000775000175000017500000000067711754226063020715 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file. from __future__ import print_function from sunlight import openstates tx_events = openstates.events( state='tx', type='committee:meeting' ) for event in tx_events: print( "Event @ %s" % event['when'] ) for who in event['participants']: print( " %s (%s)" % ( who['participant'], who['chamber'] )) sunlight-1.1.5/examples/openstates/get_rep_by_lat_lon0000775000175000017500000000061511754226063022515 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file from __future__ import print_function from sunlight import openstates reps = openstates.legislator_geo_search( longitude="-78.76648", latitude="35.81336" ) for rep in reps: print( "%s - %s %s" % ( rep['chamber'], rep['first_name'], rep['last_name'] )) sunlight-1.1.5/examples/openstates/md_ctty_lookup0000775000175000017500000000047011754226063021721 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file from __future__ import print_function from sunlight import openstates ctty = openstates.committee_detail( "MDC000065" ) print( "%s is the %s" % ( ctty['id'], ctty['committee'] )) sunlight-1.1.5/examples/openstates/vt_agro_bills0000775000175000017500000000053711754226063021517 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file from __future__ import print_function from sunlight import openstates vt_agro_bills = openstates.bills( q='agriculture', state='vt', chamber='upper' ) for bill in vt_agro_bills: print( bill['title'] ) sunlight-1.1.5/examples/openstates/get_json_vt_agro0000775000175000017500000000053211754226063022215 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file from __future__ import print_function import json from sunlight import openstates vt_agro_bills = openstates.bills( q='agriculture', state='vt', chamber='upper' ) print( json.dumps( vt_agro_bills )) sunlight-1.1.5/examples/openstates/ca_dems0000775000175000017500000000065711754226063020267 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file from __future__ import print_function from sunlight import openstates ca_dems = openstates.legislators( state='ca', party='Democratic', first_name='Bob', active='true' ) for dem in ca_dems: print( "%s %s (%s)" % ( dem['first_name'], dem['last_name'], dem['chamber'] )) sunlight-1.1.5/examples/openstates/md_cttys0000775000175000017500000000054411754226063020515 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) 2012 Paul Tagliamonte # under the terms of the LICENSE file from __future__ import print_function from sunlight import openstates md_cttys = openstates.committees( state='md', chamber='upper' ) for ctty in md_cttys: print( "%s (%s)" % ( ctty['committee'], ctty['chamber'] )) sunlight-1.1.5/examples/capitolwords/0000775000175000017500000000000011773413356017267 5ustar tagtag00000000000000sunlight-1.1.5/examples/capitolwords/gingrich_words0000775000175000017500000000044411754226063022223 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import capitolwords newt = "G000225" favorate_phrases = capitolwords.phrases( "legislator", "G000225", sort="count desc") for phrase in favorate_phrases: print( "%s: %s" % ( phrase['ngram'], phrase['count'] )) sunlight-1.1.5/examples/capitolwords/internet_dates0000775000175000017500000000042111754226063022216 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import capitolwords print( "Internet was mentioned N times on the following days:" ) print( "" ) for date in capitolwords.dates("internet"): print( "%s - %s" % ( date['count'], date['day'] )) sunlight-1.1.5/examples/capitolwords/obama_records0000775000175000017500000000035611754226063022015 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import capitolwords for phrase in capitolwords.text( phrase="obama administration" ): print( "%s mentions Obama on %s" % ( phrase['title'], phrase['date'] )) sunlight-1.1.5/examples/capitolwords/july_2010_phrases0000775000175000017500000000036611754226063022370 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import capitolwords for phrase in capitolwords.phrases( "month", "201007", sort="count desc" ): print( "%s was used %s times" % ( phrase['ngram'], phrase['count'] )) sunlight-1.1.5/examples/capitolwords/legislators_who_love_free_market0000775000175000017500000000041611754226063026010 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import capitolwords for person in capitolwords.phrases_by_entity( "legislator", phrase="free market", sort="count", ): print( "Congress BioGuide ID: %s" % person['legislator'] ) sunlight-1.1.5/examples/influenceexplorer/0000775000175000017500000000000011773413356020306 5ustar tagtag00000000000000sunlight-1.1.5/examples/influenceexplorer/contrib_to_mikulski0000775000175000017500000000063611754226063024307 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import influenceexplorer contrib = influenceexplorer.contributions( contributor_state="md|va", recipient_ft="mikulski", cycle="2008" ) for contributor in contrib: print( "%s from %s contributed %s" % ( contributor['contributor_name'], contributor['contributor_city'], contributor['amount'] )) sunlight-1.1.5/examples/influenceexplorer/lobby_for_pfizer0000775000175000017500000000053211754226063023564 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import influenceexplorer lobs = influenceexplorer.lobbying( client_ft="pfizer", year="2011" ) for lob in lobs: print( lob['registrant_name'] ) for issue in lob['issues']: print( " %s (%s)" % ( issue['general_issue'], issue['specific_issue'] )) sunlight-1.1.5/examples/influenceexplorer/nancy_givers0000775000175000017500000000047311754226063022723 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import influenceexplorer givers = influenceexplorer.entities( search="Nancy Pelosi" ) for entity in givers: print( "A(n) %s named %s gave %s" % ( entity['type'], entity['name'], entity['total_received'] )) sunlight-1.1.5/examples/influenceexplorer/homeland_security_grants0000775000175000017500000000052711754226063025330 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import influenceexplorer grants = influenceexplorer.grants( agency_ft="Homeland Security" ) for grant in grants: print( "%s to %s for %s" % ( grant['total_funding_amount'], grant['recipient_name'], grant['project_description'] )) sunlight-1.1.5/examples/influenceexplorer/microsoft_contracts0000775000175000017500000000060411754226063024315 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import influenceexplorer contracts = influenceexplorer.contracts( vendor_name="Microsoft" ) for contract in contracts: print( "%s contract for at least %s to %s" % ( contract['transaction_status'], contract['obligatedamount'], contract['descriptionofcontractrequirement'] )) sunlight-1.1.5/examples/congress/0000775000175000017500000000000011773413356016400 5ustar tagtag00000000000000sunlight-1.1.5/examples/congress/get_nacy0000775000175000017500000000037111754226063020114 0ustar tagtag00000000000000#!/usr/bin/env python from __future__ import print_function from sunlight import congress nancy = congress.legislators( lastname="Pelosi" )[0] print( "%s %s %s (%s)" % ( nancy['title'], nancy['firstname'], nancy['lastname'], nancy['party'] )) sunlight-1.1.5/PKG-INFO0000664000175000017500000000525511773413356014043 0ustar tagtag00000000000000Metadata-Version: 1.0 Name: sunlight Version: 1.1.5 Summary: Unified Sunlight API bindings Home-page: https://github.com/sunlightlabs/python-sunlight Author: Paul Tagliamonte Author-email: paultag@sunlightfoundation.com License: BSD Description: python-sunlight =============== This project is an attempt to unify all the Sunlight API bindings into a single project that is clear, concise, easy to read, powerful, and fun to play with. Setup ***** Using this library is very easy - by default, python-sunlight will search for API keys in two places. First, ``~/.sunlight.key`` will be read, and the contents of that file will be used as the API Key. Secondly, if an enviroment variable called ``SUNLIGHT_API_KEY`` is set, that will be used (in the case of both being read, the enviroment variable *will* override the file.) To register for an API key, if you don't have one, please fill out the form `here `_. The easiest way to write this file out is by running a command similar to this ( on systems that support a POSIX shell): echo "API_KEY" > ~/.sunlight.key where `API_KEY` is actually the string of letters and numbers that was emailed to you. Actually putting `API_KEY` into this file will most likely result in an error from the server. You can confirm they key with the following command: cat ~/.sunlight.key This should output the string that was emailed to you. Help me! ******** Basic usage and some brief examples can be found on `readthedocs `_. If this doens't help, feel free to email for help, ask over IRC in ``#sunlightlabs`` on ``irc.freenode.net``, or open a issue if it's a particularly nasty bug (particularly regarding ambiguous documentation, or poorly exposed API methods). License ******* All code in this project is licensed under a BSD-3 clause style license. The exact terms are in the `LICENSE` file, which will be distributed with any copy of the source you recieve. Contribute ********** Bugfixes, documentation contributions and more extensive (yet clear) example scripts are all welcome and encouraged. Please open a pull-request against python-sunlight, or email a format-patch to the email address listed in the setup.py script. Platform: any sunlight-1.1.5/sunlight/0000775000175000017500000000000011773413356014574 5ustar tagtag00000000000000sunlight-1.1.5/sunlight/config.py0000664000175000017500000000252111754226063016407 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. """ .. module:: sunlight :synopsis: Constants and other Globally read things .. warning:: If you're using these directly in your app, you might be doing something wrong. """ API_KEY = None """ This might be populated from :func:`sunlight.attempt_to_load_apikey`, or ``None`` (as it is out of the box). All :class:`sunlight.service.Service` objects will make use of this API key (once, in it's __init__, not after that) to do their job. .. note:: All Sunlight services share API keys. Nice, right? """ API_SIGNUP_PAGE = "http://services.sunlightlabs.com/accounts/register/" """ This is a link to the API Key signup page - so that we can sanely direct people to register for a key (if they don't already have one) -- after all, signing up for a Sunlight API key is fun for the whole family! """ KEY_LOCATION = "~/.sunlight.key" """ This is the location of the api key that's stored on the filesystem. Currently, it uses a file directly under a tilde, so that windows users don't have to feel as much pain when using the API. Usually this is something like ``~/.sunlight.key`` """ KEY_ENVVAR = "SUNLIGHT_API_KEY" """ This is the name of the ``os.environ`` key to look for. It's usually something stupid simple, like ``SUNLIGHT_API_KEY``. """ sunlight-1.1.5/sunlight/errors.py0000664000175000017500000000314511754232524016460 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. """ .. module:: sunlight.errors :synopsis: Exceptions and Errors """ class SunlightException(Exception): """ :class:`sunlight.errors.SunlightException` is the base exception, all other sunlight exceptions (such as :class:`sunlight.errors.NoAPIKeyException`) all inherit from this. This makes it easy to catch all sunlight errors if you really really need to (not that you should) """ def __init__(self, value): """ This is just your basic __init__ method, nothing special here. Args: value (str): Message to report with the Exception """ self.value = value def __str__(self): """ Return the string-ular representation of the exception - this makes it super easy to just run something like ``print e`` (given ``e`` is a SunlightException instance) """ return repr(self.value) class BadRequestException(SunlightException): """ This gets thrown when the underlying url request has recieved an abnormal response code, or the program has issued a request that can not be filled. """ pass class InvalidRequestException(BadRequestException): """ This gets thrown when the API gets a valid response, but has an error that should be passed back to the program. """ pass class NoAPIKeyException(SunlightException): """ This gets thrown if the bindings are asked to issue a request, but the ``sunlight.config.API_KEY`` variable is ``None``. """ pass sunlight-1.1.5/sunlight/service.py0000664000175000017500000000470711773412670016614 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. """ .. module:: sunlight.service :synopsis: Sunlight API Superclass Base service class. All API classes (such as say - :class:`sunlight.services.openstates.OpenStates`) inherit from this. """ import sys import sunlight.config import sunlight.errors if sys.version_info[0] >= 3: from urllib.parse import urlencode from urllib.request import urlopen from urllib.error import HTTPError _str_type = str else: from urllib import urlencode from urllib2 import urlopen from urllib2 import HTTPError _str_type = basestring def safe_encode(kwargs): kwargs = kwargs.copy() for k, v in kwargs.iteritems(): if isinstance(v, _str_type): kwargs[k] = v.encode('utf8') return urlencode(kwargs) class Service: """ Base class for all the API implementations, as well as a bunch of common code on how to actually fetch text over the network. """ def get(self, top_level_object, **kwargs): """ Get some data from the network - this is where we actually fetch something and make a request. .. warning:: Be sure that API_KEY was set before calling this method. This will throw a :class:`sunlight.errors.NoAPIKeyException` if the API_KEY is not set. args: ``top_level_object`` (str): Thing to query for (such as say, "bills" for OpenStates ) kwargs: These arguments will be passed to the underlying API implementation to help create a query. Validation will happen down below, and on a per-API level. """ if not sunlight.config.API_KEY: raise sunlight.errors.NoAPIKeyException( "Warning: Missing API Key. please visit " + sunlight.config.API_SIGNUP_PAGE + " to register for a key.") url = self._get_url(top_level_object, sunlight.config.API_KEY, **kwargs) try: r = urlopen(url) return_data = r.read().decode('utf8') return self._decode_response(return_data) except HTTPError as e: message = e.read() code = e.getcode() ex = sunlight.errors.BadRequestException("Error (%s) -- %s" % ( code, message )) ex.url = e.geturl() ex.message = message ex.code = code raise ex sunlight-1.1.5/sunlight/services/0000775000175000017500000000000011773413356016417 5ustar tagtag00000000000000sunlight-1.1.5/sunlight/services/influenceexplorer.py0000664000175000017500000000564311773412670022530 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. """ .. module:: sunlight.services.influenceexplorer :synopsis: InfluenceExplorer API Implementation InfluenceExplorer API Implementation inside ``python-sunlight``. """ from sunlight.errors import InvalidRequestException import sunlight.service import json service_url = "http://transparencydata.com/api/1.0" class InfluenceExplorer(sunlight.service.Service): """ Bindings into the `InfluenceExplorer `_ project. Be careful to note that this is all a very thing layer over the actual API it's self, so be sure to consult the `docs `_ when in doubt over a method's usage. """ def contributions(self, **kwargs): """ Query the InfluenceExplorer server for information regarding political campaign contributions. The docs for this method can be found in the `docs `_. """ return self.get("contributions", **kwargs) def lobbying(self, **kwargs): """ Query the InfluenceExplorer server for information regarding federal lobbying. The docs for this method can be found in the `docs `_ """ return self.get("lobbying", **kwargs) def grants(self, **kwargs): """ Query the InfluenceExplorer server for information regarding federal grants. The docs for this method can be found in the `docs `_ """ return self.get("grants", **kwargs) def contracts(self, **kwargs): """ Query the InfluenceExplorer server for information regarding federal contracts. The docs for this method can be found in the `docs `_ """ return self.get("contracts", **kwargs) def entities(self, **kwargs): """ Query the InfluenceExplorer server for information regarding aggregate contributions by a given entity. It sounds much more confusing then it really is. The docs for this method can be found in the `docs `_ """ return self.get("entities", **kwargs) # API impl methods below def _get_url( self, obj, apikey, **kwargs ): return "%s/%s?apikey=%s&%s" % ( service_url, obj, apikey, sunlight.service.safe_encode(kwargs) ) def _decode_response( self, response ): ret = json.loads( response ) if "error" in ret: ex = InvalidRequestException( ret['error'] ) ex.response = ret raise ex return ret sunlight-1.1.5/sunlight/services/congress.py0000664000175000017500000001162311773412670020615 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. """ .. module:: sunlight.services.congress :synopsis: Sunlight Congress API Implementation Sunlight Congress API Implementation inside ``python-sunlight``. """ import sunlight.service import json service_url = "http://services.sunlightlabs.com/api/" def _unpack(resp, key): return [e[key] for e in resp[key+'s']] class congress(sunlight.service.Service): """ Bindings into the `Sunlight Congress API `_, an API primarily for details on current federal legislators. """ def legislators(self, **kwargs): """ Query for all legislators matching certain criteria. See documentation at `legislators.get(List) `_ """ return _unpack(self.get('legislators.getList', **kwargs), 'legislator') def legislator_search(self, name, threshold=0.9, all_legislators=False): """ Fuzzy-matching name search against federal legislators. See documentation at `legislators.search `_ """ params = {'name': name, 'threshold': threshold} if all_legislators: params['all_legislators'] = 1 return _unpack(self.get('legislators.search', **params), 'result') def legislators_for_zip(self, zipcode): """ Query for all legislators representing a given ZIP code. This method is not recommended, prefer legislators_for_lat_lon instead. See the blog post `"Don't Use Zip Codes Unless You Have To" `_. See documentation at `legislators.allForZip `_ """ return _unpack(self.get('legislators.allForZip', zip=zipcode), 'legislator' ) def legislators_for_lat_lon(self, latitude, longitude): """ Query for all legislators representing an given location. See documentation at `legislators.allForLatLong `_ """ return _unpack(self.get('legislators.allForLatLong', latitude=latitude, longitude=longitude), 'legislator') def districts_for_zip(self, zipcode): """ Query for all congressional districts overlapping a zip code. See documentation at `districts.getDistrictFromLatLong `_ """ return _unpack(self.get('districts.getDistrictsFromZip', zip=zipcode), 'district' ) def districts_for_lat_lon(self, latitude, longitude): """ Query for all congressional districts containing a given location. See documentation at `districts.getDistrictFromLatLong `_ """ return _unpack(self.get('districts.getDistrictFromLatLong', latitude=latitude, longitude=longitude), 'district' ) def committees(self, chamber): """ Query for all committees for a chamber. (House|Senate|Joint) See documentation at `committees.getList `_ """ return _unpack(self.get('committees.getList', chamber=chamber), 'committee') def committee_detail(self, id): """ Query for all details for a committee, including members. See documentation at `committees.get `_ """ return self.get('committees.get', id=id)['committee'] def committees_for_legislator(self, bioguide_id): """ Query for all details for all of a legislator's committee assignments. See documentation at `committees.allForLegislator `_ """ return _unpack(self.get('committees.allForLegislator', bioguide_id=bioguide_id), 'committee') # implementation methods def _get_url(self, obj, apikey, **kwargs): return "%s/%s?apikey=%s&%s" % ( service_url, obj, apikey, sunlight.service.safe_encode(kwargs) ) def _decode_response(self, response): return json.loads(response)['response'] sunlight-1.1.5/sunlight/services/openstates.py0000664000175000017500000001563111773412670021162 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. import sunlight.service from sunlight.errors import BadRequestException import json module_name = "openstates" service_url = "http://openstates.org/api/v1" class openstates(sunlight.service.Service): """ Bindings into the `Open States API `_. Keep in mind this is a thin wrapper around the API so the API documentation is the place to look for help on field names and examples. """ def all_metadata(self, **kwargs): """ Get an overview of all available states including each state's name and abbreviation. For details see `Metadata Overview `_. """ return self.get(["metadata"], **kwargs) def state_metadata(self, state, **kwargs): """ Complete metadata for a given state, containing information on the particulars of this state's chambers, sessions, and terms. For details see `State Metadata `_. """ return self.get(["metadata", state], **kwargs) def bills(self, **kwargs): """ Search the entirety of bills available via the Open States API. The fields and keyword arguments can be found on the `Bill API docs `_. """ return self.get(["bills"], **kwargs) def bill(self, bill_id, **kwargs): """ Get full information on a single bill from the Open States API given the OpenStates Bill ID (such as TNB00004685) `Bill API docs `_. """ return self.get(["bills", bill_id], **kwargs) def bill_detail(self, state, session, bill_id, chamber=None): """ Get full information on a single bill from the Open States API given a ``state``, ``session``, and ``bill_id`` (and optionally ``chamber`` if the request would be ambiguous without one). The fields and keyword arguments can be found on the `Open States Bill API docs `_. """ lss = ["bills", state, session] if chamber: lss.append(chamber) lss.append(bill_id) return self.get(lss) def legislators(self, **kwargs): """ Search the entirety of legislators available via the Open States API. The fields and keyword arguments can be found on the `Legislator API docs `_. """ return self.get( [ "legislators"], **kwargs ) def legislator_detail(self, leg_id, **kwargs): """ Get detailed information on a single legislator given their Open States Legislator ID. The ``leg_id`` argument is a legislator ID code used throughout the Open States API, such as ``MDL000210``. For details on fields see the `Legislator API Fields `_. """ return self.get(["legislators", leg_id], **kwargs) def legislator_geo_search(self, latitude, longitude, **kwargs): """ Given a latitude and longitude return all legislators that represent districts containing that point. See the Open States documentation for examples of `Legislator Geo Lookup `_. """ kwargs['lat'] = latitude kwargs['long'] = longitude return self.get(["legislators", "geo"], **kwargs) def committees(self, **kwargs): """ Search against all committees available via the Open States API. Committee fields and keyword arguments can be found on the `Committee API docs `_. """ return self.get(["committees"], **kwargs) def committee_detail(self, committee_id, **kwargs): """ Get detailed information on a single committee given its Open States Committee ID. The ``committee_id`` argument is a committee ID code used throughout the Open States API, such as ``MDC000065``. For details on fields see the `Committee API Fields `_. """ return self.get(["committees", committee_id], **kwargs) def events(self, **kwargs): """ Query the Open States API for information regarding upcoming events taken from a state-level legislative calendar. See the Open States' site for details on the `Event API `_. """ return self.get([ "events" ], **kwargs) def event_detail(self, event_id, **kwargs): """ Get detailed informaton regarding a single event. ``event_id`` is an OpenStates event ID, such as ``TXE00000990``. See the Open States' site for details on the `Event API Fields `_. """ lss = [ "events", event_id ] return self.get( lss, **kwargs ) def districts(self, state, chamber=None, **kwargs): """ Get a listing of districts for a state (optionally narrowed by chamber). For a listing of fields see `District Fields `_. """ pieces = ['districts', state] if chamber: pieces.append(chamber) return self.get(pieces, **kwargs) def district_boundary(self, boundary_id, **kwargs): """ Get a detailed GeoJSON-style boundary for a given district given a boundary_id (available via the :meth:``districts``. ``boundary_id`` resembles ``sldl-tx-state-house-district-35``. For a listing of fields see `District Fields `_. For more information on this method and example output see `District Boundary Lookup `_ """ return self.get(['districts', 'boundary', boundary_id], **kwargs) # API impl methods def _get_url(self, objs, apikey, **kwargs): # Gate for any None's in the query. This is usually a problem. if None in objs: raise BadRequestException("`None' passed to the URL encoder (%s)" % (str(objs))) # join pieces by slashes and add a trailing slash object_path = "/".join(objs) object_path += "/" return "%s/%s?apikey=%s&%s" % ( service_url, object_path, apikey, sunlight.service.safe_encode(kwargs) ) def _decode_response(self, response): return json.loads(response) sunlight-1.1.5/sunlight/services/capitolwords.py0000664000175000017500000000732411773412670021507 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. from sunlight.errors import InvalidRequestException, BadRequestException import sunlight.service import json service_url = "http://capitolwords.org/api" class capitolwords(sunlight.service.Service): """ Bindings into the `CapitolWords project `_. Keep in mind, as you use this wrapper, that this is a very thin translation layer from the API into Python. There's no object magic, so the docs on the API it's self will be as useful as any of these docstrings. Feel free to read up on the CapitolWords API in the `docs `_. If a request goes through and gets a normal response code, but the requested action is for whatever reason errorful, a :class:`sunlight.errors.InvalidRequestException` will be thrown with the error string. """ def dates(self, phrase, **kwargs): """ Retrieve information regarding the popularity of a phrase over a period of time. For a list of optional arguments see `Capitol Words' dates.json endpoint `_. """ kwargs['phrase'] = phrase return self.get( "dates", **kwargs ) def phrases(self, entity_type, entity_value, **kwargs): """ Retrieve information on the top phrases for an facet. A facet can be any date, month, state or legislator. For a list of arguments see `Capitol Words' phrases.json endpoint `_. """ kwargs['entity_type'] = entity_type kwargs['entity_value'] = entity_value return self.get( "phrases", **kwargs ) def phrases_by_entity(self, entity_type, **kwargs): """ Get listing of top facets for a given phrase. A facet can be any date, month, state or legislator. For a list of arguments see `Capitol Words' phrases/entity.json endpoint `_. """ lss = "%s/%s" % ("phrases", entity_type) return self.get( lss, **kwargs ) def text( self, phrase=None, title=None, **kwargs ): """ Full text-search against Capitol Words data. Neither ``phrase`` nor ``title`` are required, but one or the other must be used. If both are omitted, a :class:`sunlight.errors.BadRequestException` will be thrown. ``phrase`` will do a full-text search on that phrase, whereas ``title`` will doa full-text search on the title of each CR (Congressional Record) document. For a list of arguments see `Capitol Words' text.json endpoint `_. """ if not phrase and not title: raise BadRequestException( "You must provide one of phrase or title to this method.") if phrase: kwargs['phrase'] = phrase if title: kwargs['title'] = title return self.get( "text", **kwargs ) # API impl methods below def _get_url( self, obj, apikey, **kwargs ): ret = "%s/%s.json?apikey=%s&%s" % ( service_url, obj, apikey, sunlight.service.safe_encode(kwargs) ) return ret def _decode_response( self, response ): ret = json.loads( response ) if "error" in ret: ex = InvalidRequestException( ret['error'] ) ex.response = ret raise ex if "results" in ret: return ret['results'] # XXX: Verify this is actually # what we want. return ret sunlight-1.1.5/sunlight/services/__init__.py0000664000175000017500000000000011754226063020512 0ustar tagtag00000000000000sunlight-1.1.5/sunlight/__init__.py0000664000175000017500000000341411773413316016703 0ustar tagtag00000000000000# Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. """ .. module:: sunlight :synopsis: Sunlight API Entry Point Sunlight API __init__ entry. This package includes and defines a few aliases, so that folks can just use the facade here, rather then fight with finding the right module to use. """ __appname__ = "sunlight" __version__ = "1.1.5" import sunlight.services.openstates import sunlight.services.capitolwords import sunlight.services.congress import sunlight.services.influenceexplorer openstates = sunlight.services.openstates.openstates() capitolwords = sunlight.services.capitolwords.capitolwords() congress = sunlight.services.congress.congress() influenceexplorer = sunlight.services.influenceexplorer.InfluenceExplorer() import os.path import warnings import sunlight.config import sunlight.service def _attempt_to_load_apikey(): """ This function (which will be auto-called on import of :mod:`sunlight`), will attempt to pull the Sunlight API Key from a few places (to offload complexity of apps using these bindings) before getting too far. .. note:: This function is implemented to let the enviroment variable override the file read key. Keep this in mind when debugging silly issues. """ try: fp = os.path.expanduser(sunlight.config.KEY_LOCATION) fd = open(fp, 'r') sunlight.config.API_KEY = fd.read().strip() except IOError as e: if e.errno != 2: warnings.warn('key file %s exists but could not be opened: %s' % ( sunlight.config.KEY_LOCATION, str(e))) try: sunlight.config.API_KEY = \ os.environ[sunlight.config.KEY_ENVVAR].strip() except KeyError as e: pass _attempt_to_load_apikey() sunlight-1.1.5/README.rst0000664000175000017500000000376011754226063014430 0ustar tagtag00000000000000python-sunlight =============== This project is an attempt to unify all the Sunlight API bindings into a single project that is clear, concise, easy to read, powerful, and fun to play with. Setup ***** Using this library is very easy - by default, python-sunlight will search for API keys in two places. First, ``~/.sunlight.key`` will be read, and the contents of that file will be used as the API Key. Secondly, if an enviroment variable called ``SUNLIGHT_API_KEY`` is set, that will be used (in the case of both being read, the enviroment variable *will* override the file.) To register for an API key, if you don't have one, please fill out the form `here `_. The easiest way to write this file out is by running a command similar to this ( on systems that support a POSIX shell): echo "API_KEY" > ~/.sunlight.key where `API_KEY` is actually the string of letters and numbers that was emailed to you. Actually putting `API_KEY` into this file will most likely result in an error from the server. You can confirm they key with the following command: cat ~/.sunlight.key This should output the string that was emailed to you. Help me! ******** Basic usage and some brief examples can be found on `readthedocs `_. If this doens't help, feel free to email for help, ask over IRC in ``#sunlightlabs`` on ``irc.freenode.net``, or open a issue if it's a particularly nasty bug (particularly regarding ambiguous documentation, or poorly exposed API methods). License ******* All code in this project is licensed under a BSD-3 clause style license. The exact terms are in the `LICENSE` file, which will be distributed with any copy of the source you recieve. Contribute ********** Bugfixes, documentation contributions and more extensive (yet clear) example scripts are all welcome and encouraged. Please open a pull-request against python-sunlight, or email a format-patch to the email address listed in the setup.py script. sunlight-1.1.5/AUTHORS0000664000175000017500000000013411754226063014001 0ustar tagtag00000000000000Paul Tagliamonte James Turk sunlight-1.1.5/sunlight.egg-info/0000775000175000017500000000000011773413356016266 5ustar tagtag00000000000000sunlight-1.1.5/sunlight.egg-info/SOURCES.txt0000664000175000017500000000272011773413355020152 0ustar tagtag00000000000000AUTHORS ChangeLog LICENSE MANIFEST.in README.rst setup.py docs/Makefile docs/source/conf.py docs/source/index.rst docs/source/services/capitolwords.rst docs/source/services/congress.rst docs/source/services/openstates.rst docs/source/sunlight/config.rst docs/source/sunlight/errors.rst docs/source/sunlight/service.rst examples/capitolwords/gingrich_words examples/capitolwords/internet_dates examples/capitolwords/july_2010_phrases examples/capitolwords/legislators_who_love_free_market examples/capitolwords/obama_records examples/congress/get_nacy examples/cross-api/death-metal examples/cross-api/free_market_lovers examples/influenceexplorer/contrib_to_mikulski examples/influenceexplorer/homeland_security_grants examples/influenceexplorer/lobby_for_pfizer examples/influenceexplorer/microsoft_contracts examples/influenceexplorer/nancy_givers examples/openstates/ca_bill_lookup examples/openstates/ca_dems examples/openstates/get_json_vt_agro examples/openstates/get_rep_by_lat_lon examples/openstates/md_ctty_lookup examples/openstates/md_cttys examples/openstates/tx_events examples/openstates/vt_agro_bills sunlight/__init__.py sunlight/config.py sunlight/errors.py sunlight/service.py sunlight.egg-info/PKG-INFO sunlight.egg-info/SOURCES.txt sunlight.egg-info/dependency_links.txt sunlight.egg-info/top_level.txt sunlight/services/__init__.py sunlight/services/capitolwords.py sunlight/services/congress.py sunlight/services/influenceexplorer.py sunlight/services/openstates.pysunlight-1.1.5/sunlight.egg-info/PKG-INFO0000664000175000017500000000525511773413355017371 0ustar tagtag00000000000000Metadata-Version: 1.0 Name: sunlight Version: 1.1.5 Summary: Unified Sunlight API bindings Home-page: https://github.com/sunlightlabs/python-sunlight Author: Paul Tagliamonte Author-email: paultag@sunlightfoundation.com License: BSD Description: python-sunlight =============== This project is an attempt to unify all the Sunlight API bindings into a single project that is clear, concise, easy to read, powerful, and fun to play with. Setup ***** Using this library is very easy - by default, python-sunlight will search for API keys in two places. First, ``~/.sunlight.key`` will be read, and the contents of that file will be used as the API Key. Secondly, if an enviroment variable called ``SUNLIGHT_API_KEY`` is set, that will be used (in the case of both being read, the enviroment variable *will* override the file.) To register for an API key, if you don't have one, please fill out the form `here `_. The easiest way to write this file out is by running a command similar to this ( on systems that support a POSIX shell): echo "API_KEY" > ~/.sunlight.key where `API_KEY` is actually the string of letters and numbers that was emailed to you. Actually putting `API_KEY` into this file will most likely result in an error from the server. You can confirm they key with the following command: cat ~/.sunlight.key This should output the string that was emailed to you. Help me! ******** Basic usage and some brief examples can be found on `readthedocs `_. If this doens't help, feel free to email for help, ask over IRC in ``#sunlightlabs`` on ``irc.freenode.net``, or open a issue if it's a particularly nasty bug (particularly regarding ambiguous documentation, or poorly exposed API methods). License ******* All code in this project is licensed under a BSD-3 clause style license. The exact terms are in the `LICENSE` file, which will be distributed with any copy of the source you recieve. Contribute ********** Bugfixes, documentation contributions and more extensive (yet clear) example scripts are all welcome and encouraged. Please open a pull-request against python-sunlight, or email a format-patch to the email address listed in the setup.py script. Platform: any sunlight-1.1.5/sunlight.egg-info/top_level.txt0000664000175000017500000000001111773413355021007 0ustar tagtag00000000000000sunlight sunlight-1.1.5/sunlight.egg-info/dependency_links.txt0000664000175000017500000000000111773413355022333 0ustar tagtag00000000000000 sunlight-1.1.5/docs/0000775000175000017500000000000011773413356013667 5ustar tagtag00000000000000sunlight-1.1.5/docs/source/0000775000175000017500000000000011773413356015167 5ustar tagtag00000000000000sunlight-1.1.5/docs/source/index.rst0000664000175000017500000000465611754226063017037 0ustar tagtag00000000000000=============== python-sunlight =============== Overview ======== python-sunlight provides a unified set of API clients for the various `open government data APIs `_ made available by `Sunlight Foundation `_ projects. Currently this library supports the following APIs: * `Sunlight Congress API `_ (via :ref:`sunlight.congress`) * `Open States API `_ (via :ref:`sunlight.openstates`) * `Capitol Words API `_ (via :ref:`sunlight.capitolwords`) Support is pending for the `Influence Explorer API `_ and the `Real Time Congress API `_, though these currently have their own Python wrappers. Installation ============ The simplest way to install python-sunlight is via `pip `_:: $ pip install sunlight You may also wish to check the project out from `GitHub `_:: $ git clone git://github.com/sunlightlabs/python-sunlight.git Usage ===== `Register for a Sunlight API Key `_ if you haven't already, then you'll be ready to start using the library. The recommended method of providing the library with your API key is by placing your key in a file at :file:`~/.sunlight.key`. Alternatively you can use an environment variable named :envvar:`SUNLIGHT_API_KEY` or set :data:`sunlight.config.API_KEY` within your program. After setting your API key simply ``import sunlight`` and start using the APIs:: >>> import sunlight >>> nc_legs = sunlight.openstates.legislators(state='nc') You can also import a specific API client:: >>> from sunlight import congress >>> pelosi = congress.legislators(lastname='Pelosi')[0] For details on how to use the various APIs check out the documentation for the individual clients: .. toctree:: :maxdepth: 2 services/congress.rst services/openstates.rst services/capitolwords.rst Internals ========= Implementation details, for extending python-sunlight or more untraditional uses. .. toctree:: :maxdepth: 2 sunlight/service.rst sunlight/config.rst sunlight/errors.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` sunlight-1.1.5/docs/source/sunlight/0000775000175000017500000000000011773413356017024 5ustar tagtag00000000000000sunlight-1.1.5/docs/source/sunlight/errors.rst0000664000175000017500000000027711754226063021074 0ustar tagtag00000000000000sunlight.errors -- Exceptions and errors ======================================== Exception, Errors and Failures, Oh My! Exceptions ********** .. automodule:: sunlight.errors :members: sunlight-1.1.5/docs/source/sunlight/service.rst0000664000175000017500000000053611754226063021216 0ustar tagtag00000000000000sunlight.service -- API superclass ================================== This page is more aimed to API hackers, not so much API users. If you're a user, feel free to read up on how this works, but this might not be the easiest thing to develop an app around. Classes and Variables ********************* .. automodule:: sunlight.service :members: sunlight-1.1.5/docs/source/sunlight/config.rst0000664000175000017500000000045411754226063021022 0ustar tagtag00000000000000sunlight.config =============== This particular module is full of all sorts of fun tidbits that the API uses all over the place, such as file locations, strings that might change at some point and all that. Methods and Constants ********************* .. automodule:: sunlight.config :members: sunlight-1.1.5/docs/source/conf.py0000664000175000017500000001517711754226063016475 0ustar tagtag00000000000000# -*- coding: utf-8 -*- import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../')) # -- General configuration ----------------------------------------------------- import sunlight version = sunlight.__version__ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-sunlight' copyright = u'2012, Sunlight Labs' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = version # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'python-sunlightdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} sunlight-1.1.5/docs/source/services/0000775000175000017500000000000011773413356017012 5ustar tagtag00000000000000sunlight-1.1.5/docs/source/services/capitolwords.rst0000664000175000017500000000135311754226063022254 0ustar tagtag00000000000000.. _sunlight.capitolwords: ===================== sunlight.capitolwords ===================== For every day Congress is in session, `Capitol Words `_ visualizes the most frequently used words in the Congressional Record, giving you an at-a-glance view of which issues lawmakers address on a daily, weekly, monthly and yearly basis. Capitol Words lets you see what are the most popular words spoken by lawmakers on the House and Senate floor. .. automethod:: sunlight.services.capitolwords.capitolwords.dates .. automethod:: sunlight.services.capitolwords.capitolwords.phrases .. automethod:: sunlight.services.capitolwords.capitolwords.phrases_by_entity .. automethod:: sunlight.services.capitolwords.capitolwords.text sunlight-1.1.5/docs/source/services/openstates.rst0000664000175000017500000000655011754226063021733 0ustar tagtag00000000000000.. _sunlight.openstates: =================== sunlight.openstates =================== This is a thin wrapper around the `Open States `_ API, which provides data on state legislators, bills, votes, committees, districts, events, and more! Please consider contributing to the `Open States project `_, it's all open-source, and community involvement is valued very much by the Open States crew. .. note:: If you come across data quality issues, broken code, or missing data, please file a report on the `GitHub issues page `_. Thanks! Metadata ======== Methods for dealing with `Open States Metadata `_. .. automethod:: sunlight.services.openstates.openstates.all_metadata .. automethod:: sunlight.services.openstates.openstates.state_metadata Bills ===== Methods for dealing with `Open States Bills `_. .. automethod:: sunlight.services.openstates.openstates.bills .. automethod:: sunlight.services.openstates.openstates.bill_detail Legislators =========== Methods for dealing with `Open States Legislators `_. .. automethod:: sunlight.services.openstates.openstates.legislators .. automethod:: sunlight.services.openstates.openstates.legislator_detail .. automethod:: sunlight.services.openstates.openstates.legislator_geo_search Committees ========== Methods for dealing with `Open States Committees `_. .. automethod:: sunlight.services.openstates.openstates.committees .. automethod:: sunlight.services.openstates.openstates.committee_detail Districts ========= Methods for dealing with `Open States Districts `_. .. automethod:: sunlight.services.openstates.openstates.districts .. automethod:: sunlight.services.openstates.openstates.district_boundary Events ====== Methods for dealing with `Open States Events `_. .. automethod:: sunlight.services.openstates.openstates.events .. automethod:: sunlight.services.openstates.openstates.event_detail Examples ======== Bills:: from sunlight import openstates vt_agro_bills = openstates.bills( q='agriculture', state='vt', chamber='upper' ) for bill in vt_agro_bills: print bill['title'] Legislators:: from sunlight import openstates ca_dems = openstates.legislators( state='ca', party='Democratic', first_name='Bob', active='true' ) for dem in ca_dems: print "%s %s (%s)" % ( dem['first_name'], dem['last_name'], dem['chamber'] ) Committees:: from sunlight import openstates md_cttys = openstates.committees( state='md', chamber='upper' ) for ctty in md_cttys: print "%s (%s)" % ( ctty['committee'], ctty['chamber'] ) Events:: from sunlight import openstates tx_events = openstates.events( state='tx', type='committee:meeting' ) for event in tx_events: print "Event @ %s" % event['when'] for who in event['participants']: print " %s (%s)" % ( who['participant'], who['chamber'] ) sunlight-1.1.5/docs/source/services/congress.rst0000664000175000017500000000311611754226063021364 0ustar tagtag00000000000000.. _sunlight.congress: ================= sunlight.congress ================= The `Sunlight Labs Congress API `_ provides methods for obtaining basic information on Members of Congress, legislator IDs used by various websites, and geographical lookups between places and the politicians that represent them. The primary purpose of the API is to facilitate mashups involving politicians and the various other APIs that are out there. Legislators =========== This set of Congress API methods deal with federal legislators. For detailed documentaion on the return value of these methods see `legislator fields `_. .. automethod:: sunlight.services.congress.congress.legislators .. automethod:: sunlight.services.congress.congress.legislator_search .. automethod:: sunlight.services.congress.congress.legislators_for_zip .. automethod:: sunlight.services.congress.congress.legislators_for_lat_lon Districts ========= Pair of methods for retrieving districts. District dictionaries have a `'state'` and `'number'` key (ex. `{'state': 'NC', 'number': '3'}`) .. automethod:: sunlight.services.congress.congress.districts_for_zip .. automethod:: sunlight.services.congress.congress.districts_for_lat_lon Committees ========== Methods for dealing with committees. .. automethod:: sunlight.services.congress.congress.committees .. automethod:: sunlight.services.congress.congress.committee_detail .. automethod:: sunlight.services.congress.congress.committees_for_legislator sunlight-1.1.5/docs/Makefile0000664000175000017500000001102611754226063015323 0ustar tagtag00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-sunlight.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-sunlight.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/python-sunlight" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-sunlight" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." sunlight-1.1.5/ChangeLog0000664000175000017500000000642611773413307014515 0ustar tagtag000000000000002012-06-29 James Turk * sunlight/service.py: - Add new safe_encode function to use rather then urlencode * sunlight/services/*.py: - Migrate the sunlight.service.urlencode call to a .safe_encode call. * Bump release to 1.1.5 2012-06-29 Paul Tagliamonte * sunlight/services/openstates.py: - Encode all URL pararms before they get to urlencode, in the event a non-ascii name is passed as a kwarg. * Bump release to 1.1.4 2012-05-14 Paul Tagliamonte * sunlight/services/openstates.py: - Added a new method - "openstates.bill", to get single bills by bill ID - Fixed the exception that gets raised when running "openstates.bill(None)" from something cryptic to something a bit more explicit. * Bump release to 1.1.3 2012-04-12 Paul Tagliamonte * sunlight/services/capitolwords.py: Fixed a URL Encoding issue that was sitting there, undiscovered. Thanks, dandrinkard! * Bump release to 1.1.2 2012-02-27 James Turk [James] - Yet another fix for Python 3, remove an extra items() call in congress client - Bumping to 1.1.1 [Paul] - Modified all the examples to work on Python 3 2012-02-26 Paul Tagliamonte * MANIFEST.in: Including the docs in the sdist tarball. * Bump release to 1.0.6, then to 1.1.0 2012-02-21 Paul Tagliamonte * sunlight/service.py: Fixed the decode param to work with python2.6. This issue was discovered and reported by @eyeseast on GitHub. Sorry for the bumpy ride, everyone. * Bump release to 1.0.5 2012-02-17 Paul Tagliamonte * sunlight/service.py: Added a UTF hint to the .decode() call, it was resulting in a unicode error when translating UTF -> ASCII. This resulted in issue #170 in OpenStates. * Hotfix release, thanks ehazlett! * Bump release to 1.0.4 2012-02-17 Paul Tagliamonte * Import InvalidRequestException to the IE module, thanks pyflakes! * Bump release to 1.0.3 2012-02-11 James Turk * fix urllib imports for Python 3 compatibility * Bump release to 1.0.2 2012-02-08 James Turk * fix MANIFEST.in for PyPI and pip install directions * Bump release from 1.0 -> 1.0.1 2012-02-08 Paul Tagliamonte * Updating README.rst to reflect a "1.0" status. - Added "Contributing" block, and "License" block. * Bumping release to 1.0from 1.1~rc1. 2012-02-07 Paul Tagliamonte * Bumping release to 1.0~rc1 * Removed the set-key binary, it was not really ready for use. 2012-02-06 James Turk * refactor documentation to prepare for release * internal classes are now lowercase, ugly but it fixes sphinx * rename sunlight.common to sunlight.config * move sunlight.service.API_KEY to sunlight.config.API_KEY 2012-01-26 Paul Tagliamonte * Initial ChangeLog commit entry. Current working projects: - OpenStates - CapitolWords - Congress * Bumped the release 0.1~pre1 -> 0.5 * Brushed up the last bits to the docs. S'all good. * Changed to from setuptools from distutils. sunlight-1.1.5/setup.py0000775000175000017500000000125511754226063014453 0ustar tagtag00000000000000#!/usr/bin/env python # Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. from sunlight import __appname__, __version__ from setuptools import setup long_description = open('README.rst').read() setup( name = __appname__, version = __version__, packages = [ 'sunlight', 'sunlight.services' ], author = "Paul Tagliamonte", author_email = "paultag@sunlightfoundation.com", long_description = long_description, description = 'Unified Sunlight API bindings', license = "BSD", url = "https://github.com/sunlightlabs/python-sunlight", platforms = ['any'] ) sunlight-1.1.5/setup.cfg0000664000175000017500000000007311773413356014560 0ustar tagtag00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 sunlight-1.1.5/LICENSE0000664000175000017500000000302311754226063013736 0ustar tagtag00000000000000BSD-style license ================= Copyright (c) 2012, Sunlight Labs All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sunlight Labs nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sunlight-1.1.5/MANIFEST.in0000664000175000017500000000013711754226063014472 0ustar tagtag00000000000000include AUTHORS ChangeLog *.rst LICENSE recursive-include docs * recursive-include examples *