Python: 如何处理 https 连接被拒绝错误并将日志写入服务器
Python: How to handle https connection refused error and write the logs in server
我正在尝试处理 post 请求的特定异常类型,但在执行期间 URL 抛出错误
Connection refused
当控件到达代码时
except requests.exceptions.ConnectionError as connErr:
这本身就抛出异常。
"在处理上述异常的过程中,又发生了一个异常:"
据我所知,打印语句不会将错误写入服务器日志,因此我必须使用记录器将日志发布到服务器。
所以我的问题是:
- 如何在 Python.
中以正确的方式定义异常处理
- 连接被拒绝-我应该从这个错误中得出什么结论。 post 请求是否需要一些凭据?或者那个 IP 本身不起作用??
目前我正在使用 Azure insight 来跟踪已发布日志中的错误。
import requests
import logging
data={'number': 12524, 'type': 'issue', 'action': 'show'}
def GetPost(data):
logging.info('-----------GetPost Function Starts Here-----------')
try:
headers = {
'user-agent': 'customize header string',
'Content-Type': 'application/json; charset=utf-8'
}
response = requests.post('http://dummyurl.org', data= data, headers=headers, timeout=3)
logging.info('Http received response code: ', response.status_code)
response.raise_for_status()
except requests.exceptions.HTTPError as httpErr:
logging.error("Http Error: ", exc_info=httpErr)
except requests.exceptions.ConnectionError as connErr:
logging.error("Error Connecting: ", exc_info=connErr)
except requests.exceptions.Timeout as timeOutErr:
logging.error("Timeout Error: ", exc_info=timeOutErr)
except requests.exceptions.RequestException as reqErr:
logging.error("Something Else: ", exc_info=reqErr)
except Exception as err:
logging.error("Other error occurred: ", exc_info=err)
logging.info('-----------GetPost Function Ends Here-----------')
以下是我从 Azure Insight 获取的错误日志:
Error Connecting:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 169, in _new_conn
conn = connection.create_connection(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/connection.py", line 96, in create_connection
raise err
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/connection.py", line 86, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 699, in urlopen
httplib_response = self._make_request(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 382, in _make_request
self._validate_conn(conn)
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 1010, in _validate_conn
conn.connect()
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 353, in connect
conn = self._new_conn()
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 181, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/adapters.py", line 439, in send
resp = conn.urlopen(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 755, in urlopen
retries = retries.increment(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/retry.py", line 574, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='dummyip', port=443): Max retries exceeded with url: /test.gateway/rest/RestEndpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/PWO_EventHubTrigger/postCall.py", line 13, in GetPost
response = requests.post('https://dummyip:443/test.gateway/rest/RestEndpoint', data= data, headers=headers, timeout=3)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='dummyip', port=443): Max retries exceeded with url: /test.gateway/rest/RestEndpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused'))
我正在从主函数调用 GetPost 函数。
我是 python 开发新手,正在尝试编写 Azure 函数。有多个类似的 post 可用但无法确定正确答案:(
how do define exception handling in a correct way in Python.
从你的描述来看,你的异常处理似乎是正确的。
During handling of the above exception, another exception occurred:
当你抛出异常或者except部分在except部分有问题时总是会出现这个问题。
你定义了'httpErr'吗?
下面的代码似乎是我这边的问题:
try:
x = 2
y = 0
result = x / y
except ZeroDivisionError as e:
logging.error("Http Error: ", exc_info="<some info>")
Connection refused- what should I conclude by this error. Is it
requires some credentials for the post request?? or that IP itself is
not working??
这个问题有很多可能的原因。端口、防火墙、虚拟网络、ip等。其实这个应该算一个完全不同的问题,需要根据你用的东西的具体情况具体分析。
TL;DR
如果您想避免 During handling of the above exception, another exception occurred
从跟踪中捕获第一个异常。
您的异常处理是正确的,只是您没有捕获所有异常:)
一般来说,这样做是可以的,捕获您想要以不同方式处理的异常,否则通常 raise/handle 就可以了。
您的代码:
我收到一个套接字错误,然后引发连接错误,以便修复将套接字错误添加为您期望的第一个异常:
def GetPost(data):
logging.info('-----------GetPost Function Starts Here-----------')
try:
headers = {
'user-agent': 'customize header string',
'Content-Type': 'application/json; charset=utf-8'
}
response = requests.post('http://dummyurl.org', data= data, headers=headers, timeout=3)
logging.info('Http received response code: ', response.status_code)
response.raise_for_status()
except socket.error as exc:
logging.error(f"Caught exception socket.error : {exc}")
except requests.exceptions.HTTPError as httpErr:
logging.error("Http Error: ", exc_info=httpErr)
except requests.exceptions.ConnectionError as connErr:
logging.error("Error Connecting: ", exc_info=connErr)
except requests.exceptions.Timeout as timeOutErr:
logging.error("Timeout Error: ", exc_info=timeOutErr)
except requests.exceptions.RequestException as reqErr:
logging.error("Something Else: ", exc_info=reqErr)
except Exception as err:
raise RuntimeError(f"Something bad happened {err}") from None
logging.info('-----------GetPost Function Ends Here-----------')
GetPost(data)
我正在尝试处理 post 请求的特定异常类型,但在执行期间 URL 抛出错误
Connection refused
当控件到达代码时
except requests.exceptions.ConnectionError as connErr:
这本身就抛出异常。 "在处理上述异常的过程中,又发生了一个异常:" 据我所知,打印语句不会将错误写入服务器日志,因此我必须使用记录器将日志发布到服务器。 所以我的问题是:
- 如何在 Python. 中以正确的方式定义异常处理
- 连接被拒绝-我应该从这个错误中得出什么结论。 post 请求是否需要一些凭据?或者那个 IP 本身不起作用??
目前我正在使用 Azure insight 来跟踪已发布日志中的错误。
import requests
import logging
data={'number': 12524, 'type': 'issue', 'action': 'show'}
def GetPost(data):
logging.info('-----------GetPost Function Starts Here-----------')
try:
headers = {
'user-agent': 'customize header string',
'Content-Type': 'application/json; charset=utf-8'
}
response = requests.post('http://dummyurl.org', data= data, headers=headers, timeout=3)
logging.info('Http received response code: ', response.status_code)
response.raise_for_status()
except requests.exceptions.HTTPError as httpErr:
logging.error("Http Error: ", exc_info=httpErr)
except requests.exceptions.ConnectionError as connErr:
logging.error("Error Connecting: ", exc_info=connErr)
except requests.exceptions.Timeout as timeOutErr:
logging.error("Timeout Error: ", exc_info=timeOutErr)
except requests.exceptions.RequestException as reqErr:
logging.error("Something Else: ", exc_info=reqErr)
except Exception as err:
logging.error("Other error occurred: ", exc_info=err)
logging.info('-----------GetPost Function Ends Here-----------')
以下是我从 Azure Insight 获取的错误日志:
Error Connecting:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 169, in _new_conn
conn = connection.create_connection(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/connection.py", line 96, in create_connection
raise err
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/connection.py", line 86, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 699, in urlopen
httplib_response = self._make_request(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 382, in _make_request
self._validate_conn(conn)
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 1010, in _validate_conn
conn.connect()
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 353, in connect
conn = self._new_conn()
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connection.py", line 181, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/adapters.py", line 439, in send
resp = conn.urlopen(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/connectionpool.py", line 755, in urlopen
retries = retries.increment(
File "/home/site/wwwroot/.python_packages/lib/site-packages/urllib3/util/retry.py", line 574, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='dummyip', port=443): Max retries exceeded with url: /test.gateway/rest/RestEndpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/site/wwwroot/PWO_EventHubTrigger/postCall.py", line 13, in GetPost
response = requests.post('https://dummyip:443/test.gateway/rest/RestEndpoint', data= data, headers=headers, timeout=3)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "/home/site/wwwroot/.python_packages/lib/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='dummyip', port=443): Max retries exceeded with url: /test.gateway/rest/RestEndpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f53b8c1a040>: Failed to establish a new connection: [Errno 111] Connection refused'))
我正在从主函数调用 GetPost 函数。 我是 python 开发新手,正在尝试编写 Azure 函数。有多个类似的 post 可用但无法确定正确答案:(
how do define exception handling in a correct way in Python.
从你的描述来看,你的异常处理似乎是正确的。
During handling of the above exception, another exception occurred:
当你抛出异常或者except部分在except部分有问题时总是会出现这个问题。
你定义了'httpErr'吗?
下面的代码似乎是我这边的问题:
try:
x = 2
y = 0
result = x / y
except ZeroDivisionError as e:
logging.error("Http Error: ", exc_info="<some info>")
Connection refused- what should I conclude by this error. Is it requires some credentials for the post request?? or that IP itself is not working??
这个问题有很多可能的原因。端口、防火墙、虚拟网络、ip等。其实这个应该算一个完全不同的问题,需要根据你用的东西的具体情况具体分析。
TL;DR
如果您想避免 During handling of the above exception, another exception occurred
从跟踪中捕获第一个异常。
您的异常处理是正确的,只是您没有捕获所有异常:)
一般来说,这样做是可以的,捕获您想要以不同方式处理的异常,否则通常 raise/handle 就可以了。
您的代码:
我收到一个套接字错误,然后引发连接错误,以便修复将套接字错误添加为您期望的第一个异常:
def GetPost(data):
logging.info('-----------GetPost Function Starts Here-----------')
try:
headers = {
'user-agent': 'customize header string',
'Content-Type': 'application/json; charset=utf-8'
}
response = requests.post('http://dummyurl.org', data= data, headers=headers, timeout=3)
logging.info('Http received response code: ', response.status_code)
response.raise_for_status()
except socket.error as exc:
logging.error(f"Caught exception socket.error : {exc}")
except requests.exceptions.HTTPError as httpErr:
logging.error("Http Error: ", exc_info=httpErr)
except requests.exceptions.ConnectionError as connErr:
logging.error("Error Connecting: ", exc_info=connErr)
except requests.exceptions.Timeout as timeOutErr:
logging.error("Timeout Error: ", exc_info=timeOutErr)
except requests.exceptions.RequestException as reqErr:
logging.error("Something Else: ", exc_info=reqErr)
except Exception as err:
raise RuntimeError(f"Something bad happened {err}") from None
logging.info('-----------GetPost Function Ends Here-----------')
GetPost(data)