python - Boto3 没有将 zip 文件上传到 S3 python

标签 python amazon-s3 boto3

我正在尝试使用 boto3 for python 将 .zip 文件上传到 S3,但我目录中的 .zip 文件未正确上传。 该代码下载给定用户的所有电子邮件,将它们压缩到同一目录中并将它们上传到 S3 存储桶。 问题是上传的文件不是我打算上传的文件。而是只出现一个 18kb 的文件。

代码如下:

import sys
import imaplib
import getpass
import email
import shutil
import boto3
import os

username = input("Enter user's first name: ")
surname = input("Enter user's surname: ")
email_address = username + "." + surname + "@gmail.com"
password = getpass.getpass()
directory = username + surname + '/'
def download_emails(server):
    result, data = server.uid('search', None, "ALL")    #search all email and return their uids
    if result == 'OK':
        for num in data[0].split():
            result, data = server.uid('fetch', num, '(RFC822)')    #RFC is a standard for the format of ARPA Internet text messages
            if result == 'OK':
                email_message = email.message_from_bytes(data[0][1])    #raw email text including headers
                file_name = email_message['Subject']       #use dates and file names(can be changed)
                if not os.path.exists(directory):
                    os.makedirs(directory)      #create a dir for user's emails
                try:
                    email_file = open(directory + file_name+'.eml', 'wb')   #open a file for each email and insert the data.
                    email_file.write(data[0][1])
                    email_file.close()
                except:
                    pass

#function to zip all the emails
def archive(zipname, directory):
    return shutil.make_archive(zipname, 'zip', root_dir=directory, base_dir=None)

#function to upload zipped emails to AWS bucket
def upload_to_s3(file_name):
    s3 = boto3.resource('s3',
                aws_access_key_id=accessKey,
                aws_secret_access_key=secretKey,
                aws_session_token=secretToken,
                )

    s3.Bucket('user-backups').put_object(Key=username.title() + " " +
                                surname.title() + "/" + file_name, Body=file_name)
    print("Uploaded")


def main():
    server = imaplib.IMAP4_SSL("imap.gmail.com", 993)   #connect to gmail's imap server
    server.login(email_address, password)   #enter creds
    result, data = server.select('"[Gmail]/All Mail"')  #get all emails(inbox, outbox etc)
    if result == 'OK':
        print("Downloading")
        download_emails(server)
        server.close()
    else:
        print("ERROR: Unable to open mailbox ", result)
    server.logout()
    archive(username + surname, directory)
    upload_to_s3(username + surname + ".zip")
    #os.remove(email_address + ".zip")
    #shutil.rmtree(email_address)
    print("Done")
if __name__ == "__main__":
    main()

最佳答案

你可以看看这个 article了解更多信息。

有多种上传方式。看看这个 boto3 document我有下面列出的方法:

The managed upload methods are exposed in both the client and resource interfaces of boto3:

S3.Client method to upload a file by name: S3.Client.upload_file()
S3.Client method to upload a readable file-like object: S3.Client.upload_fileobj()
S3.Bucket method to upload a file by name: S3.Bucket.upload_file()
S3.Bucket method to upload a readable file-like object: S3.Bucket.upload_fileobj()
S3.Object method to upload a file by name: S3.Object.upload_file()
S3.Object method to upload a readable file-like object: S3.Object.upload_fileobj()

我使用 s3.client.upload_file 让它工作.

upload_file(Filename, Bucket, Key, ExtraArgs=None, Callback=None, Config=None) .
Upload a file to an S3 object.

import boto3
s3Resource = boto3.resource('s3')

try: 
    s3Resource.meta.client.upload_file('/path/to/file', 'bucketName', 'keyName')
except Exception as err:
    print(err)

关于python - Boto3 没有将 zip 文件上传到 S3 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49552507/

相关文章:

python - 如何通过整个 MainWIndow 将 CSS 样式应用到 QMenu

python - pywinauto 使远程桌面保持事件状态

android - HttpURLConnection SSL 握手因 AWS 签名 URL 重定向而中止

python - 我们如何使用 Boto3 列出 aws 参数存储中的所有参数? boto3文档中没有ssm.list_parameters?

python - 如何覆盖夹层评论表单?

同一类中的 Python 函数指针

amazon-web-services - 将相同的生命周期规则应用于多个存储桶

mysql - 在 S3 中临时保存大查询结果(~100k 行)的最佳方法是什么?

python - dynamodb boto3 中的 update_item 示例

javascript - 通过 Python Boto3 为 cognito 用户启用 SOFTWARE_TOKEN_MFA