pycurl.POSTFIELDS有问题

时间:2010-01-06 23:24:37

标签: python django curl libcurl pycurl

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

3 个答案:

答案 0 :(得分:3)

我喜欢这样:

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 :(得分:2)

我知道这是一个老帖子,但我刚刚花了我的早晨试图追踪同样的错误。事实证明,pycurl中有一个fixed in 7.16.2.1的错误导致setopt()在64位计算机上中断。

答案 2 :(得分:1)

看起来你的pycurl安装(或卷曲库)会以某种方式损坏。从卷曲错误代码文档:

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,因为您的脚本将更容易移动到其他系统。