Python MultiPart POST格式错误

时间:2016-03-17 19:06:34

标签: python post request onenote onenote-api

我试图弄清楚如何使用Python向OneNote编写MultiPart POST请求。这是我到目前为止所做的:

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)

但是,每当我去运行它时,我都会得到错误响应&#34;多部分有效负载格式错误。&#34;我也尝过这样的话:

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)

同样的事情。甚至超级基本:

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)

给出错误。我做错了什么?

1 个答案:

答案 0 :(得分:0)

第一次预感:确保请求正文中的换行符是CRLF(而不仅仅是LF)。 multipart的RFC规范非常挑剔