【问题标题】:When creating a class I get TypeError: missing 1 required position argument创建类时,我得到 TypeError: missing 1 required position argument
【发布时间】:2021-09-24 19:04:12
【问题描述】:

我正在尝试将 csv 文件上传到 s3。当我尝试围绕方法创建一个类时,我得到一个Type Error: upload_file_to_s3bucket() missing 1 required positional argument: 'file_path'。它可以在没有类的情况下成功运行。

class S3Upload():

    def __init__(self, filename=TEST_FILE, filetype='.csv'):
        self.filename = filename
        self.type = filetype

    def make_bucket(self, name, acl):
        session = aws_session()
        s3_resource = session.resource('s3')
        return s3_resource.create_bucket(Bucket=name, ACL=acl)

    def upload_file_to_s3bucket(self, bucket_name, file_path):
        session = aws_session()
        s3_resource = session.resource('s3')
        file_dir, file_name = os.path.split(file_path)

        bucket = s3_resource.Bucket(bucket_name)
        bucket.upload_file(
        Filename=file_path,
        Key=file_name,
        ExtraArgs={'ACL': 'public-read'}
        )

        s3_url = f"https://{bucket_name}.s3.amazonaws.com/{file_name}"
        return s3_url

    s3_url = upload_file_to_s3bucket('mitch-demo', TEST_FILE)
    print(s3_url) # https://mitch-demo.s3.amazonaws.com/simple.csv

if __name__ == '__main__':
    S3 = S3Upload(TEST_FILE)
    S3.make_bucket()
    S3.upload_file_to_s3bucket()

【问题讨论】:

  • 你为什么在类定义中调用upload_file_to_s3bucket in?您将其作为普通函数调用,但它仍需要 3 个参数:S3Upload 的实例、存储桶名称和文件名。
  • 你到底为什么在课堂上做s3_url = upload_file_to_s3bucket('mitch-demo', TEST_FILE)?你期望做什么?

标签: python csv amazon-s3


【解决方案1】:

在这一行

    s3_url = upload_file_to_s3bucket('mitch-demo', TEST_FILE)

您传入两个参数作为方法中定义的存储桶名称和文件路径

def upload_file_to_s3bucket(self, bucket_name, file_path):

但是在您以后的代码中,您没有这样做,这就是它出错的原因。它实际上发生了两次......您需要传入我放置 cmets 的值:

S3.make_bucket(#you need to add a name and acl arguments)
S3.upload_file_to_s3bucket(# you need to add bucket name and file path arguments)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2016-05-09
    • 2023-03-28
    相关资源
    最近更新 更多