How can I post a PDF to AWS lambda

瘦欲@ 提交于 2019-12-11 13:26:57

问题


I have AWS Lambda set up.

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps(event)
    }

I would like to POST in a PDF file so that I can operate on it in my lambda function.

Here is my POST code

import requests

headers = {
    'X-API-KEY':'1234',
    'Content-type': 'multipart/form-data'}

files = {
    'document': open('my.pdf', 'rb')
}

r = requests.post(url, files=files,  headers=headers)

display(r)
display(r.text)

I am getting the error:

<Response [400]>
'{"message": "Could not parse request body into json: Unexpected character (\\\'-\\\' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value

How can I POST over my PDF and be able to properly send over my PDF and access it in Lambda?

Note:

I am successful if I do this:

payload = '{"key1": "val1","key2": 22,"key3": 15,"key4": "val4"}' 
r = requests.post(url = URL, data=payload, headers=HEADERS) 

It is just the PDF part which I can't get


回答1:


I figured it out. Took me a ton of time but I think I got it. Essentially it's all about encoding and decoding as bytes. Didn't have to touch the API Gateway at all.

Request:

HEADERS = {'X-API-KEY': '12345'}
data = '{"body" : "%s"}' % base64.b64encode(open(path, 'rb').read())
r = requests.post(url, data=data, headers=HEADERS)

In lambda

from io import BytesIO
def lambda_handler(event, context):
    pdf64 = event["body"]

    # Need this line as it does 'b'b'pdfdatacontent'.
    pdf64 = pdf64[2:].encode('utf-8')

    buffer = BytesIO()
    content = base64.b64decode(pdf64)
    buffer.write(content)


来源:https://stackoverflow.com/questions/57121011/how-can-i-post-a-pdf-to-aws-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!