Can I serve a multipart http response in Flask?

好久不见. 提交于 2019-12-19 04:46:16

问题


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?


回答1:


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)



回答2:


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.




回答3:


So, I was looking into something similar today. This is an old question. But so that you dont have search - simple answer is create a Multipart mime entity from email package. And return that. Flask will handle the output correctly.

responseBody = MIMEMultipart() ...

Response(responseBody.as_string())



来源:https://stackoverflow.com/questions/26643354/can-i-serve-a-multipart-http-response-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!