TypeError: a bytes-like object is required, not 'str' with serverless and Python3

18 浏览
0 Comments

TypeError: a bytes-like object is required, not 'str' with serverless and Python3

我有一个 AWS Lambda 函数,每当 CSV 文件上传到 S3 存储桶时就会触发该函数。我正在使用 Python 3.6 的 Serverless 框架,问题在于我遇到了这个错误信息:

a bytes-like object is required, not \'str\': TypeError

Traceback (most recent call last):

File \"/var/task/handler.py\", line 33, in csvfile

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

TypeError: a bytes-like object is required, not \'str\'

我在网络上进行了一些研究 (这里),问题在于我没有使用 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('
')
    #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

admin 更改状态以发布 2023年5月22日
0
0 Comments

问题在于

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

返回的是一个 bytes 对象,而不是字符串。这是因为编码可能需要多个字符。现在,你正在对一个 bytes 对象使用 split 方法,但是你不能使用字符串对其进行拆分,需要使用另一个 bytes 对象进行拆分。具体来说,

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

应该解决你的错误,但根据你的期望,也许在拆分之前进行解码更为适合?

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

0