Python如何处理HTTPS连接被拒错误并将日志写入服务器
问题1:Python中如何正确定义异常处理逻辑
- 你现有的异常捕获顺序是正确的,遵循了从具体异常到宽泛异常的原则,不会出现子类型异常被父类异常提前拦截的问题。
- 你遇到的「处理异常时又抛出新异常」的问题,核心是
logging方法的使用错误:exc_info参数接受的是布尔值、或者异常栈三元组,你直接传入异常对象会触发参数类型错误。正确做法是在except块内直接设置exc_info=True,logging会自动捕获当前异常的完整栈信息;也可以直接用logging.exception()方法,该方法默认开启exc_info=True,专门用于异常场景的日志打印。- 你打印响应状态码的代码
logging.info('Http received response code: ', response.status_code)写法错误,logging第一个参数为格式字符串,后续参数为填充值,正确写法是logging.info('Http received response code: %s', response.status_code),或者用f-string格式化:logging.info(f'Http received response code: {response.status_code}')。
- 额外优化点:你请求头设置了
Content-Type: application/json,但传参用了data=data,这会让requests把字典转为表单格式发送,和请求头不符,应该修改为json=data,requests会自动序列化字典为JSON格式,同时自动设置正确的请求头。
修正后的代码如下:
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' } # 用json参数传字典,自动适配JSON格式 response = requests.post('http://dummyurl.org', json=data, headers=headers, timeout=3) # 正确打印状态码 logging.info(f'Http received response code: {response.status_code}') response.raise_for_status() except requests.exceptions.HTTPError as httpErr: # 用logging.exception自动打印异常栈 logging.exception("Http Error: ") except requests.exceptions.ConnectionError as connErr: logging.exception("Error Connecting: ") except requests.exceptions.Timeout as timeOutErr: logging.exception("Timeout Error: ") except requests.exceptions.RequestException as reqErr: logging.exception("Something Else: ") except Exception as err: logging.exception("Other error occurred: ") logging.info('-----------GetPost Function Ends Here-----------')
问题2:Connection refused错误代表什么含义
Connection refused是TCP传输层的错误,和应用层的凭证校验无关,不会是因为缺少请求凭证导致的,如果是凭证错误你会收到401/403这类HTTP状态码,而不是连接拒绝。
这个错误的本质是你的Azure函数发起TCP连接请求时,目标服务直接拒绝了连接,常见原因有:
- 目标IP对应的服务器没有正常运行,或者没有在你请求的443端口上部署监听服务
- 目标服务器的防火墙/网络安全组拦截了你的Azure函数的出站IP,没有放开443端口的入站权限
- 你请求的端口填写错误,比如目标服务实际监听的是8080端口,你误写为443
- 如果目标服务也部署在Azure上,需要检查目标服务的NSG规则、VPC配置是否允许来自你的Azure函数所在网络的访问请求
内容的提问来源于stack exchange,提问作者Stark
相关产品推荐
相关产品推荐

