本文介绍了在Python中解析多部分请求字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串

I have a string like this

"--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--5b34210d81fb44c5a0fdc1a1e5ce42c3--\r\n"

我在其他vairbles中也有请求标头.

I also have request headers available in other vairbles.

如何使用Python3轻松解析?

How do I easily parse this with Python3?

我正在通过API网关在AWS Lambda中处理文件上传,请求主体和标头可通过Python字典获得.

I am handling a file upload in AWS Lambda via API Gateway, request body and headers are available via Python dicts.

关于stackoverflow还有其他类似的问题,但是大多数人都假定使用requests模块或其他模块,并且期望请求的详细信息采用特定的对象或格式.

There are other similar questions on stackoverflow, but most are assuming use of the requests module or other modules and expect the request details to be in a specific object or format.

注意:我知道可以将用户上传到S3并触发Lambda,但是在这种情况下,我故意选择不这样做.

NOTE: I am aware its possible to have user upload to S3 and trigger Lambda, but I am intentionally choosing not to do that in this case.

推荐答案

可以通过类似

from requests_toolbelt.multipart import decoder
multipart_string = "--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--ce560532019a77d83195f9e9873e16a1--\r\n"
content_type = "multipart/form-data; boundary=ce560532019a77d83195f9e9873e16a1"
decoder.MultipartDecoder(multipart_string, content_type)

这篇关于在Python中解析多部分请求字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:19