Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
Nick Retallack Avatar asked Sep 01 '25 10:09

Nick Retallack


2 Answers

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)
like image 104
lacabra Avatar answered Sep 02 '25 23:09

lacabra


You seem to be asking at least two different things here. I'm going to answer the one that's in your title: Can Flask send multipart responses? (If you need to know whether/how libcurl supports multipart responses, either try it and see, or ask a separate question.)

Of course it can. Even if there's no Flask extension to automate it (I haven't searched to see whether there is), there's nothing stopping you from, e.g., using the email package in the stdlib to generate the MIME envelope manually, and then serving it up with the appropriate Content-Type.

like image 33
abarnert Avatar answered Sep 03 '25 00:09

abarnert