gpt4 book ai didi

python - 如何使用 Aws Lambda(python)接收文件

转载 作者:太空狗 更新时间:2023-10-29 19:35:54 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何通过 Python 中的 API 调用接收浏览器发送的文件。

Web 客户端可以发送任何类型的文件(比如 .txt、.docx、.xlsx 等)。我不知道我是否应该使用二进制文件。

想法是在 S3 之后保存文件。现在我知道可以使用像 Aws Amplify 这样的 js 库并生成一个临时 url,但我对该解决方案不太感兴趣。

感谢任何帮助,我已经在 Python 中广泛搜索了一个解决方案,但我找不到任何实际工作的东西!

我的 API 是私有(private)的,我正在使用无服务器进行部署。

files_post:
handler: post/post.post
events:
- http:
path: files
method: post
cors: true
authorizer:
name: authorizer
arn: ${cf:lCognito.CognitoUserPoolMyUserPool}

编辑

我有一半的解决方案适用于文本文件但不适用于 PDF、XLSX 或图像,如果有人有我会非常高兴

from cgi import parse_header, parse_multipart
from io import BytesIO
import json


def post(event, context):


print event['queryStringParameters']['filename']
c_type, c_data = parse_header(event['headers']['content-type'])
c_data['boundary'] = bytes(c_data['boundary']).encode("utf-8")

body_file = BytesIO(bytes(event['body']).encode("utf-8"))
form_data = parse_multipart(body_file, c_data)

s3 = boto3.resource('s3')
object = s3.Object('storage', event['queryStringParameters']['filename'])
object.put(Body=form_data['upload'][0])

最佳答案

您正在使用 API 网关,因此您的 lambda 事件将映射到类似这样的内容(来自 Amazon Docs ):

{
"resource": "Resource path",
"path": "Path parameter",
"httpMethod": "Incoming request's method name"
"headers": {String containing incoming request headers}
"multiValueHeaders": {List of strings containing incoming request headers}
"queryStringParameters": {query string parameters }
"multiValueQueryStringParameters": {List of query string parameters}
"pathParameters": {path parameters}
"stageVariables": {Applicable stage variables}
"requestContext": {Request context, including authorizer-returned key-value pairs}
"body": "A JSON string of the request payload."
"isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}

您可以在正文中将文件作为 base64 值传递,并在您的 lambda 函数中对其进行解码。采用以下 Python 代码段

def lambda_handler(event, context):
data = json.loads(event['body'])
# Let's say we user a regular <input type='file' name='uploaded_file'/>
encoded_file = data['uploaded_file']
decoded_file = base64.decodestring(encoded_file)
# now save it to S3

关于python - 如何使用 Aws Lambda(python)接收文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171891/

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