超时机制
一般应用于处理阻塞问题
场景:
- 复杂度较大的计算(解析)某个数值、加解密计算等
- 请求中遇到阻塞,避免长时间等待
- 网络波动,避免长时间请求,浪费时间
1. requests 请求超时机制
reqeusts 依赖中的Post请求中自带 timeout 参数,可以直接设置
1 2 3 4 | response = requests.post(url, data = request_body, headers = headers, timeout = timeout) |
2. 其他函数时间超时机制
自定义一个超时函数 timeout()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import signal from functools import wraps import errno import os class TimeoutError(Exception): pass def timeout(seconds = 10 , error_message = os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper( * args, * * kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try : result = func( * args, * * kwargs) finally : signal.alarm( 0 ) return result return wraps(func)(wrapper) return decorator @timeout ( 5 ) def long_running_function(): # 这里是可能会长时间运行的代码 # 例如,可以使用 time.sleep 来模拟长时间运行的操作 import time time.sleep( 10 ) try : long_running_function() except TimeoutError as e: print ( "Function call timed out" ) |
注:
timeout() 函数的编写借鉴 ChatGPT4.0
到此这篇关于Python 超时请求或计算的处理的文章就介绍到这了,更多相关Python 超时请求内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!