Guest User

Untitled

a guest
Nov 19th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. #!/usr/bin/python2.4
  2. #
  3. # Connect to PostgresDB table containing 'a full address';
  4. # Use geocoder library with Google API to update DB row with geocoder values
  5. #
  6. # Before running:
  7. # pip install psycopg2
  8. # pip install geocoder
  9.  
  10. import psycopg2
  11. import psycopg2.extras
  12. import geocoder
  13.  
  14. try:
  15. conn = psycopg2.connect("dbname='location_db' user='postgres' host='localhost' password='postgres'")
  16. except:
  17. print "I am unable to connect to the database"
  18.  
  19. cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  20.  
  21. try:
  22. cur.execute("""SELECT id, full_address from location_table order by id asc""")
  23. except:
  24. print "I can't SELECT from location_table"
  25.  
  26. rows = cur.fetchall()
  27. counter = 1
  28. for row in rows:
  29.  
  30. # # Geocoding an address
  31. g = geocoder.google(row['full_address'], components="country:US", long_name=True)
  32.  
  33. print row['id'], ":", g
  34.  
  35. updates = {
  36. 'g_street_name' : g.road_long,
  37. 'g_street_number' : g.street_number,
  38. 'g_city' : g.locality,
  39. 'g_zip' : g.postal,
  40. 'g_apt' : g.subpremise,
  41. 'g_neighborhood' : g.neighborhood,
  42. 'g_lat' : g.lat,
  43. 'g_lng' : g.lng
  44. }
  45. sql_template = "UPDATE location_table SET ({}) = %s WHERE id = {};"
  46. sql = sql_template.format(', '.join(updates.keys()), row['id'])
  47. params = (tuple(updates.values()),)
  48. cur.execute(sql, params)
  49. conn.commit()
Add Comment
Please, Sign In to add comment