python - PyCurl 类型错误 : invalid argument to setopt

标签 python post curl pycurl

我正在使用 PyCurl 发送带有文件附件的 POST 请求:

d = pycurl.Curl()
d.setopt(pycurl.URL, url)
# d.setopt(pycurl.RETURNTRANSFER, True)
d.setopt(pycurl.POST, True)
d.setopt(pycurl.POSTFIELDS, {filename: "@" + filename})
b = StringIO.StringIO()
d.setopt(pycurl.WRITEFUNCTION, b.write)
d.perform()
d.close()
message = b.getvalue()

我得到:

Something went wrong, invalid arguments to setopt
Traceback (most recent call last):
  File "hasoff.py", line 214, in create_offers_for_advertiser
    if filename:
TypeError: invalid arguments to setopt

怎么了?

最佳答案

pycurl.POSTFIELDS 需要 URL 编码的数据。 From docs :

post_data = {'field': 'value'}
postfields = urlencode(post_data)
c.setopt(c.POSTFIELDS, postfields)

您不能使用 pycurl.POSTFIELDS 发送文件。

可以使用 pycurl.HTTPPOST 发送文件。 From docs :

c.setopt(c.HTTPPOST, [
    ('fileupload', (
        c.FORM_FILE, __file__,
        c.FORM_FILENAME, 'helloworld.py',
        c.FORM_CONTENTTYPE, 'application/x-python',
    )),
])

关于python - PyCurl 类型错误 : invalid argument to setopt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37385115/

相关文章:

Python:将 PDF 转换为 DOC

http - WP7 HttpWebRequest POST,服务器返回 "{ result: ' ok' }\"in emulator, but "错误 : NotFound"on device

ssl - 带有 cacert 选项的 Ansible URI 模块

PHP curl : CURLOPT_URL, CURLOPT_POST 和 CURLOPT_POSTFIELDS

php - 提交表单时德语变音符中断

oracle - 如何在 PL/SQL 中发送带有表单数据和参数的 POST 请求

python - 如何加速pandas申请字符串匹配

python - 电子邮件作为 email.Message Python 中的类对象

Python 在嵌套列表中嵌套列表而不循环

ios - 选取图片并上传