2
2
import datetime
3
3
import os
4
4
import time
5
+ import datetime
6
+ import tempfile
5
7
6
8
import ckanapi
7
9
import requests
@@ -104,18 +106,17 @@ def handle(self, *args, **options):
104
106
resource_name = "{month} {year} Sensor Data Archive" .format (
105
107
month = calendar .month_name [date .month ], year = date .year
106
108
)
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
+
111
113
self ._create_or_update_resource (
112
114
resource_name , filepath , resources , ckan , package
113
115
)
114
116
115
- # Cleanup
116
- if os .path .exists (filepath ):
117
- os .remove (filepath )
118
-
117
+ # Cleanup temp file
118
+ fp .close ()
119
+
119
120
# Don't DDOS openAFRICA
120
121
time .sleep (5 )
121
122
@@ -128,25 +129,24 @@ def handle(self, *args, **options):
128
129
)
129
130
130
131
@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
+ ]
135
148
)
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" ))
150
150
151
151
@staticmethod
152
152
def _create_or_update_resource (resource_name , filepath , resources , ckan , package ):
0 commit comments