Search code examples
pythoncurlflaskmultipart

Can I serve a multipart http response in Flask?


I want to do a multipart http response similar to the multipart http requests that forms can produce for file uploads. It would contain multiple data segments, each with its own content type. When I google this, all I find is information on streaming.

I don't care if browsers support this, since it's for a client that is using libcurl. However, I'm not sure if libcurl supports multipart responses either. Does it? Are multipart responses a thing you can do?


Solution

  • Building on the other answers, and using the requests toolbelt library, the code would look something like the following:

    from flask import Flask, Response
    from requests_toolbelt import MultipartEncoder
    
    app = Flask(__name__)
    
    @app.route('/downloads')
    def downloads():
        m = MultipartEncoder(
               fields={'field0': 'value', 'field1': 'value',
                       'field2': ('filename', open('file.py', 'rb'), 'text/plain')}
            )
        return Response(m.to_string(), mimetype=m.content_type)