我熟悉PHP中的CURL,但我第一次使用pycurl在Python中使用它.
我一直收到错误:
Exception Type: error
Exception Value: (2, '')
我不知道这可能是什么意思.这是我的代码:
data = {'cmd': '_notify-synch',
'tx': str(request.GET.get('tx')),
'at': paypal_pdt_test
}
post = urllib.urlencode(data)
b = StringIO.StringIO()
ch = pycurl.Curl()
ch.setopt(pycurl.URL, 'https://www.sandbox.paypal.com/cgi-bin/webscr')
ch.setopt(pycurl.POST, 1)
ch.setopt(pycurl.POSTFIELDS, post)
ch.setopt(pycurl.WRITEFUNCTION, b.write)
ch.perform()
ch.close()
错误是指ch.setopt行(pycurl.POSTFIELDS,post)
解决方法:
看来你的pycurl安装(或curl库)以某种方式被损坏了.从curl错误代码文档:
CURLE_FAILED_INIT (2)
Very early initialization code failed. This is likely to be an internal error or problem.
您可能需要重新安装或重新编译curl或pycurl.
但是,要像你一样做一个简单的POST请求,你实际上可以使用python的“urllib”而不是CURL:
import urllib
postdata = urllib.urlencode(data)
resp = urllib.urlopen('https://www.sandbox.paypal.com/cgi-bin/webscr', data=postdata)
# resp is a file-like object, which means you can iterate it,
# or read the whole thing into a string
output = resp.read()
# resp.code returns the HTTP response code
print resp.code # 200
# resp has other useful data, .info() returns a httplib.HTTPMessage
http_message = resp.info()
print http_message['content-length'] # '1536' or the like
print http_message.type # 'text/html' or the like
print http_message.typeheader # 'text/html; charset=UTF-8' or the like
# Make sure to close
resp.close()
要打开https:// URL,您可能需要安装PyOpenSSL:
http://pypi.python.org/pypi/pyOpenSSL
一些distibutions包括这个,其他的通过你最喜欢的包管理器提供它作为额外的包.
编辑:你有没有打电话给pycurl.global_init()?我仍然建议尽可能使用urllib / urllib2,因为您的脚本将更容易移动到其他系统.