#!/usr/bin/python # # Copyright (c) 2007-2008 by Fred Morris Consult, Seattle WA USA # # Author: Fred Morris # Date: 16-Feb-2008 # # Licensed under the Perl Artistic License: "under the same terms # as Perl itself". """Data Example (Part Two) Usage: Called as a CGI Script Returns some Javascript (JSON). Parameters: None Version: 1.1 Modification History: FWM 19-Feb-2008 prepare(); Fix an indent which caused candidate_data to be uselessly calculated each time a field was added. Refactor using Tagged. """ import sys from snakestation.handlers import TemplatedHTMLFinder from potusclient import PrecinctResults from snakestation.utils import Tagged class Handler (TemplatedHTMLFinder): """The business end of the stick. This one has no template, the entirety of the response is programmatically generated. """ TEMPLATE_NAME = None CANDIDATE_FIELDS = ('candidatename','votes') def __init__(self,**args): TemplatedHTMLFinder.__init__(self,**args) self.response.headers['Content-Type'] = 'text/javascript' self.precinct = '' self.county = '' self.function = '' self.params_ok = False return def analyze(self): request = self.request self.precinct = request.getfirst('precinct',None) if self.precinct is None: self.error = 'precinct was not supplied' return self.county = request.getfirst('county',None) if self.county is None: self.error = 'county was not supplied' return self.function = request.getfirst('function',None) if self.function is None: self.error = 'function was not supplied' return self.params_ok = True return def prepare(self): results = [] json_dict = [] if self.params_ok: # There is no template fetched, and this is the only remote response. # We could have fired this off in post_template(), but we wouldn't # gain anything in this particular case. results = self.request_response( PrecinctResults(self.template_map['Precincts']), 'Precinct Lookup error:', results, self.precinct, self.county ) try: for k in ('counted','registered'): json_dict += ['"%s":%s' % (k,results[0][k])] candidates = Tagged(results[0]['candidates']) candidate_list = [] for candidate in candidates.record_dict_list( 'candidate', self.CANDIDATE_FIELDS ): candidate_fields = [] for field in self.CANDIDATE_FIELDS: value = candidate[field] if field == 'candidatename': field = 'name' candidate_fields += ['"%s":"%s"' % (field,value) ] candidate_data = '{' + ','.join(candidate_fields) + '}' candidate_list += [ candidate_data ] json_dict += [ '"candidates":[' + ','.join(candidate_list) + ']' ] except (KeyError,IndexError): self.error = 'incomplete data' for key in ('error',): json_dict += [ '"%s":"%s"' % ( key, getattr(self,key,'') ) ] if self.function is None: self.function = 'None' self.response.body = self.function + '({' + ','.join(json_dict) + '});' return def main(): handler = Handler() handler.template_map = { 'Precincts' : 'http://devil.m3047.inwa.net/elections/perl/election-product.cgi' } handler.main() if __name__ == '__main__': main()