我正在使用Python avro 库。我想通过http发送一个avro文件,但我并不特别想先将该文件保存到磁盘,所以我想我会使用StringIO来存放文件内容,直到我准备好发送。但是 avro.datafile.DataFileWriter 周到地为我关闭了文件句柄,这让我很难从 StringIO 中取回数据。这就是我在代码中的意思:
from StringIO import StringIO
from avro.datafile import DataFileWriter
from avro import schema, io
from testdata import BEARER, PUBLISHURL, SERVER, TESTDATA
from httplib2 import Http
HTTP = Http()
##
# Write the message data to a StringIO
#
# @return StringIO
#
def write_data():
message = TESTDATA
schema = getSchema()
datum_writer = io.DatumWriter(schema)
data = StringIO()
with DataFileWriter(data, datum_writer, writers_schema=schema, codec='deflate') as datafile_writer:
datafile_writer.append(message)
# If I return data inside the with block, the DFW buffer isn't flushed
# and I may get an incomplete file
return data
##
# Make the POST and dump its response
#
def main():
headers = {
"Content-Type": "avro/binary",
"Authorization": "Bearer %s" % BEARER,
"X-XC-SCHEMA-VERSION": "1.0.0",
}
body = write_data().getvalue() # AttributeError: StringIO instance has no attribute 'buf'
# the StringIO instance returned by write_data() is already closed. :(
resp, content = HTTP.request(
uri=PUBLISHURL,
method='POST',
body=body,
headers=headers,
)
print resp, content
我确实有一些我可以使用的解决方法,但它们都不是非常优雅。关闭后有什么方法可以从 StringIO 获取数据?