处理[Errno 111]连接拒绝按烧瓶中的请求返回

时间:2013-08-21 09:35:10

标签: python error-handling flask python-requests

我的后端是用java开发的,可以进行各种处理。我的前端是使用python的flask框架开发的。我正在使用requests发送请求并从java中的api获取响应。

以下是我的代码中的行:

req = requests.post(buildApiUrl.getUrl('user') + "/login", data=payload)

我的问题是,有时当tomcat实例没有运行或java apis存在问题时,我总是从请求中得到错误,如下所示:

    ERROR:root:HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /MYAPP/V1.0/user/login (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
Traceback (most recent call last):
  File "/home/rahul/git/myapp/webapp/views/utils.py", line 31, in decorated_view
    return_value = func(*args, **kwargs)
  File "/home/rahul/git/myapp/webapp/views/public.py", line 37, in login
    req = requests.post(buildApiUrl.getUrl('user') + "/login", data=payload)
  File "/home/rahul/git/myapp/venv/local/lib/python2.7/site-packages/requests/api.py", line 88, in post
    return request('post', url, data=data, **kwargs)
  File "/home/rahul/git/myapp/venv/local/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/home/rahul/git/myapp/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 335, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/rahul/git/myapp/venv/local/lib/python2.7/site-packages/requests/sessions.py", line 438, in send
    r = adapter.send(request, **kwargs)
  File "/home/rahul/git/myapp/venv/local/lib/python2.7/site-packages/requests/adapters.py", line 327, in send
    raise ConnectionError(e)
ConnectionError: HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /MYAPP/V1.0/user/login (Caused by <class 'socket.error'>: [Errno 111] Connection refused)

我想处理我在烧瓶应用程序中收到的任何此类错误,以便我可以在网页上给出必要的响应,而不是显示空白屏幕。那我怎么能实现这个呢?

1 个答案:

答案 0 :(得分:2)

使用try-except

捕获异常request.post
try:
    req = requests.post(buildApiUrl.getUrl('user') + "/login", data=payload)
except requests.exceptions.RequestException:
    # Handle exception ..