我正在尝试使用请求向RESTful API发出POST请求。我的代码很简单:
import json
import requests
import subprocess
url = 'https://api.host.name?key=MY_API_KEY'
post_data = {'parameter': 'value'}
try:
requests.post(url, json = post_data, verify=False) # Fails Frequently ...
except requests.exceptions.SSLError:
post_data_str = json.dumps(post_data)
curl_cli = "curl -H \"Content-Type: application/json\" -H \"Accept: application/json\" -X POST -d '%s' %s" %(post_data_str, url)
output = subprocess.check_output(curl_cli , shell=True) # Works every time!
代码有时会起作用,但最常见的是失败并出现错误:
requests.exceptions.SSLError:HTTPSConnectionPool(host ='api.host.name',port = 443):使用url:api.host.name超出了最大重试次数(由SSLError引起(SSLError('未能分配SSL上下文) ”,),))
错误似乎是随机的,即有时它在第一次运行代码时失败,有时是在几次成功请求之后。当我从Postman(一个向REST API发出请求的应用程序)执行相同的请求时,它总是成功的。
我的requests
版本是2.18.4,我在Ubuntu 16.04.3 LTS上使用Python 2.7.12
编辑:
我也试过urllib2
,结果相似。代码是:
import json
import urllib2
url = 'https://api.host.name?key=MY_API_KEY'
post_dict = {'parameter': 'value'}
post_data = json.dumps(post_dict)
clen = len(post_data)
req = urllib2.Request(url, post_data, {'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
错误基本相同:
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 429, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 447, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1241, in https_open
context=self._context)
File "/usr/lib/python2.7/urllib2.py", line 1167, in do_open
h = http_class(host, timeout=req.timeout, **http_conn_args)
File "/usr/lib/python2.7/httplib.py", line 1262, in __init__
context = ssl._create_default_https_context()
File "/usr/lib/python2.7/ssl.py", line 411, in create_default_context
context = SSLContext(PROTOCOL_SSLv23)
File "/usr/lib/python2.7/ssl.py", line 337, in __new__
self = _SSLContext.__new__(cls, protocol)
ssl.SSLError: ('failed to allocate SSL context',)
答案 0 :(得分:1)
如果没有更多信息,我可以提供以下内容:
希望这有帮助!