PageRenderTime 53ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/layers/models.py

https://bitbucket.org/rukku/webandgis
Python | 76 lines | 75 code | 1 blank | 0 comment | 0 complexity | 4697186a72ff3c75b9cb31d5f556a949 MD5 | raw file
  1. from django.db import models
  2. from django.dispatch import receiver
  3. from django.conf import settings
  4. from django.contrib.gis.gdal import DataSource
  5. from django.template.defaultfilters import slugify
  6. import zipfile
  7. import os, errno
  8. import glob
  9. class Layer(models.Model):
  10. name = models.CharField(max_length=255)
  11. description = models.TextField(null=True, blank=True)
  12. slug = models.SlugField(editable=False)
  13. bbox = models.CharField(max_length=255, null=True, blank=True)
  14. original = models.FileField(upload_to='uploads', null=True, blank=True,
  15. help_text="""Zip file with either geotiff and
  16. projection or shapefiles and friends""")
  17. # type = models.CharField(max_length=255)
  18. style = models.TextField(null=True, blank=True)
  19. def __unicode__(self):
  20. return self.name
  21. def save(self, force_insert=False, force_update=False):
  22. self.slug = slugify(self.name)
  23. super(Layer, self).save(force_insert, force_update)
  24. def create_folder(path):
  25. try:
  26. os.makedirs(path)
  27. except OSError as exc: # Python >2.5
  28. if exc.errno == errno.EEXIST and os.path.isdir(path):
  29. pass
  30. else: raise
  31. @receiver(models.signals.pre_save, sender=Layer)
  32. def layer_handler(sender, instance, *args, **kwargs):
  33. """
  34. Post process the uploaded layer
  35. Get the bounding box information and save it with the model
  36. """
  37. instance.slug = slugify(instance.name)
  38. # Make a folder with the slug name
  39. # and create a 'raw' subdirectory to hold the files
  40. layer_folder = os.path.join(settings.MEDIA_ROOT, 'layers', instance.slug)
  41. create_folder(layer_folder)
  42. zip_out = os.path.join(layer_folder, 'raw')
  43. create_folder(zip_out)
  44. # Iterate over the files in the zip and create them in the raw folder.
  45. z = zipfile.ZipFile(instance.original)
  46. for name in z.namelist():
  47. outfile = open(os.path.join(zip_out, name), 'wb')
  48. outfile.write(z.read(name))
  49. outfile.close()
  50. # Check if it is vector or raster
  51. # if it has a .shp file, it is vector :)
  52. os.chdir(zip_out)
  53. shapefiles = glob.glob('*.shp')
  54. if len(shapefiles) > 0:
  55. # this means it is a vector
  56. # FIXME(This is a very weak way to get the shapefile)
  57. shapefile = shapefiles[0]
  58. # Use ogr to inspect the file and get the bounding box
  59. ds = DataSource(shapefile)
  60. layer = ds[0]
  61. extent = layer.extent.tuple
  62. instance.bbox = ",".join(["%s" % x for x in extent])
  63. # Render the tiles (if possible)