Advertisement
Guest User

Untitled

a guest
Apr 4th, 2017
508
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.38 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. ###########################################################################
  4. """Usage: gdb_to_pg.py -D <path> -H <host> -u <user> -w <password> -d <dbname>
  5. Options:
  6. -h, --help эта справка по работе с программой
  7. -H, --host хост БД, в которую конвертируются данные
  8. -u, --user имя пользователя для подключения к БД
  9. -w, --password пароль пользользователя, под которым происходит подключение
  10. -d, --dbname имя БД, в которую юудет производится импорт данных
  11. -p, --port порт для подключения к БД
  12. -D, --dir корневая директория для поиска файлов
  13. """
  14. __author__ = 'vladimir.rybalko@gmail.com (Vladimir Rybalko)'
  15.  
  16. import os, sys, fnmatch, psycopg2, chardet
  17. from optparse import OptionParser
  18. try:
  19. from osgeo import ogr, osr, gdal
  20. except:
  21. sys.exit('ERROR: cannot find GDAL/OGR modules')
  22.  
  23. def ParseInputs():
  24. parser = OptionParser()
  25. parser.add_option('-H', '--host', dest='host', default='localhost', help='The host name PG to connect.')
  26. parser.add_option('-u', '--user', dest='userName', default='postgres', help='The user to connect the PG.')
  27. parser.add_option('-w', '--password', dest='password', default='', help="The user's password")
  28. parser.add_option('-p', '--port', dest='port', default='5432', help='The port to connect the PG')
  29. parser.add_option('-d', '--dbname', dest='databaseName', default='postgres', help='The database name to connect the PG')
  30. parser.add_option('-D','--dir', dest='dir', help='The root directory for find files')
  31. (options, args) = parser.parse_args()
  32. if args:
  33. parser.print_help()
  34. parser.exit(msg='\nUnexpected arguments: %s\n' % ' '.join(args))
  35.  
  36. invalid_args = False
  37. if options.host is None:
  38. print ('-H (host) is required')
  39. invalid_args = True
  40. if options.userName is None:
  41. print ('-u (userName) is required')
  42. invalid_args = True
  43. if options.password is None:
  44. print ('-w (password) is required')
  45. invalid_args = True
  46. if options.databaseName is None:
  47. print ('-d (dbname) is required')
  48. invalid_args = True
  49. if options.dir is None or os.path.isdir(options.dir) is False:
  50. print ('-D (dir) задан не задан или задан не правильно')
  51. invalid_args = True
  52. if invalid_args:
  53. sys.exit(4)
  54. return options
  55.  
  56. def connect(options):
  57. try:
  58. client = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s'" % (options.databaseName, options.userName, options.host, options.password))
  59. except:
  60. #print ("I am unable to connect to the database")
  61. sys.exit('I am unable to connect to the database')
  62. return client
  63.  
  64. def main():
  65. options = ParseInputs()
  66. conn = connect(options)
  67. # print conn
  68. cursor = conn.cursor()
  69. try:
  70. cursor.execute("SELECT COUNT(f_geometry_column) FROM public.geometry_columns")
  71. except psycopg2.Error, e:
  72. sys.exit('The database have not PostGIS extension')
  73.  
  74. cursor.execute("BEGIN TRANSACTION")
  75. cursor.execute("CREATE TABLE IF NOT EXISTS import_gdb (id SERIAL NOT NULL PRIMARY KEY, path text, geometry geometry)")
  76. cursor.execute("END TRANSACTION")
  77. cursor.execute("CREATE INDEX import_gdb_rtee ON import_gdb USING gist (geometry)")
  78. for path, subdirs, files in os.walk(options.dir):
  79. for name in files:
  80. file = os.path.join(path, name)
  81. if file.lower().endswith(('.gdb')):
  82. driver = ogr.GetDriverByName("FileGDB")
  83.  
  84. dataSource = driver.Open(file, 0)
  85. multipolygon = ogr.Geometry(ogr.wkbMultiPolygon)
  86.  
  87. for l in range( dataSource.GetLayerCount() ):
  88. layer = dataSource.GetLayer(l)
  89. layerDefinition = layer.GetLayerDefn()
  90. layerName = layer.GetName()
  91. feat = layer.GetNextFeature()
  92. geom = feat.GetGeometryRef()
  93. if geom.GetGeometryName() == 'POLYGON' or geom.GetGeometryName() == 'MULTIPOLYGON':
  94. for feature in layer:
  95. multipolygon.AddGeometry(feature.GetGeometryRef())
  96. cursor.execute("".join(["INSERT INTO import_gdb(path, geometry) VALUES ('", file, "',ST_GeomFromText('", multipolygon.ExportToWkt(),"'))"]))
  97.  
  98. cursor.close()
  99. if conn:
  100. conn.close()
  101.  
  102. return 0
  103. if __name__ == '__main__':
  104. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement