|
#!/usr/bin/env python |
|
import cgi |
|
import web |
|
from xml.etree.ElementTree import parse |
|
|
|
cgi.maxlen = 1048576 * 1 # no files more than 1 MB |
|
|
|
urls = ( |
|
r'/', 'upload', |
|
) |
|
app = web.application(urls, globals()) |
|
app.internalerror = web.debugerror |
|
application = app.wsgifunc() |
|
|
|
class upload: |
|
def GET(self): |
|
return """<!DOCTYPE html> |
|
<html> |
|
<head> |
|
<title>Census bookmark generator</title> |
|
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" /> |
|
</head> |
|
<body> |
|
<form method="POST" enctype="multipart/form-data" action=""> |
|
<label for="aff">AFF (query) file:</label> |
|
<input type="file" name="aff" /> |
|
<br /><br /> |
|
<input type="submit" value="Go" /> |
|
</form> |
|
</body> |
|
</html>""" |
|
|
|
def POST(self): |
|
try: |
|
data = web.input(aff={}) |
|
except ValueError: |
|
return "File too large" |
|
|
|
new_url_base = 'http://factfinder2.census.gov/bkmk/table/1.0/en' |
|
document = parse(data['aff'].file) |
|
|
|
product = document.find('product') |
|
url = '/'.join([ |
|
new_url_base, |
|
product.attrib['program-id'], |
|
product.attrib['dataset-id'], |
|
product.attrib['table-id'] |
|
]) |
|
|
|
geo_ids = [] |
|
code_types = {} |
|
selection = document.find('selection') |
|
if selection is not None and len(selection): |
|
for dimension in selection.findall('dimension'): |
|
dimension_type = dimension.attrib['type'] |
|
if dimension_type == 'geo': |
|
for cat_id in dimension.findall('cat-id'): |
|
geo_ids.append(cat_id.text) |
|
else: |
|
codes = [] |
|
if dimension_type in code_types: |
|
codes = code_types[dimension_type] |
|
for cat_id in dimension.findall('cat-id'): |
|
codes.append(cat_id.text) |
|
code_types[dimension_type] = codes |
|
if geo_ids: |
|
url = '%s/%s' % (url, '|'.join(geo_ids)) |
|
|
|
if code_types: |
|
for code_type in code_types.keys(): |
|
url = '%s/%s~%s' % (url, code_type, '|'.join(code_types[code_type])) |
|
|
|
return """<!DOCTYPE html> |
|
<html> |
|
<head> |
|
<title>Census bookmark generator</title> |
|
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1" /> |
|
</head> |
|
<body> |
|
<p>Here's your link: <a href="%(url)s">%(url)s</a></p> |
|
<p><a href="/">Again?</a></p> |
|
</body> |
|
</html>""" % {'url': url} |
|
|
|
if __name__ == "__main__": |
|
app.run() |
|
|