Skip to main content
 首页 » 编程设计

python之将文件上传到 S3 存储桶之Python Django

2024年08月22日30itcoder

我想将一个字符串(这是一个 xml 响应)放入一个文件中,然后将其上传到一个 amazon s3 存储桶中。以下是我在 Python3 中的函数

def excess_data(user, resume): 
    res_data = BytesIO(bytes(resume, "UTF-8")) 
    file_name = 'name_of_file/{}_resume.xml'.format(user.id) 
    s3 = S3Storage(bucket="Name of bucket", endpoint='s3-us-west-2.amazonaws.com') 
    response = s3.save(file_name, res_data) 
    url = s3.url(file_name) 
    print(url) 
    print(response) 
    return get_bytes_from_url(url) 

但是,当我运行此脚本时,我不断收到错误 - AttributeError: Unable to determine the file's size. 知道如何解决这个问题吗?

提前致谢!

请您参考如下方法:

我正在使用 s3boto (需要 python-boto)在我的 Django 项目中连接 S3。

使用boto很容易做你想做的事:

>>> from boto.s3.key import Key 
>>> k = Key(bucket) 
>>> k.key = 'foobar' 
>>> k.set_contents_from_string('This is a test of S3') 

查看此 documentation存储数据部分。

希望对您的问题有所帮助。