3

我熟悉 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)

4

3 回答 3

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()
于 2010-04-21T15:08:36.113 回答
2

我知道这是一篇旧帖子,但我刚刚花了一上午的时间试图找出同样的错误。事实证明,7.16.2.1 中修复了 pycurl中的一个错误,导致 setopt() 在 64 位机器上中断。

于 2011-06-01T20:20:04.523 回答
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://URL,您可能需要安装 PyOpenSSL: http ://pypi.python.org/pypi/pyOpenSSL

一些分布包括这个,其他的通过你最喜欢的包管理器将它作为一个额外的包提供。


编辑:你打电话给pycurl.global_init()了吗?我仍然尽可能推荐 urllib/urllib2,因为您的脚本将更容易移动到其他系统。

于 2010-01-07T02:06:49.607 回答