簡體   English   中英

使用Python請求庫

[英]Using Python Requests library

嘿,所有你愛的人,我有另一個給你。 我正在使用django,請求和谷歌結賬。 我正准備將xml發送到Google Checkout。 一切都很好。 使用請求庫我得到了一些我不希望在POST中的內容。 讓我解釋。 所以google想要一個正確的XML文件,得到它,我正在使用一個甜蜜的庫來從模式中創建數據結構。 所以我的XML是正確的。 請求雖然將此發送給谷歌。

--178.32.28.118.55290.2265475.1333156904.984.1
Content-Disposition: form-data; name="this.xml"; filename="../xml/this.xml"
Content-Type: application/xml

<?xml version="1.0" ?>
<checkout-shopping-cart xmlns='http://checkout.google.com/schema/2'>
<shopping-cart>
    <item>
        <digital-content>
            <url>/site_media/digitalGoods/Resume.html.pdf</url>
            <description>None Yet</description>
            <display-disposition>OPTIMISTIC</display-disposition>
        </digital-content>
        <item-name>Fire Safety Part 1</item-name>
        <item-description>&lt;p&gt;Pellentesque habitant morbi tristique senectus et   netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
</item-description>
        <unit-price currency="USD">1.500000e+01</unit-price>
        <quantity>1</quantity>
        <merchant-item-id>1</merchant-item-id>
    </item>
</shopping-cart>
<checkout-flow-support>    
<merchant-checkout-flow-support/>
</checkout-flow-support>
</checkout-shopping-cart>
--178.32.28.118.55290.2265475.1333156904.984.1--

我認為問題是請求將這些數字和那些標題放在xml之上,就像它們是一個文檔一樣。 它也是在xml之后直接寫這些數字。 我認為這是一個問題,因為我從谷歌集成控制台得到的錯誤是。

 Error parsing XML; message from parser is: Content is not allowed in prolog.

所以我的問題是:有沒有辦法解決這個問題,我是否需要破壞我自己的請求代碼,或者什么。 這是我如何使用requets進行POST

#....other code and vars above
sendfile = {'this.xml':open('../xml/this.xml', 'r')}#the file
headers={'Authorization':("Basic %s" % auth),#google specific headers
        'Content-Type':'application/xml; charset=UTF-8',
        'Accept':'application/xml; charset=UTF-8'}
#send POST
r = requests.post(diagnose_turl, files=sendfile,headers=headers, verify=False)

問題似乎是你不僅試圖解析XML,而且還試圖解析內容類型的頭,並且解析器抱怨因為它期望XML根元素,而不是“Content-Disposition”字符串。

這很奇怪,因為如果你這樣做:

response = requests.post(some_url, ...)

response.text不應該包含標題。 如果您正在使用原始響應,請切換到response.text

如果您正在獲取標題,請在將第一個空行( \\r\\n\\r\\n )之前的所有內容放到解析器之前刪除所有內容:

import re
xml = '\n'.join(re.split(r'\r?\n\r?\n', raw_response)[1:])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM