【问题标题】:Text file content loss on Boto S3 uploadBoto S3 上传时文本文件内容丢失
【发布时间】:2015-08-04 22:59:25
【问题描述】:

我一直在将文本文件上传到 S3,我遇到了这个有趣的错误:文件并不总是上传,只是文件名。所以有时整个文件上传,有时我在 S3 上有一个 0 字节的文件。我一直在使用这个教程:

http://stackabuse.com/example-upload-a-file-to-aws-s3/

这是我一直在使用的代码(减号等):

#NOTE Section 8: Uploading to Amazon

AWS_ACCESS_KEY = ''
AWS_ACCESS_SECRET_KEY = ''

filea = open(date + '.txt', 'r+')

key = filea.name
bucket = ''





import os
import boto
from boto.s3.key import Key


##Beginning of function
def upload_to_s3(aws_access_key_id, aws_secret_access_key, filea, bucket, key, callback=None, md5=None, reduced_redundancy=False, content_type=None):
    """
    Uploads the given file to the AWS S3
    bucket and key specified.

    callback is a function of the form:

    def callback(complete, total)

    The callback should accept two integer parameters,
    the first representing the number of bytes that
    have been successfully transmitted to S3 and the
    second representing the size of the to be transmitted
    object.

    Returns boolean indicating success/failure of upload.
    """

    #   try:
     #      size = os.fstat(file.fileno()).st_size
    #   except:
            # Not all file objects implement fileno(),
            # so we fall back on this
     #      file.seek(0, os.SEEK_END)
      #     size = file.tell()

    conn = boto.connect_s3(aws_access_key_id, aws_secret_access_key)
    bucket = conn.get_bucket(bucket, validate=False)
    k = Key(bucket)
    k.key = key

    print k.key

    #if content_type:
     #  k.set_metadata('Content-Type', content_type)
    sent = k.set_contents_from_file(filea, cb=callback, md5=md5, reduced_redundancy=reduced_redundancy, rewind=True)

    print sent

        # Rewind for later use
    filea.seek(0)
    #print size

##End of function



upload_to_s3(AWS_ACCESS_KEY, AWS_ACCESS_SECRET_KEY, filea, bucket, key)
os.remove(date + '.txt')

现在关于我输入的内容的一些信息:代码的早期部分写出一个文本文件,有多行段落,但仍然是一个使用 a+ 权限创建的文本文件。该文件使用 (date + '.txt') 命名,并且不会在代码的早期部分中使用 .close() 关闭,除非 python 解释器执行了一些我不知道的子进程 (.close()给了我一些问题,所以我把它打开了,因为我的代码的最后一行在这里删除了它)。

我尝试循环上传过程,但文件似乎没有正确读取。我做错了什么?

【问题讨论】:

    标签: python amazon-s3 boto


    【解决方案1】:

    Boto 在开始上传之前不会将文件回退到 0。如果您传递给k.set_contents_from_file 的文件指针不在文件的开头,则不会发送从开头到文件到其当前位置的任何数据(由 fp.tell() 报告)。这是设计使然,我不会认为这是 boto 中的错误。

    如果要确保将整个文件上传到 S3,请确保文件指针位于文件开头,然后再将其传递给 boto。从上面显示的代码中,您在上传之后而不是之前进行倒带。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-01
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 2013-02-20
      • 2014-04-02
      • 2021-01-16
      相关资源
      最近更新 更多