In-memory zip file uploads a 0 B object

时间:2017-10-12 10:21:01

标签: python python-2.7 boto3 zipfile

I am creating an in-memory zip file and uploading it to S3 as follows:

def upload_script(s3_key, file_name, script_code):
    """Upload the provided script code onto S3, and return the key of uploaded object"""
    bucket = boto3.resource('s3').Bucket(config.AWS_S3_BUCKET)
    zip_file = BytesIO()
    zip_buffer = ZipFile(zip_file, "w", ZIP_DEFLATED)
    zip_buffer.debug = 3
    zip_buffer.writestr("{}.py".format(file_name), script_code)
    for zfile in zip_buffer.filelist:
        zfile.create_system = 0
    zip_buffer.close()
    upload_key = "{}/{}_{}.zip".format(s3_key, file_name, TODAY())
    print zip_buffer.namelist(), upload_key
    bucket.upload_fileobj(zip_file, upload_key)
    return upload_key

The print and return values are as follows for a test run:

['s_o_me.py'] a/b/s_o_me_20171012.zip
a/b/s_o_me_20171012.zip

The test script is a simple python line:

print upload_script('a/b', 's_o_me', "import xyz")

The files are being created in the S3 bucket, but they are of 0 B size. Why is the buffer not being written/uploaded properly?

1 个答案:

答案 0 :(得分:1)

显然,在继续进行进一步操作之前,您必须在BytesIO对象中寻找第0个索引。

将代码段更改为:

zip_file.seek(0)
bucket.upload_fileobj(zip_file, upload_key)

完美无缺。