首页 文章

TypeError:需要类似字节的对象,而不是无服务器和Python3的'str'

提问于
浏览
0

我有一个aws-lambda函数,只要将CSV文件上传到s3存储桶就会触发该函数 . 我在Python 3.6中使用无服务器框架,问题是我收到此错误消息

需要一个类似字节的对象,而不是'str':TypeError Traceback(最近一次调用last):文件“/var/task/handler.py”,第33行,在csvfile中,fichier = obj ['Body'] . () . split('\ n')TypeError:需要类似字节的对象,而不是'str'

我在net 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')

这是我的serverless.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 回答

  • 3

    问题是

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

    返回 bytes 对象,而不是字符串 . 这是因为编码可能需要多个单个字符 . 现在您在 bytes 对象上使用 split ,但是您无法使用字符串拆分它,您需要使用另一个 bytes 对象进行拆分 . 特别

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

    应该修复你的错误,但取决于你期望的解码可能在拆分之前更合适吗?

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

相关问题