Data models / API wrapper (elex.api)¶
elex.api¶
-
class
elex.api.
APElection
¶ Base class for most objects.
Includes handy methods for transformation of data and AP connections
-
serialize
()¶ Serialize the object. Should be implemented in all classes that inherit from
APElection
.Should return an OrderedDict.
-
set_candidates
()¶ Set candidates.
If this thing (race, reportingunit) has candidates, serialize them into objects.
-
set_polid
()¶ Set politication id.
If polid is zero, set to None.
-
set_reportingunitids
()¶ Set reporting unit ID.
Per Tracy / AP developers, if the level is “state”, the reportingunitid is always 1.
-
set_reportingunits
()¶ Set reporting units.
If this race has reportingunits, serialize them into objects.
-
set_state_fields_from_reportingunits
()¶ Set state fields.
-
-
class
elex.api.
BallotMeasure
(**kwargs)¶ Canonical representation of a ballot measure.
Ballot measures are similar to :class:`Candidate`s, but represent a position on a ballot such as “In favor of” or “Against” for ballot measures such as a referendum.
-
serialize
()¶ Implements
APElection.serialize()
.
-
set_id_field
()¶ Set id to <unique_id>.
-
set_unique_id
()¶ Generate and set unique id.
Candidate IDs are not globally unique. AP National Politian IDs (NPIDs or polid) are unique, but only national-level candidates have them; everyone else gets ‘0’. The unique key, then, is the NAME of the ID we’re using and then the ID itself. Verified this is globally unique with Tracy.
-
-
class
elex.api.
Candidate
(**kwargs)¶ Canonical representation of a candidate. Should be globally unique for this election, across races.
-
serialize
()¶ Implements
APElection.serialize()
.
-
set_id_field
()¶ Set id to <unique_id>.
-
set_unique_id
()¶ Generate and set unique id.
Candidate IDs are not globally unique. AP National Politian IDs (NPIDs or polid) are unique, but only national-level candidates have them; everyone else gets ‘0’. The unique key, then, is the NAME of the ID we’re using and then the ID itself. Verified this is globally unique with Tracy.
-
-
class
elex.api.
CandidateDelegateReport
(**kwargs)¶ ‘level’: ‘state’, ‘party_total’: 4762, ‘superdelegates_count’: 0, ‘last’: u’Steinberg’, ‘state’: u’SD’, ‘candidateid’: u‘11291’, ‘party_need’: 2382, ‘party’: u’Dem’, ‘delegates_count’: 0, ‘id’: u’SD-11291’, ‘d1’: -1, ‘d7’: 8, ‘d30’: 10
-
serialize
()¶ Implements
APElection.serialize()
.
-
-
class
elex.api.
CandidateReportingUnit
(**kwargs)¶ Canonical reporesentation of an AP candidate. Note: A candidate can be a person OR a ballot measure.
-
serialize
()¶ Implements
APElection.serialize()
.
-
set_id_field
()¶ Set id to <raceid>-<uniqueid>-<reportingunitid>.
-
set_unique_id
()¶ Generate and set unique id.
Candidate IDs are not globally unique. AP National Politian IDs (NPIDs or polid) are unique, but only national-level candidates have them; everyone else gets ‘0’. The unique key, then, is the NAME of the ID we’re using and then the ID itself. Verified this is globally unique with Tracy Lewis.
-
-
class
elex.api.
DelegateReport
(**kwargs)¶ Base class for a single load of AP delegate counts. d = DelegateReport() [z.__dict__ for z in d.candidates]
-
get_ap_file
(path, key)¶ Get raw data file.
-
get_ap_report
(key, params={})¶ Given a report number and a key for indexing, returns a list of delegate counts by party. Makes a request from the AP using requests. Formats that request with env vars.
-
get_report_id
(reports, key)¶ Takes a delSuper or delSum as the argument and returns organization-specific report ID.
-
load_raw_data
(delsuper_datafile, delsum_datafile)¶ Gets underlying data lists we need for parsing.
-
output_candidates
()¶ Transforms our multi-layered dict of candidates / states into a single list of candidates at each reporting level.
-
parse_sum
()¶ Parses the delsum JSON produced by the AP.
-
parse_super
()¶ Parses the delsuper JSON produced by the AP.
-
-
class
elex.api.
Election
(**kwargs)¶ Canonical representation of an election on a single date.
-
ballot_measures
¶ Return list of ballot measure objects with results.
-
candidate_reporting_units
¶ Return list of candidate reporting unit objects.
-
candidates
¶ Return list of candidate objects with results.
-
get
(path, **params)¶ Farms out request to api_request. Could possibly handle choosing which parser backend to use – API-only right now. Also the entry point for recording, which is set via environment variable.
Parameters: - path – API url path.
- **params –
A dict of optional parameters to be included in API request.
-
get_race_objects
(parsed_json)¶ Get parsed race objects.
Parameters: parsed_json – Dict of parsed AP election JSON.
-
get_raw_races
(**params)¶ Convenience method for fetching races by election date. Accepts an AP formatting date string, e.g., YYYY-MM-DD. Accepts any number of URL params as kwargs.
If datafile passed to constructor, the file will be used instead of making an HTTP request.
Parameters: **params – A dict of additional parameters to pass to API. Ignored if datafile was passed to the constructor.
-
get_uniques
(candidate_reporting_units)¶ Parses out unique candidates and ballot measures from a list of CandidateReportingUnit objects.
-
get_units
(race_objs)¶ Parses out races, reporting_units, and candidate_reporting_units in a single loop over the race objects.
Parameters: race_objs – A list of top-level Race objects.
-
races
¶ Return list of race objects.
-
reporting_units
¶ Return list of reporting unit objects.
-
results
¶ Return list of candidate reporting unit objects with results.
-
serialize
()¶ Implements
APElection.serialize()
.
-
set_id_field
()¶ Set id to <electiondate>.
-
-
class
elex.api.
Elections
¶ Holds a collection of election objects
-
get_elections
(datafile=None)¶ Get election data from API or cached file.
Parameters: datafile – If datafile is specified, use instead of making an API call.
-
get_next_election
(datafile=None, electiondate=None)¶ Get next election. By default, will be relative to the current date.
Parameters: - datafile – If datafile is specified, use instead of making an API call.
- electiondate – If electiondate is specified, gets the next election after the specified date.
-
-
class
elex.api.
Race
(**kwargs)¶ Canonical representation of a single race, which is a seat in a political geography within a certain election.
-
serialize
()¶ Implements
APElection.serialize()
.
-
set_id_field
()¶ Set id to <raceid>.
-
-
class
elex.api.
ReportingUnit
(**kwargs)¶ Canonical representation of a single level of reporting.
-
serialize
()¶ Implements
APElection.serialize()
.
-
set_candidate_votepct
()¶ Set vote percentage for each candidate.
-
set_id_field
()¶ Set id to <reportingunitid>.
-
set_level
()¶ New England states report at the township level. Every other state reports at the county level. So, change the level from ‘subunit’ to the actual level name, either ‘state’ or ‘township’.
-
set_votecount
()¶ Set vote count.
-
-
class
elex.api.
BaseTrendReport
(trend_file=None)¶ A base class for retrieving trend reports from the AP API.
-
get_ap_file
(path)¶ Get raw data file.
-
get_ap_report
(key, params={})¶ Given a report number and a key for indexing, returns a list of delegate counts by party. Makes a request from the AP using requests. Formats that request with env vars.
-
get_report_id
(reports, key)¶ Takes a delSuper or delSum as the argument and returns organization-specific report ID.
-
load_raw_data
(office_code, trend_file=None)¶ Gets underlying data lists we need for parsing.
-
output_parties
()¶ Parse the raw data on political parties returned by the API, converts them into objects and assigns them to the object’s
parties
attribute.
-
-
class
elex.api.
USGovernorTrendReport
(trend_file=None)¶ A trend report on U.S. governors.
-
class
elex.api.
USSenateTrendReport
(trend_file=None)¶ A trend report on the U.S. Senate.
-
class
elex.api.
USHouseTrendReport
(trend_file=None)¶ A trend report on U.S. House.
elex.api.utils¶
Utility functions to record raw election results and handle low-level HTTP interaction with the Associated Press Election API.
-
class
elex.api.utils.
UnicodeMixin
¶ Python 2 + 3 compatibility for __unicode__
-
elex.api.utils.
api_request
(path, **params)¶ Function wrapping Python-requests for making a request to the AP’s elections API.
A properly formatted request: * Modifies the BASE_URL with a path. * Contains an API_KEY. * Returns a response object.
Parameters: **params – Extra parameters to pass to requests. For example, apiKey=”<YOUR API KEY>, your AP API key, or national=True, for national-only results.
-
elex.api.utils.
get_reports
(params={})¶ Get data from reports endpoints.
-
elex.api.utils.
write_recording
(payload)¶ Record a timestamped version of an Associated Press Elections API data download.
Presumes JSON at the moment. Would have to refactor if using XML or FTP. FACTOR FOR USE; REFACTOR FOR REUSE.
Parameters: payload – JSON payload from Associated Press Elections API.