天天看点

python POST发送多个段(如json消息+文件)

 用C的时候,数据想怎么组装就怎么组装,而利用 Python

……

  比如,今天吾要发送一个消息,同时上传文件,怎么办?

  • 说明:吾用C调用的时候,只要import这个就会崩溃。原因未知,应该是哪里冲突。
  • 先安装
sudo pip install requests_toolbelt      
  • 代码
from requests_toolbelt.multipart.encoder import MultipartEncoder
 
        m = MultipartEncoder(
            fields={
                'message': json_data,
                'file': (file_name, open(file_path, 'rb'), 'image/jpeg')},
            boundary='---------------------------8654321amtfabcdggg'
        )
 
        response = requests.post(STRANGER_URL, data=m, headers={'Content-Type': m.content_type})