Python:如何处理 https 连接被拒绝错误并在服务器中写入日志 [英] Python: How to handle https connection refused error and write the logs in server
问题描述
我正在尝试处理发布请求的特定异常类型,但在执行期间 URL 抛出错误
I am trying to handle the specific exception type for a post request but during the execution the URL is throwing the error
Connection refused
当控件到达代码时
except requests.exceptions.ConnectionError as connErr:
这本身会引发异常."在处理上述异常的过程中,又发生了一个异常:"据我所知,打印语句不会将错误写入服务器日志,因此我必须使用记录器将日志发布到服务器.所以我的问题是:
this itself throws an exception. "During handling of the above exception, another exception occurred:" Where as I know print statement will not write the error to the server logs so I have to use the logger to publish the logs to the server. So my questions are:
- 如何在 Python 中以正确的方式定义异常处理.
- 连接被拒绝 - 我应该通过这个错误得出什么结论.发布请求是否需要一些凭据?或者那个 IP 本身不起作用??
目前我正在使用 Azure Insight 来跟踪已发布日志中的错误.
Presently I am using Azure insight to trace the errors in the published log.
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 函数.有多个类似的帖子可用,但无法确定正确答案:(
I am calling GetPost function from the main function. I am new to python development and trying to write a Azure functions. There are multiple similar posts are available but unable to identify the correct answer :(
推荐答案
TL;DR
如果您想避免在处理上述异常的过程中,发生了另一个异常
从跟踪中捕获第一个异常.
If you want to avoid During handling of the above exception, another exception occurred
catch the first exception from your trace.
您的异常处理是正确的,只是您没有捕获所有异常:)
Your exception handling is correct it's just that you aren't catching all of them :)
一般情况下这样做是可以的,捕获您想要以不同方式处理的异常,否则只是通常引发/处理它.
In general it is okay to do that, catch exceptions which you want to handle differently otherwise just raise/handle it commonly.
您的代码:
我收到一个套接字错误,然后引发了一个 ConnectionError,为了修复该错误,将套接字错误添加为您期望的第一个异常:
I am getting a socket error which then raises a ConnectionError, in order to fix that add the socket error as the first exception you expect:
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)
参考:处理异常
这篇关于Python:如何处理 https 连接被拒绝错误并在服务器中写入日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!