Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - parse multipart/form-data, received from requests post

I am writing Web Service Client, using requests library. I am getting data in multipart/form-data that contains a file and text-json. I have no idea how to parse it. Is there a proper library to parse multipart/form-data format in python or should I write parser on my own?

my code:

data = {
  "prototypeModel" :('prototypeModel', open(prototypeModel, 'rb'), 'application/octet-stream', {'Expires': '0'}),
  "mfcc_1" : ('mfcc', open(mfcc_1, 'rb'), 'application/octet-stream', {'Expires': '0'}),
  "mfcc_2" : ('mfcc', open(mfcc_2, 'rb'), 'application/octet-stream', {'Expires': '0'}),
  "mfcc_3" : ('mfcc', open(mfcc_3, 'rb'), 'application/octet-stream', {'Expires': '0'}),
}

print( '---------------------- start enroll ----------------------')
testEnrollResponse = requests.post(server+sessionID, files = data, json = declaredParameters)

b' --c00750d1-8ce4-4d29-8390-b50bf02a92cc Content-Disposition: form-data; name="playbackHash" Content-Type: application/octet-stream x16x00x00x00x00x00x00x00serialization::archive x00x04x08x04 .... x00x00Rx94x9bpx8cx00 --c00750d1-8ce4-4d29-8390-b50bf02a92cc Content-Disposition: form-data; name="usersMFCC" Content-Type: application/octet-stream x16x00x00x00x00x00x00x00serialization::archive x00x04x08x04x08x01x00x00x00x00x00x00x00x00xf8x16x00x00x00x00x00x00uxbdxb4/xda1xeaxbfx0fxedxa2<xc9xf8xe7xbf?xd5xf06uxe7xf0xbfxd4x8dxd4xa1Fxbex03@x85X!x19xd8Ax06@x8coxf7 .....
x80xd9x95Yxnxd0? --c00750d1-8ce4-4d29-8390-b50bf02a92cc Content-Disposition: form-data; name="scoreAndStatus" Content-Type: application/json; charset=utf-8 {"lexLikelihood":1.544479046897232,"overallScore":-nan,"playbackLikelihood":-inf,"status":{"errorCode":0,"errorMessage":""}} --c00750d1-8ce4-4d29-8390-b50bf02a92cc-- '

I replaced more binary data with " ..... "

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're receiving a multipart/form-data response, you can parse it using the requests-toolbelt library like so:

$ pip install requests-toolbelt

After installing it

from requests_toolbelt.multipart import decoder

testEnrollResponse = requests.post(...)
multipart_data = decoder.MultipartDecoder.from_response(testEnrollResponse)

for part in multipart_data.parts:
    print(part.content)  # Alternatively, part.text if you want unicode
    print(part.headers)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...