22import datetime
33import os
44import time
5+ import datetime
6+ import tempfile
57
68import ckanapi
79import requests
@@ -104,18 +106,17 @@ def handle(self, *args, **options):
104106 resource_name = "{month} {year} Sensor Data Archive" .format (
105107 month = calendar .month_name [date .month ], year = date .year
106108 )
107-
108- filepath = "/tmp/%s.csv" % resource_name . lower (). replace ( " " , "_" )
109-
110- self . _write_file ( filepath = filepath , qs = qs )
109+ fp = tempfile . NamedTemporaryFile ( mode = "w+b" , suffix = ".csv" )
110+ self . _write_file ( fp , qs )
111+ filepath = fp . name
112+
111113 self ._create_or_update_resource (
112114 resource_name , filepath , resources , ckan , package
113115 )
114116
115- # Cleanup
116- if os .path .exists (filepath ):
117- os .remove (filepath )
118-
117+ # Cleanup temp file
118+ fp .close ()
119+
119120 # Don't DDOS openAFRICA
120121 time .sleep (5 )
121122
@@ -128,25 +129,24 @@ def handle(self, *args, **options):
128129 )
129130
130131 @staticmethod
131- def _write_file (filepath , qs ):
132- with open (filepath , "w" ) as fp :
133- fp .write (
134- "sensor_id;sensor_type;location;lat;lon;timestamp;value_type;value\n "
132+ def _write_file (fp , qs ):
133+ fp .write (
134+ b"sensor_id;sensor_type;location;lat;lon;timestamp;value_type;value\n "
135+ )
136+ for sd in qs .iterator ():
137+ s = ";" .join (
138+ [
139+ str (sd ["sensor__id" ]),
140+ sd ["sensor__sensor_type__name" ],
141+ str (sd ["location__id" ]),
142+ "{:.3f}" .format (sd ["location__latitude" ]),
143+ "{:.3f}" .format (sd ["location__longitude" ]),
144+ sd ["timestamp" ].isoformat (),
145+ sd ["sensordatavalues__value_type" ],
146+ sd ["sensordatavalues__value" ],
147+ ]
135148 )
136- for sd in qs .iterator ():
137- s = ";" .join (
138- [
139- str (sd ["sensor__id" ]),
140- sd ["sensor__sensor_type__name" ],
141- str (sd ["location__id" ]),
142- "{:.3f}" .format (sd ["location__latitude" ]),
143- "{:.3f}" .format (sd ["location__longitude" ]),
144- sd ["timestamp" ].isoformat (),
145- sd ["sensordatavalues__value_type" ],
146- sd ["sensordatavalues__value" ],
147- ]
148- )
149- fp .write (s + "\n " )
149+ fp .write (bytes (s + "\n " ,"utf-8" ))
150150
151151 @staticmethod
152152 def _create_or_update_resource (resource_name , filepath , resources , ckan , package ):
0 commit comments