pycurl.POSTFIELDS 出现问题

3 投票
3 回答
12213 浏览
提问于 2025-04-15 17:43

我之前在PHP中用过CURL,但这次在Python里第一次用pycurl。

我一直遇到这个错误:

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)

3 个回答

2

我知道这是一条老帖子,但我今天早上花了很多时间在找这个错误。结果发现,pycurl里有个bug,这个bug在版本7.16.2.1中被修复了,导致在64位机器上setopt()这个功能出现问题。

4

我喜欢这个:

post_params = [
    ('ASYNCPOST',True),
    ('PREVIOUSPAGE','yahoo.com'),
    ('EVENTID',5),
]
resp_data = urllib.urlencode(post_params)
mycurl.setopt(pycurl.POSTFIELDS, resp_data)
mycurl.setopt(pycurl.POST, 1)
...
mycurl.perform()
1

看起来你的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://的网址,可能需要安装PyOpenSSL: http://pypi.python.org/pypi/pyOpenSSL

有些系统自带这个,有些则需要通过你喜欢的包管理工具额外安装。


补充:你有没有调用过pycurl.global_init()?我还是建议在可能的情况下使用urllib/urllib2,因为这样你的脚本更容易在其他系统上运行。

撰写回答