Created
March 18, 2015 08:48
-
-
Save jamescw/1a15baf57528c8ab4ef9 to your computer and use it in GitHub Desktop.
Shape file export for django import export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from import_export.formats.base_formats import Format | |
from shapely.geometry import Point, mapping | |
from fiona import collection | |
class SHPFormat(Format): | |
def get_title(self): | |
return 'shp' | |
def export_data(self, dataset): | |
""" | |
Returns format representation for given dataset. | |
""" | |
attribs = { | |
'ID': 'str', | |
'Title': 'str', | |
} | |
schema = {'geometry': 'Point', 'properties': attribs} | |
#TODO: it would be much better to save the artifacts to an in memory buffer | |
with collection("sample.shp", "w", "ESRI Shapefile", schema) as output: | |
for thing in dataset.dict: | |
data = dict() | |
data['ID'] = thing.id | |
data['Title'] = thing.title | |
point = Point(thing.point.x, thing.point.y) | |
output.write({'properties': data, 'geometry': mapping(point)}) | |
in_memory = StringIO.StringIO() | |
zip = ZipFile(in_memory, "a") | |
for file in glob.glob("sample.*"): | |
zip.write(file) | |
# fix for Linux zip files read in Windows | |
for file in zip.filelist: | |
file.create_system = 0 | |
zip.close() | |
in_memory.seek(0) | |
return in_memory.read() | |
def get_extension(self): | |
""" | |
Returns extension for this format files. | |
""" | |
return "zip" | |
def can_export(self): | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment