Package madrona :: Package xyquery :: Package management :: Package commands :: Module loadraster
[hide private]

Source Code for Module madrona.xyquery.management.commands.loadraster

 1  import os 
 2  import sys 
 3  from osgeo import gdal 
 4  from subprocess import Popen 
 5  from django.core.management.base import BaseCommand, CommandError 
 6  from django.utils.datastructures import SortedDict 
 7  from django.contrib.gis.gdal import SpatialReference 
 8  from django.conf import settings 
 9  from madrona.xyquery.models import Raster, Layer 
10   
11  from optparse import make_option 
12   
13 -class Command(BaseCommand):
14 option_list = BaseCommand.option_list + ( 15 make_option('-n', '--name', dest='name', 16 help='Raster name.'), 17 make_option('-s', '--srs', dest='srs', 18 help='Spatial reference system of input raster'), 19 ) 20 help = 'Load a shapefile into the xyquery app.' 21 args = '[shapefile ...]' 22
23 - def parse_layer(self,rast, layername, srs):
24 ds = gdal.Open(rast) 25 if ds is None: 26 raise Exception("Dataset is not valid") 27 else: 28 rast = os.path.abspath(rast) 29 30 if srs: 31 srscmdpart = "-a_srs '%s'" % srs 32 else: 33 srscmdpart = '' 34 if ds.GetProjection() == '' or not ds.GetProjection(): 35 raise Exception("Looks like the raster doesn't have a projection defined - use --srs") 36 37 # Create a new layer 38 overwrite = True 39 if overwrite: 40 try: 41 old_lyr = Layer.objects.get(name=layername) 42 old_lyr.delete() 43 except: 44 pass 45 the_layer = Layer(name=layername) 46 the_layer.save() 47 48 # Make a vrt copy of the dataset 49 vrtpath = os.path.abspath(os.path.join(settings.MEDIA_ROOT,"xyquery_rasters",layername + ".vrt")) 50 command = "gdal_translate %s -of VRT '%s' '%s'" % (srscmdpart, rast, vrtpath) 51 output = Popen(command, shell=True).communicate()[0] 52 53 ds = gdal.Open(vrtpath) 54 if not ds or not os.path.exists(vrtpath): 55 raise Exception("%s does not exist .. somthing went screwy in the gdal_translate command \n\n %s" % (vrtpath, command)) 56 del ds 57 58 # Create a new raster model instance 59 the_raster = Raster(layer=the_layer, filepath=vrtpath) 60 the_raster.save()
61
62 - def handle(self, *rast, **options):
63 if len(rast) != 1: 64 return "Specify the path of a single raster dataset" 65 rast = rast[0] 66 67 if not os.path.exists(rast): 68 return "%s not found; Specify the path to an existing raster file" % rast 69 70 srs = options.get('srs',None) 71 layername = options.get('name',None) 72 if not layername: 73 layername = os.path.splitext(os.path.basename(rast))[0] 74 75 self.parse_layer(rast, layername, srs) 76 return "Raster layer %s has been loaded" % layername
77