处理超时请求
- 在某些情况下,我们调用第三方接口时,响应时间无法估计,但我们还要考虑到下面代码的执行,此时就可以使用该方法,指定超时时间,如果超时未处理成功,则直接跳过他,继续向下执行。当然也可以使用异步任务进行处理。
方式一:
import time
import eventlet
eventlet.monkey_patch()
try:
with eventlet.Timeout(2):
# 模拟耗时操作,如果等待时间超过3秒,则直接抛出异常
time.sleep(3)
print(11111111)
except eventlet.timeout.Timeout:
# 对异常进行捕获
print('我被捕获啦')
print('finished')
# # 超时后不做任何处理,直接往下进行
# with eventlet.Timeout(2, False):
# # 模拟耗时操作,如果等待时间超过3秒,则直接抛出异常
# time.sleep(3)
# print(11111111)
#
# print('finished')
方式二:(该方法在win10下无法正常使用,win10下signal模块缺少SIGALRM信号,仅能使用SIGABRT、SIGFPE、SIGILL、SIGINT、SIGSEGV、SIGTERM等模块)
pip install timeout-decorator
import time
import timeout_decorator
@timeout_decorator.timeout(5)
def my_test():
print("Start")
for i in range(1, 10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
my_test()
1 second have passed
2 second have passed
3 second have passed
4 second have passed
Traceback (most recent call last):
File "test.py", line 12, in <module>
my_test()
File "/usr/local/lib/python3.8/site-packages/timeout_decorator/timeout_decorator.py", line 81, in new_function
return function(*args, **kwargs)
File "test.py", line 9, in my_test
time.sleep(1)
File "/usr/local/lib/python3.8/site-packages/timeout_decorator/timeout_decorator.py", line 72, in handler
_raise_exception(timeout_exception, exception_message)
File "/usr/local/lib/python3.8/site-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception
raise exception()
timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'
- 可以通过
try except timeout_decorator.timeout_decorator.TimeoutError
进行异常捕获
指定在超时时引发的备用异常:
import time
import timeout_decorator
@timeout_decorator.timeout(5, timeout_exception=StopIteration)
def mytest():
print("Start")
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
mytest()
1 second have passed
2 second have passed
3 second have passed
4 second have passed
Traceback (most recent call last):
File "test.py", line 12, in <module>
my_test()
File "/usr/local/lib/python3.8/site-packages/timeout_decorator/timeout_decorator.py", line 81, in new_function
return function(*args, **kwargs)
File "test.py", line 9, in my_test
time.sleep(1)
File "/usr/local/lib/python3.8/site-packages/timeout_decorator/timeout_decorator.py", line 72, in handler
_raise_exception(timeout_exception, exception_message)
File "/usr/local/lib/python3.8/site-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception
raise exception()
StopIteration
多线程
默认情况下,timeout decorator
使用信号来限制执行时间 给定函数的。如果您的功能是 不在主线程中执行(例如,如果它是 Web应用程序)。有另一种超时策略 案例-使用多处理。使用它,只要通过 use_signals=False
到超时装饰函数:
import time
import timeout_decorator
@timeout_decorator.timeout(5, use_signals=False)
def mytest():
print "Start"
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
mytest()