电脑记事本做复杂网站,90后小姑娘做网站,个人网页模板网站,门户网站和搜索网站的区别超时机制
一般应用于处理阻塞问题
场景#xff1a;
复杂度较大的计算#xff08;解析#xff09;某个数值、加解密计算等请求中遇到阻塞#xff0c;避免长时间等待网络波动#xff0c;避免长时间请求#xff0c;浪费时间
1. requests 请求超时机制
reqeusts 依赖中的…超时机制
一般应用于处理阻塞问题
场景
复杂度较大的计算解析某个数值、加解密计算等请求中遇到阻塞避免长时间等待网络波动避免长时间请求浪费时间
1. requests 请求超时机制
reqeusts 依赖中的Post请求中自带 timeout 参数可以直接设置
response requests.post(url, datarequest_body, headersheaders, timeouttimeout)2. 其他函数时间超时机制
自定义一个超时函数 timeout()
import signal
from functools import wraps
import errno
import osclass TimeoutError(Exception):passdef timeout(seconds10, error_messageos.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 resultreturn wraps(func)(wrapper)return decoratortimeout(5)
def long_running_function():# 这里是可能会长时间运行的代码# 例如可以使用 time.sleep 来模拟长时间运行的操作import timetime.sleep(10)try:long_running_function()
except TimeoutError as e:print(Function call timed out) 注
timeout() 函数的编写借鉴 ChatGPT4.0