Advertisement
Guest User

Untitled

a guest
Feb 16th, 2017
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import psycopg2
  2. from shapely.geometry import LineString
  3. from shapely import wkb
  4.  
  5. conn = psycopg2.connect('...')
  6. curs = conn.cursor()
  7.  
  8. # Make a Shapely geometry
  9. ls = LineString([(2.2, 4.4, 10.2), (3.3, 5.5, 8.4)])
  10. ls.wkt # LINESTRING Z (2.2 4.4 10.2, 3.3 5.5 8.4)
  11. ls.wkb_hex # 0102000080020000009A999999999901409A999999999911406666666666662440666666...
  12.  
  13. # Send it to PostGIS
  14. curs.execute('CREATE TEMP TABLE my_lines(geom geometry, name text)')
  15. curs.execute(
  16. 'INSERT INTO my_lines(geom, name)'
  17. 'VALUES (ST_SetSRID(%(geom)s::geometry, %(srid)s), %(name)s)',
  18. {'geom': ls.wkb_hex, 'srid': 4326, 'name': 'First Line'})
  19.  
  20. conn.commit() # save data
  21.  
  22. # Fetch the data from PostGIS, reading hex-encoded WKB into a Shapely geometry
  23. curs.execute('SELECT name, geom FROM my_lines')
  24. for name, geom_wkb in curs:
  25. geom = wkb.loads(geom_wkb, hex=True)
  26. print('{0}: {1}'.format(name, geom.wkt))
  27. # First Line: LINESTRING Z (2.2 4.4 10.2, 3.3 5.5 8.4)
  28.  
  29. >>> import psycopg2
  30. >>> conn = psycopg2.connect(dbname=..., port=..., user=...,
  31. password=..., host=...)
  32. >>> cur = conn.cursor()
  33. >>> x, y, z, = 32, 34, 0
  34. >>> cur.execute("SELECT ST_SetSRID(ST_MakePoint(%s, %s, %s),4326);", (x, y, z))
  35. >>> cur.fetchall()
  36. [('01010000A0E6100000000000000000404000000000000041400000000000000000',)]
  37.  
  38. >>> cur.execute("SELECT ST_AsText(ST_SetSRID(ST_MakePoint(%s, %s, %s),4326));", (x, y, z))
  39. >>> cur.fetchall()
  40. [('POINT Z (32 34 0)',)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement