-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwsgi_utils.py
50 lines (44 loc) · 1.62 KB
/
wsgi_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import os
class PipeWrapper(object):
""" Like Flask's FileWrapper, but designed for processes opened with
Popen(). While FileWrapper *almost* works with pipes, it doesn't
terminate the underlying process once the pipe is closed. This does.
"""
def __init__(self, pipe, buffer_size=8192, copy_to_filename=None):
self.pipe = pipe
self.buffer_size = buffer_size
self.copy_to_filename = copy_to_filename
if copy_to_filename:
self.partial_filename = copy_to_filename + '.part'
self.copy_to_file = open(self.partial_filename, 'wb')
else:
self.copy_to_file = None
def close(self):
if self.copy_to_file:
self.copy_to_file.close()
# TODO: cleanup the incomplete file
self.pipe.stdout.close()
self.pipe.terminate()
self.pipe.wait()
def __iter__(self):
return self
def __next__(self):
data = self.pipe.stdout.read(self.buffer_size)
if data:
if self.copy_to_filename:
self.copy_to_file.write(data)
return data
if self.copy_to_filename:
self.copy_to_file.close()
# Now that it's done, remove the ".part" from the end of the
# filename.
try:
os.rename(self.partial_filename, self.copy_to_filename)
except OSError:
print((
"WARNING: Couldn't rename to {}".format(
self.copy_to_filename
)
))
self.copy_to_file = None
raise StopIteration()