如何使用Python请求和requests-toolbelt解析/解码多部分表单数据

vsmadaxz  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(95)

我试图创建一个AWS Lambda函数与函数URL。该函数应接受文件(图像)上传沿着一些字段,如名称,日期和文本。
我从REACTJS中的前端发送请求:

export async function postFormData(url, form) {
  const response = await axios({
    method: "post",
    url,
    data: form,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  })

  return response.data
}

我也使用postman来测试API。但是,我无法解析lambda函数中的字段,我一直得到下面的错误,我猜这意味着主体没有正确形成?但我使用postman发送它,所以我不知道我做错了什么

ImproperBodyPartContentException: content does not contain CR-LF-CR-LF

我的AWS Lambda python3代码:

import json
import requests
from requests_toolbelt.multipart import decoder

def lambda_handler(event, context):
    # get the request body and headers
    body = event['body']
    headers = event['headers']
    
    # decode the multipart/form-data request
    data = decoder.MultipartDecoder(body.encode(), headers['content-type'])

    # iterate over the parts of the request
    for part in data.parts:
        # check if the part is a file
        if part.headers[b'content-disposition'].startswith(b'form-data; name="file"; filename='):
            # get the filename and content type of the file
            filename = part.headers[b'content-disposition'].decode('utf-8').split('"')[3]
            content_type = part.headers[b'content-type'].decode('utf-8')
            # write the file content to disk or do something else with it
            with open(filename, 'wb') as f:
                f.write(part.content)
        # if the part is not a file, print its content
        else:
            print(part.content.decode('utf-8'))

    # create the response
    response = {
        'statusCode': 200,
        'body': json.dumps({'message': 'Request processed successfully'})
    }

    return response

我只允许使用requests和requests toolbelt,所以如果你能给我一个只使用这两个库的解决方案,我将不胜感激。
总之,我只想使用AWS Lambda创建一个python API,它接受一些字符串数据,如名称,日期和文本以及图像文件。我想然后将图像文件保存为/tmp目录中的.png。

toiithl6

toiithl61#

我想明白了:

def lambda_handler(event, context):
    # get the request body and headers
    headers = event['headers']
    # decode the multipart/form-data request
    postdata = base64.b64decode(event['body'])

    request = {} # Save request here
    
    for part in decoder.MultipartDecoder(postdata, headers['content-type']).parts:

        decoded_header = part.headers[b'Content-Disposition'].decode('utf-8')
        key = get_key(decoded_header)
        request[key] = part.content

    print(request) # This is the request



def get_key(form_data):
    # 'form-data; name="birth_date"', 'content': b'2012-123'
    key = form_data.split(";")[1].split("=")[1].replace('"', '')

    print(key)

    return key

相关问题