Python MultiPart POST Malformed

烈酒焚心 提交于 2019-12-08 05:45:57

问题


I'm trying to figure out how to write a MultiPart POST request to OneNote using Python. Here is what I've done so far:

url = ROOT_URL+"pages"

headers = {"Content-Type":"multipart/form-data; boundary=MyAppPartBoundary",
           "Authorization" : "bearer " + access_token}         

txt = """--MyAppPartBoundary
        Content-Disposition:form-data; name="Presentation"
        Content-type:text/html

        <!DOCTYPE html>
        <html>
          <head>
            <title>One Note Text</title>
          </head>
            <body>
              <p>Hello OneNote World</p>
            </body>
        </html>
        --MyAppPartBoundary--
        """

session = requests.Session()
request = requests.Request(method="POST", headers=headers,
                           url=url,  data=txt)
prepped = request.prepare()
response = session.send(prepped)

However, whenever I go to run it, I get the error response "The multi-part payload was malformed." I've also tried it like this:

url = ROOT_URL+"pages"

headers = {"Content-Type":"multipart/form-data; boundary=MyAppPartBoundary",
           "Authorization" : "bearer " + access_token} 

txt = """<!DOCTYPE html>
        <html>
          <head>
            <title>One Note Text</title>
          </head>
            <body>
              <p>Hello OneNote World</p>
            </body>
        </html>"""    

files = {'file1': ('Presentation', txt, 'text/html')}

session = requests.Session()
request = requests.Request(method="POST", headers=headers,
                           url=url,  files=files)
prepped = request.prepare()
response = session.send(prepped)

Same thing. Even super basic:

headers = {"Content-Type":"multipart/form-data; boundary=MyAppPartBoundary",
           "Authorization" : "bearer " + access_token}

files = {'file1': ('filename', 'data', 'text/plain')}

r = requests.post(url, headers=headers, files=files)

Gives that error. What am I doing wrong?


回答1:


First hunch: Make sure line breaks in your request body are CRLF (not just LF). The RFC spec for multipart is very picky about that



来源:https://stackoverflow.com/questions/36069553/python-multipart-post-malformed

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