How to send a “multipart/related” with requests in python?

后端 未结 2 1832
梦谈多话
梦谈多话 2021-01-01 23:20

I\'m trying to send a multipart/related message using requests in Python. The script seems simple enough, except that requests only seems to allow multipart/form-data messag

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 00:04

    You'll have to create the MIME encoding yourself. You can do so with the email.mime package:

    import requests
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    related = MIMEMultipart('related')
    
    submission = MIMEText('text', 'xml', 'utf8')
    submission.set_payload(open('submission_set.xml', 'rb').read())
    related.attach(submission)
    
    document = MIMEText('text', 'plain')
    document.set_payload(open('document.txt', 'rb').read())
    related.attach(document)
    
    body = related.as_string().split('\n\n', 1)[1]
    headers = dict(related.items())
    
    r = requests.post(url, data=body, headers=headers)
    

    I presumed the XML file uses UTF-8, you probably want to set a character set for the document entry as well.

    requests only knows how to create multipart/form-data post bodies; the multipart/related is not commonly used.

提交回复
热议问题