【问题标题】:Using Python Requests library使用 Python 请求库
【发布时间】:2012-03-31 17:22:43
【问题描述】:

嘿,你们所爱的人,我有另一个给你们。 我正在使用 django、requests 和 google checkout。我正准备将 xml 发送到 Google 结帐。一切都很好,除了。使用请求库,我在 POST 中得到了一些我不想要的内容。让我解释。 所以谷歌想要一个正确的 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.

所以我的问题是:有没有办法关闭它,我需要自己修改请求代码,还是什么。 这是我使用请求发布的方式

#....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)

【问题讨论】:

  • 您还应该包括一个提交请求的示例

标签: python django http-request python-requests


【解决方案1】:

问题似乎是您不仅要解析 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:])

【讨论】:

  • 好的,我明白了,谢谢你的回复。我在问是否有办法编辑请求以不这样做。
  • 感谢您的回复,我仍然认为它与请求模块有关,因为服务器上的 xml(静态文件)没有类似的东西。我不认为 get 行不通,因为我需要将文件发布到谷歌。
  • 嘿,我使用 httplib 解决了这个问题,如果你愿意,我会告诉你我是如何做到的,这样你就可以用它来回答这个问题,因为我没有代表来回答我自己的问题。无论如何感谢人,耶稣真的爱你。好的,祝你有美好的一天,保罗
  • @JesusisLord: post or get, r.text 不应该包含任何标题,所以一定要通过r.text而不是r.raw访问xml
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
相关资源
最近更新 更多