comparison flys-backend/contrib/shpimporter/importer.py @ 2853:bd9e76e0b55d

Improved the python shapefile importer. flys-backend/trunk@4313 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Ingo Weinzierl <ingo.weinzierl@intevation.de>
date Fri, 27 Apr 2012 06:39:12 +0000
parents
children b0132e1b9719
comparison
equal deleted inserted replaced
2852:875a87b8489f 2853:bd9e76e0b55d
1 import ogr
2
3 class Importer:
4
5 def __init__(self, dbconn, river_id):
6 self.dbconn = dbconn
7 self.river_id = river_id
8
9
10 def getKind(self, path):
11 raise NotImplementedError("Importer.getKind is abstract!")
12
13
14 def getPath(self, base):
15 raise NotImplementedError("Importer.getPath is abstract!")
16
17
18 def getTablename(self):
19 raise NotImplementedError("Importer.getTablename is abstract!")
20
21
22 def IsFieldSet(self, feat, name):
23 try:
24 isset = feat.GetField(name)
25 return isset is not None
26 except:
27 return False
28
29
30 def IsDoubleFieldSet(self, feat, name):
31 try:
32 isset = feat.GetFieldAsDouble(name)
33 return isset is not None
34 except:
35 return False
36
37
38 def isShapeRelevant(self, name, path):
39 return True
40
41
42 def walkOverShapes(self, shape):
43 (name, path) = shape
44 if not self.isShapeRelevant(name, path):
45 print "Skip shapefile '%s'" % name
46 return
47
48 shp = ogr.Open(shape[1])
49 if shp is None:
50 print "Shapefile '%s' could not be opened!" % path
51 return
52
53 print "Opened shapefile '%s'" % path
54 srcLayer = shp.GetLayerByName(name)
55
56 if srcLayer is None:
57 print "Layer '%s' was not found!" % name
58 return
59
60 return self.shape2Database(srcLayer, name, path)
61
62
63 def shape2Database(self, srcLayer, name, path):
64 table = ogr.Open(self.dbconn)
65 destLayer = table.GetLayerByName(self.getTablename())
66
67 if srcLayer is None:
68 print "Shapefile is None!"
69 return -1
70
71 if destLayer is None:
72 print "No destination layer given!"
73 return -1
74
75 count = srcLayer.GetFeatureCount()
76 print "Try to add %i features to database." % count
77
78 srcLayer.ResetReading()
79
80 geomType = -1
81 success = 0
82 unsupported = 0
83 featureDef = destLayer.GetLayerDefn()
84
85 for feat in srcLayer:
86 geom = feat.GetGeometryRef()
87 geomType = geom.GetGeometryType()
88
89 if self.isGeometryValid(geomType):
90 newFeat = self.createNewFeature(featureDef,
91 feat,
92 name=name,
93 path=path)
94
95 if newFeat is not None:
96 res = destLayer.CreateFeature(newFeat)
97 if res is None or res > 0:
98 print "Error while inserting feature: %r" % res
99 else:
100 success = success + 1
101 else:
102 unsupported = unsupported + 1
103
104 print "Inserted %i features" % success
105 print "Found %i unsupported features" % unsupported
106
107 try:
108 destLayer.CommitTransaction()
109 except e:
110 print "Exception while committing transaction."
111
112 return geomType
113

http://dive4elements.wald.intevation.org