]> gitweb.michael.orlitzky.com - dead/census-tools.git/blob - src/Census.py
Added the Census module.
[dead/census-tools.git] / src / Census.py
1 import pgdb
2
3 import GPS
4
5
6 class Database:
7 """
8 This class wraps all of the operations that we'd like to perform
9 on the census database. Most of the utility scripts will just call
10 one or two methods from within this class.
11 """
12
13 def __init__(self, _host, _database, _username, _srid):
14 self.connection = pgdb.connect(host=_host,
15 database=_database,
16 user=_username)
17 self.srid = _srid
18
19
20 def __del__(self):
21 self.connection.close()
22
23
24 def find_average_population_density(self, coords):
25 """
26 Find the average population density at a set of GPS coordinates.
27 """
28 cursor = self.connection.cursor()
29
30 query = """
31 SELECT population_density
32 FROM (sf1_blocks INNER JOIN tiger
33 ON sf1_blocks.tiger_blkidfp00=tiger.blkidfp00)
34 WHERE ST_Contains(tiger.the_geom,
35 ST_SetSRID(ST_Point(%.6f, %.6f), %d));
36 """
37
38 sql_params = (coords.longitude, coords.latitude, self.srid)
39 cursor.execute(query, sql_params)
40 rows = cursor.fetchall()
41
42 if len(rows) > 0:
43 return rows[0][0]
44 else:
45 return None
46