problemy z pracą z generatorami python i klientem openstack swift
Mam problem z generatorami Pythona podczas pracy z biblioteką klienta Openstack Swift.
Problem polega na tym, że próbuję pobrać duży ciąg danych z określonego adresu URL (około 7 MB), rozdzielić łańcuch na mniejsze bity i wysłać klasę generatora z powrotem, przy czym każda iteracja zawiera fragment kawałka łańcucha. w zestawie testowym jest to tylko łańcuch wysyłany do klasy monkeypatched szybkiego klienta do przetwarzania.
Kod w klasie monkeypatched wygląda następująco:
def monkeypatch_class(name, bases, namespace):
'''Guido's monkeypatch metaclass.'''
assert len(bases) == 1, "Exactly one base class required"
base = bases[0]
for name, value in namespace.iteritems():
if name != "__metaclass__":
setattr(base, name, value)
return base
A w zestawie testów:
from swiftclient import client
import StringIO
import utils
class Connection(client.Connection):
__metaclass__ = monkeypatch_class
def get_object(self, path, obj, resp_chunk_size=None, ...):
contents = None
headers = {}
# retrieve content from path and store it in 'contents'
...
if resp_chunk_size is not None:
# stream the string into chunks
def _object_body():
stream = StringIO.StringIO(contents)
buf = stream.read(resp_chunk_size)
while buf:
yield buf
buf = stream.read(resp_chunk_size)
contents = _object_body()
return headers, contents
Po zwróceniu obiektu generatora został wywołany przez funkcję strumienia w klasie pamięci masowej:
class SwiftStorage(Storage):
def get_content(self, path, chunk_size=None):
path = self._init_path(path)
try:
_, obj = self._connection.get_object(
self._container,
path,
resp_chunk_size=chunk_size)
return obj
except Exception:
raise IOError("Could not get content: {}".format(path))
def stream_read(self, path):
try:
return self.get_content(path, chunk_size=self.buffer_size)
except Exception:
raise OSError(
"Could not read content from stream: {}".format(path))
I wreszcie w moim zestawie testów:
def test_stream(self):
filename = self.gen_random_string()
# test 7MB
content = self.gen_random_string(7 * 1024 * 1024)
self._storage.stream_write(filename, io)
io.close()
# test read / write
data = ''
for buf in self._storage.stream_read(filename):
data += buf
self.assertEqual(content,
data,
"stream read failed. output: {}".format(data))
Wynik kończy się tym:
======================================================================
FAIL: test_stream (test_swift_storage.TestSwiftStorage)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/bacongobbler/git/github.com/bacongobbler/docker-registry/test/test_local_storage.py", line 46, in test_stream
"stream read failed. output: {}".format(data))
AssertionError: stream read failed. output: <generator object _object_body at 0x2a6bd20>
Próbowałem to wyizolować za pomocą prostego skryptu Pythona, który ma taki sam przepływ, jak powyższy kod, który minął bez problemów:
def gen_num():
def _object_body():
for i in range(10000000):
yield i
return _object_body()
def get_num():
return gen_num()
def stream_read():
return get_num()
def main():
num = 0
for i in stream_read():
num += i
print num
if __name__ == '__main__':
main()
Każda pomoc w tym zakresie jest bardzo mile widziana :)