尝试发送PUT请求时的ConnectionResetError

时间:2017-11-20 13:08:53

标签: python curl python-requests urllib

我正在尝试使用PUT REST Api上传文件,但我得到了ConnectionResetError。我已尝试将urllib.request.Request()urllib.request.urlopen()以及requests.put()一起使用。

当我使用cURL时它正常工作:

$ curl -X PUT http://localhost:5000/root.bar/test/1.0/jre -H 'Content-Type: application/java-archive' -H 'Content-Name: bfg-1.12.16.jar' -H 'Authorization: Basic cm9vdDphbHBpbmU=' -d @C:/Users/niklas/Desktop/bfg-1.12.16.jar

代码的重要部分:

headers = {'Content-Type': args.mime, 'Content-Name': args.name}
if args.auth:
  headers['Authorization'] = build_basicauth(username, password)
url = args.apiurl.rstrip('/') + '/{}/{}/{}/{}'.format(*parts)
if not urllib.parse.urlparse(url).scheme:
  url = 'https://' + url

if args.test:
  command = ['curl', '-X', 'PUT', url]
  for key, value in headers.items():
    command += ['-H', '{}: {}'.format(key, value)]
  command += ['-d', '@' + args.file.name]
  print('$', ' '.join(map(shlex.quote, command)))
  return 0

response = requests.put(url, data=args.file, headers=headers)
print(response)

我错过了cURL正在做什么?

(PS:我也尝试通过传递bytes来使用requests.put()发送data=args.file.read()而不是类似文件的对象

完整的追溯:

$ python -m fatartifacts.web.cli http://localhost:5000 root.bar:test:1.0:jre ~/Desktop/bfg-1.12.16.jar  -m application/java-archive -u root:alpine
Traceback (most recent call last):
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 357, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1065, in _send_output
    self.send(chunk)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 986, in send
    self.sock.sendall(data)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\adapters.py", line 440, in send
    timeout=timeout
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\util\retry.py", line 357, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\packages\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
    chunked=chunked)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 357, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1065, in _send_output
    self.send(chunk)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 986, in send
    self.sock.sendall(data)
urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\niklas\appdata\local\programs\python\python36\Lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\niklas\repos\fatartifacts\fatartifacts\web\cli.py", line 106, in <module>
    main_and_exit()
  File "C:\Users\niklas\repos\fatartifacts\fatartifacts\web\cli.py", line 102, in main_and_exit
    sys.exit(main())
  File "C:\Users\niklas\repos\fatartifacts\fatartifacts\web\cli.py", line 97, in main
    response = requests.put(url, data=args.file, headers=headers)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\api.py", line 126, in put
    return request('put', url, data=data, **kwargs)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\adapters.py", line 490, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

REST API由flaskflask-restful实现。

时似乎发生了这种异常
  • 使用Python(urllib.requestrequests
  • 发出请求
  • API使用flask.abort()
  • 返回非200状态代码

1 个答案:

答案 0 :(得分:1)

问题是Flask REST API没有使用随请求发送的所有内容。在abort(403)被读取之前,Flask应用程序调用了flask.request.stream

由于我不想在请求被拒绝时读取所有数据,我发现调用request.environ['wsgi.input'].close()关闭流而不先读取内容,这样可以避免ConnectionResetError在客户端。

def close_input_stream(func):
  @functools.wraps(func)
  def wrapper(*a, **kw):
    try:
      return func(*a, **kw)
    finally:
      fp = request.environ.get('wsgi.input')
      if fp:
        fp.close()
  return wrapper