代码之家  ›  专栏  ›  技术社区  ›  ner

TypeError:需要类似字节的对象,而不是serverless和Python3的“str”

  •  0
  • ner  · 技术社区  · 8 年前

    我有一个aws lambda函数,每当CSV文件上传到s3 bucket时就会触发。我在Python 3.6中使用无服务器框架,问题是我收到了这个错误消息

    需要类似字节的对象,而不是“str”:TypeError

    回溯(最近一次呼叫最后一次):

    csvfile中第33行的文件“/var/task/handler.py”

    fichier=obj['Body']。读取()。拆分(“\n”)

    TypeError:需要类似字节的对象,而不是“str”

    我在网上做了一些研究 here 问题是,我没有使用open方法,因为文件是由s3事件读取的,所以不知道如何修复它

    这是我的代码:

    import logging
    import boto3
    from nvd3 import pieChart
    import sys
    import csv
    
    
    xdata = []
    ydata = []
    xdata1 = []
    ydata1 = []
    
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    def csvfile(event, context):
    
        s3 = boto3.client('s3')    
        # retrieve bucket name and file_key from the S3 event
        bucket_name = event['Records'][0]['s3']['bucket']['name']
        file_key = event['Records'][0]['s3']['object']['key']
        logger.info('Reading {} from {}'.format(file_key, bucket_name))
        # get the object
        obj = s3.get_object(Bucket=bucket_name, Key=file_key)
        # get lines inside the csv
        fichier = obj['Body'].read().split('\n')
        #print lines
         for ligne in fichier:
            if len(ligne) > 1:
                logger.info(ligne.decode())
                liste = ligne.split(',')
                print(liste)
                if liste[2] == 'ByCateg':
                    xdata.append(liste[4]) 
                    ydata.append(liste[1]) 
                elif liste[2] == 'ByTypes':
                    xdata1.append(liste[4]) 
                    ydata1.append(liste[1]) 
    
             print ' '.join(xdata) 
    
    print('Function execution Completed')
    

    这是我的无服务器。yml代码:

    service: aws-python # NOTE: update this with your service name
    
    provider:
      name: aws
      runtime: python3.6
      stage: dev
      region: us-east-1
      iamRoleStatements:
            - Effect: "Allow"
              Action:
                  - s3:*
                  - "ses:SendEmail"
                  - "ses:SendRawEmail"
                  - "s3:PutBucketNotification"
              Resource: "*"
    
        functions:
      csvfile:
        handler: handler.csvfile
        description: send mail whenever a csv file is uploaded on S3 
        events:
          - s3:
              bucket: car2
              event: s3:ObjectCreated:*
              rules:
                - suffix: .csv
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   kabanus    8 年前

    问题是

    fichier = obj['Body'].read()
    

    返回a bytes 对象,而不是字符串。这是因为编码可能需要多个字符。现在你正在使用 split 字节数 对象,但不能使用字符串拆分,需要使用另一个字符串拆分 字节数 对象明确地

    fichier = obj['Body'].read().split(b'\n')
    

    应该修复错误,但根据您的期望,在分割之前解码可能更合适?

    fichier = obj['Body'].read().decode("utf-8").split('\n')