在Python 2.7中找不到支持HTTP PUT的库

3 投票
3 回答
706 浏览
提问于 2025-04-16 13:49

我需要在Python中执行HTTP的PUT操作,哪些库被证明可以支持这个功能呢?更具体一点,我需要对密钥对进行PUT操作,而不是上传文件。

我尝试使用restful_lib.py这个库,但从我正在测试的API中得到的结果都是不正确的。(我知道结果不对,因为我可以在命令行用curl发送同样的请求,并且它能正常工作。)

在参加2011年的Pycon大会后,我觉得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()

3 个回答

0

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

我的代码现在是这样的:

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

更新:现在我得到了有效的响应。这似乎就是我的解决方案。(最后的美化打印功能还没工作,但我并不在乎,这只是我在构建这个功能时用的。)

2

建议使用urlliburllib2这两个库。

3

httplib 应该负责处理。

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

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

撰写回答