【问题标题】:Trouble finding library that supports http PUT in Python 2.7在 Python 2.7 中找不到支持 http PUT 的库
【发布时间】:2011-07-16 14:24:44
【问题描述】:

我需要从 python 执行 http PUT 操作 哪些库已被证明支持此操作?更具体地说,我需要对密钥对执行 PUT,而不是文件上传。

我一直在尝试使用 restful_lib.py,但是我从我正在测试的 API 中得到了无效的结果。 (我知道结果是无效的,因为我可以从命令行使用 curl 触发相同的请求并且它可以工作。)

参加 Pycon 2011 后,我觉得 pycurl 可能是我的解决方案,所以我一直在尝试实现它。我这里有两个问题。首先,pycurl 将“PUT”重命名为“UPLOAD”,这似乎意味着它专注于文件上传而不是密钥对。其次,当我尝试使用它时,我似乎从未从 .perform() 步骤中获得回报。

这是我当前的代码:

import pycurl
import urllib
url='https://xxxxxx.com/xxx-rest'
UAM=pycurl.Curl()

def on_receive(data):
  print data

arglist= [\
    ('username', 'testEmailAdd@test.com'),\
    ('email', 'testEmailAdd@test.com'),\
    ('username','testUserName'),\
    ('givenName','testFirstName'),\
    ('surname','testLastName')]
encodedarg=urllib.urlencode(arglist)
path2= url+"/user/"+"99b47002-56e5-4fe2-9802-9a760c9fb966"
UAM.setopt(pycurl.URL, path2)
UAM.setopt(pycurl.POSTFIELDS, encodedarg)
UAM.setopt(pycurl.SSL_VERIFYPEER, 0)
UAM.setopt(pycurl.UPLOAD, 1) #Set to "PUT"
UAM.setopt(pycurl.CONNECTTIMEOUT, 1) 
UAM.setopt(pycurl.TIMEOUT, 2) 
UAM.setopt(pycurl.WRITEFUNCTION, on_receive)
print "about to perform"
print UAM.perform()

【问题讨论】:

    标签: python http pycurl http-put


    【解决方案1】:

    httplib 应该管理。

    http://docs.python.org/library/httplib.html

    这个页面上有一个例子http://effbot.org/librarybook/httplib.htm

    【讨论】:

      【解决方案2】:

      urlliburllib2 也被推荐。

      【讨论】:

      • 谢谢,阅读答案并尝试立即实施。
      【解决方案3】:

      感谢大家的帮助。我想我找到了答案。

      我的代码现在看起来像这样:

      import urllib
      import httplib
      import lxml
      from lxml import etree
      url='xxxx.com'
      UAM=httplib.HTTPSConnection(url)
      
      arglist= [\
          ('username', 'testEmailAdd@test.com'),\
          ('email', 'testEmailAdd@test.com'),\
          ('username','testUserName'),\
          ('givenName','testFirstName'),\
          ('surname','testLastName')\
          ]
      encodedarg=urllib.urlencode(arglist)
      
      uuid="99b47002-56e5-4fe2-9802-9a760c9fb966"
      path= "/uam-rest/user/"+uuid
      UAM.putrequest("PUT", path)
      UAM.putheader('content-type','application/x-www-form-urlencoded')
      UAM.putheader('accepts','application/com.internap.ca.uam.ama-v1+xml')
      UAM.putheader("Content-Length", str(len(encodedarg)))
      UAM.endheaders()
      UAM.send(encodedarg)
      response = UAM.getresponse()
      html = etree.HTML(response.read())
      result = etree.tostring(html, pretty_print=True, method="html")
      print result
      

      更新:现在我收到了有效的回复。这似乎是我的解决方案。 (最后的漂亮打印不起作用,但我真的不在乎,那只是在我构建函数时。)

      【讨论】:

        猜你喜欢
        • 2010-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-19
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        相关资源
        最近更新 更多