在 urllib3 中使用证书

use*_*060 4 python ssl google-app-engine

我是 Python 新手。我正在使用 urllib3 与 api 对话。我使用它而不是请求的原因是我想在 GAE 上托管我的应用程序。我的应用程序使用证书。当我发布数据时,出现以下错误:

TypeError: __init__() got an unexpected keyword argument 'cert_reqs'
Run Code Online (Sandbox Code Playgroud)

如何在我的 urlopen 调用中包含证书?一段代码如下

CA_CERTS = ('client-2048.crt', 'client-2048.key')

http = urllib3.PoolManager()
r = http.urlopen('POST', url, body=payload, headers={'X-Application': '???', 'Content-Type': 'application/x-www-form-urlencoded'}, cert_reqs='REQUIRED', ca_certs=CA_CERTS)
print r.status, r.data
Run Code Online (Sandbox Code Playgroud)

mha*_*wke 7

您可以下拉到可以直接执行的HTTPSConnectionPool级别:

from urllib3.connectionpool import HTTPSConnectionPool
conn = HTTPSConnectionPool('httpbin.org', ca_certs='/etc/pki/tls/cert.pem', cert_reqs='REQUIRED')
Run Code Online (Sandbox Code Playgroud)

或者,更简单地或通过connection_from_url()辅助函数:

conn = urllib3.connection_from_url('https://httpbin.org', ca_certs='/etc/pki/tls/cert.pem', cert_reqs='REQUIRED')
Run Code Online (Sandbox Code Playgroud)

请注意,这ca_certs是用于验证远程服务器证书的证书包的文件名。使用cert_filekey_file将您的客户端证书提供给远程服务器:

conn = urllib3.connection_from_url('https://httpbin.org', cert_file='client-2048.crt', key_file='client-2048.key', ca_certs='/etc/pki/tls/cert.pem', cert_reqs='REQUIRED')
Run Code Online (Sandbox Code Playgroud)

然后发出您的请求:

response = conn.request('POST', 'https://httpbin.org/post', fields={'field1':1234, 'field2':'blah'})
>>> print response.data
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "field1": "1234",
    "field2": "blah"
  },
  "headers": {
    "Accept-Encoding": "identity",
    "Connection": "close",
    "Content-Length": "220",
    "Content-Type": "multipart/form-data; boundary=048b02ad15274fc485c2cb2b6a280034",
    "Host": "httpbin.org",
    "X-Request-Id": "92fbc1da-d83e-439c-9468-65d27492664f"
  },
  "json": null,
  "origin": "220.233.14.203",
  "url": "http://httpbin.org/post"
}
Run Code Online (Sandbox Code Playgroud)