在python中解析POST文件

问题描述 投票:1回答:1

对不起,在网络方面我是个菜鸟。我正在尝试使用API​​网关发送excel文件并使用python中的lambda处理它以写入S3。我发送文件为“application / octet-stream”并在获取事件对象后进行解析,如下所示:

import io
import cgi
import pandas as pd
import xlrd

def read_file(event):
    c_type, c_data = parse_header(event['headers']['Content-Type'])
    encoded_file = event['body'].encode('utf-8')
    c_data['boundary'] = bytes(c_data['boundary'], "utf-8")
    parsed_body = cgi.parse_multipart(io.BytesIO(encoded_file), c_data)
    return(parsed_body)

这本质上应该给我一个io.BytesIO流,我应该能够读到它

df = pd.ExcelFile(list(parsed_body.values())[0][0], engine = 'xlrd')

函数read_file()将被lambda_handler称为

def lambda_handler(event, context):
    p_body = read_file(event)
    df = pd.ExcelFile(list(parsed_body.values())[0][0], engine = 'xlrd')
    # Some post processing to the df

我在大熊猫无法读取这个parsed_body的地方失败了。我也尝试了multipart库,因为它也没有给我一个结果。

如果有人能告诉我一个方法来解析事件正文并给我一个结果我会很生气。

我得到的错误是

File "<ipython-input-264-dfd56a631cc4>", line 1, in <module>
cgi.parse_multipart(event_bytes, c_data)

File    

"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/cgi.py",line 261, in parse_multipart
    line = fp.readline()

AttributeError: 'bytes' object has no attribute 'readline'
python excel post aws-lambda aws-api-gateway
1个回答
0
投票

我终于找到了答案,使用cURL中的base64编码并将数据传递给API

curl -H 'Content-Type:application/octet-stream' --data-binary '{"file": "'"$(base64 /Path/to/file)"'"}' 'https://someAPI.com/some/path?param1=value1\&param2=value2'

有了这个,API网关在体内接收一个结构为{"file": "Base64 encoded string here"}的json

一旦你有了这个主体,首先得到base64编码的字符串

eventBody = base64.b64decode(json.loads(event['body'])['file'])

现在创建一个空流并将此解码后的字符串写入流中。同时将搜索位置设置为0

toread=io.BytesIO()
toread.write(eventBody)
toread.seek(0)

最后只需将此流传递给熊猫

df=pd.read_excel(toread, sheet_name=sn)

它奏效了。

© www.soinside.com 2019 - 2024. All rights reserved.