【问题标题】:How to translate url requests using pycurl to python-requests?如何使用 pycurl 将 url 请求转换为 python-requests?
【发布时间】:2014-01-17 21:42:04
【问题描述】:

我想修改以下代码以运行使用“请求”模块。 我有以下代码在网站上运行:

def post(url, message, key, sign):

    curl = pycurl.Curl()
    curl.setopt(pycurl.URL, url)
    curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    buf = cStringIO.StringIO()
    curl.setopt(pycurl.WRITEFUNCTION, buf.write)
    curl.setopt(pycurl.POSTFIELDS, message)
    curl.setopt(pycurl.HTTPHEADER, ['Key:' + key,
                                'Sign:' + (sign)])
    curl.perform()
    response = buf.getvalue()
    buf.close()
    return response        

我尝试通过请求访问该网站,但使用以下代码因请求值无效而被拒绝:

def post(url, message, key, sign):
    import requests
    session = requests.session()
    session.headers = {'Key': key, 'Sign': sign}
    response = session.post(url, message)
    return response

这些方法的行为不同,我做错了什么?

谢谢。

【问题讨论】:

  • 你应该添加你的回溯。如果它与 ssl 证书有关,请尝试使用 session.post(url, message, verify=False)
  • 我没有回溯,因为没有 python 失败。从网站返回错误...

标签: python python-requests pycurl


【解决方案1】:

使用 Pycurl:

POST /post HTTP/1.1
User-Agent: PycURL/7.32.0
Host: 127.0.0.1:4000
Accept: */*
Key:key
Sign:sign
Content-Length: 3
Content-Type: application/x-www-form-urlencoded

foo

有请求:

POST /post HTTP/1.1
Host: 127.0.0.1:4000
Accept-Encoding: identity
Content-Length: 3
Key: key
Sign: sign

foo

有几个差异可能导致您的错误:

  • 缺少 User-AgentAccept 标头。这是因为您覆盖了包含这些默认标头的session.headers 属性。试试这个:

    session.headers.update({'Key': key, 'Sign': sign})

  • 缺少Content-Type 标头。我认为您将字符串作为message 参数传递。 Requests 不知道这是application/x-www-form-urlencoded,因此没有设置相关的标头。 要么:

    • 自己设置标题
    • 更好:传递请求参数字典。它们将被正确编码和声明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多