gpt4 book ai didi

python - 在 python 中解析 POSTed Excel 文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:43 27 4
gpt4 key购买 nike

抱歉,在网络方面我是个菜鸟。我正在尝试使用 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

我在 pandas 无法读取此 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'

最佳答案

我终于找到了答案,使用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 编码的字符串"}

的 json

一旦你有了这个正文,首先获取base64编码的字符串

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

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

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

最后将此流传递给 pandas

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

并且成功了。

关于python - 在 python 中解析 POSTed Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084962/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com