1 import os
2 from django.core.management.base import BaseCommand, CommandError
3 from django.utils.datastructures import SortedDict
4 from django.contrib.gis.gdal.datasource import DataSource
5 from django.contrib.gis.gdal import SpatialReference
6 from django.db import transaction
7 from madrona.xyquery.models import Feature, Layer, Attribute
8
9 from optparse import make_option
12 option_list = BaseCommand.option_list + (
13 make_option('-n', '--name', dest='name',
14 help='Layer name.'),
15 make_option('-f', '--field', dest='fields',action='append', default=[],
16 help='Field name to include in attribute table (use multiple -f to include multiple fields).'),
17 )
18 help = 'Load a shapefile into the xyquery app.'
19 args = '[shapefile ...]'
20
21 @transaction.commit_on_success
22 - def parse_layer(self,shapefile, layername, fields_of_interest):
23 ds = DataSource(shapefile)
24 lyr = ds[0]
25 num_feat = lyr.num_feat
26
27 overwrite = True
28 if overwrite:
29 try:
30 old_lyr = Layer.objects.get(name=layername)
31 old_lyr.delete()
32 except:
33 pass
34 try:
35 the_layer = Layer(name=layername)
36 the_layer.save()
37 except:
38 raise Exception('Unable to create layer named %s' % layername)
39
40 wgs84 = SpatialReference(4326)
41 pctdone = 0
42 for feat in lyr:
43 try:
44 the_geometry = feat.geom.transform(wgs84,clone=True)
45 the_feature = Feature(layer=the_layer, geom=the_geometry.wkt)
46 the_feature.save()
47 except:
48 raise Exception('Unable to create feature')
49
50 try:
51 for fld in lyr.fields:
52 if fld in fields_of_interest or len(fields_of_interest) == 0:
53 the_attribute = Attribute(key=fld, value=str(feat[fld]), feature=the_feature)
54 the_attribute.save()
55 except:
56 raise Exception('Unable to create attribute')
57
58 oldpctdone = pctdone
59 pctdone = int((feat.fid * 100.) / float(num_feat))
60 if pctdone > oldpctdone:
61 print "Completed %d percent of %d features" % (pctdone, num_feat)
62
63 - def handle(self, *shapefile, **options):
64 if len(shapefile) != 1:
65 return "Specify the path of a single .shp file"
66 shapefile = shapefile[0]
67
68 if not os.path.exists(shapefile):
69 return "%s not found; Specify the path to an existing .shp file" % shapefile
70
71 layername = options.get('name',None)
72 if not layername:
73 layername = os.path.splitext(os.path.basename(shapefile))[0]
74 fields_of_interest = options.get('fields',[])
75
76 self.parse_layer(shapefile, layername, fields_of_interest)
77 return "Layer %s has been created" % layername
78