Parse multipart request string in Python

前端 未结 5 1626
走了就别回头了
走了就别回头了 2020-12-10 09:15

I have a string like this

\"--5b34210d81fb44c5a0fdc1a1e5ce42c3\\r\\nContent-Disposition: form-data; name=\\\"author\\\"\\r\\n\\r\\nJohn Smith\\r\\n--5b34210d         


        
5条回答
  •  孤街浪徒
    2020-12-10 10:10

    If using CGI, I recommend using FieldStorage:

    from cgi import FieldStorage
    
    fs = FieldStorage(fp=event['body'], headers=event['headers'], environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':event['headers']['Content-Type'], })['file']
    originalFileName = fs.filename
    binaryFileData = fs.file.read()
    

    see also: https://stackoverflow.com/a/38718958/10913265

    If the event body contains multiple files:

    fs = FieldStorage(fp=event['body'], headers=event['headers'], environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':event['headers']['Content-Type'], })['file']
    

    delivers a list of FieldStorage objects. So you can do:

    for f in fs:
        originalFileName = f.filename
        binaryFileData = f.file.read()
    

    Altogether my solution for dealing with a single file as well as multiple files as well as a body containing no file and assuring that it was mutlipart/form-data:

    from cgi import parse_header, FieldStorage
    
    #see also: https://stackoverflow.com/a/56405982/10913265
    c_type, c_data = parse_header(event['headers']['Content-Type'])
    assert c_type == 'multipart/form-data'
    
    #see also: https://stackoverflow.com/a/38718958/10913265
    fs = FieldStorage(fp=event['body'], headers=event['headers'], environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':event['headers']['Content-Type'], })['file']
    
    #If fs contains a single file or no file: making FieldStorage object to a list, so it gets iterable
    if not(type(fs) == list):
        fs = [fs]
    
    for f in fs:
        originalFileName = f.filename
        #no file: 
        if originalFileName == '':
            continue
        binaryFileData = f.file.read()
        #Do something with the data 
    

提交回复
热议问题