D complete
[BS_AY250.git] / week5 / d.py
blobd322cef4d02a42bbcc09700b82603991431288d8
1 '''
2 AY250 HW5 C
3 Build sqlite3 table of names and pictures
4 Author: Bryan Steinbach
5 '''
7 import os
8 import sqlite3
9 import webbrowser
11 import numpy as np
13 tablefn = 'poll'
15 conn = sqlite3.connect(tablefn)
18 # sanity check
19 #c.execute('select * from polls where state = "CA"')
21 def getpic(name):
22 ''' Fetch image URL from candidate's name '''
23 if name == '': return ''
24 c = conn.cursor()
25 c.execute(''' select url from pics where name = '%s' '''%name)
26 (url,) = c.next()
27 c.close()
29 return url
31 def retrieve_state(state):
32 ''' Fetch information about state and render to web page '''
33 c = conn.cursor()
34 c.execute('''select polls.state,polls.gop,polls.dem,polls.ind,polls.date1,polls.pollster,names.gop,names.dem,names.ind,names.incpar
35 from polls,names,pics where polls.state = '%s' and names.state = '%s' order by polls.date1 desc limit 1'''%(state,state))
37 state,gopfrac,demfrac,indfrac,date,pollster,gopname,demname,indname,incparname = c.next()
39 c.close()
41 goppic = getpic(gopname)
42 dempic = getpic(demname)
43 indpic = getpic(indname)
45 fracs = np.array([gopfrac,demfrac,indfrac])
46 partys = ['Republican','Democratic','Independent']
48 favi = np.argmax(fracs)
49 favp = partys[favi]
51 fn = state+'.html'
52 with open(fn,'w') as f:
53 print>>f,"<html>"
54 print>>f,"<body>"
55 print>>f,"<h1>State of "+state+" polling</h1>"
57 if gopname:
58 print>>f,"<h2>Republican candidate: ",gopname,"</h2>"
59 print>>f,"<img src='"+goppic+"'></img>"
60 print>>f,"<p>"
61 print>>f,"Polling: ",gopfrac
63 print>>f,"<p><p>"
65 if demname:
66 print>>f,"<h2>Democratic candidate: ",demname,"</h2>"
67 print>>f,"<img src='"+dempic+"'></img>"
68 print>>f,"<p>"
69 print>>f,"Polling: ",demfrac
71 print>>f,"<p><p>"
73 if indname:
74 print>>f,"<h2>Independent candidate: ",indname,"</h2>"
75 print>>f,"<img src='"+indpic+"'></img>"
76 print>>f,"<p>"
77 print>>f,"Polling: ",indfrac
79 print>>f,"<p><p>"
81 print>>f,"The incumbent party is "+incparname+"."
82 if favp != incparname:
83 print>>f,"We expect that to change to %s this election."%favp
84 else:
85 print>>f,"We don't expect that to change this election."
87 print>>f,"</body>"
88 print>>f,"</html>"
90 webbrowser.open(fn)
93 retrieve_state('CA')