python 处理超时请求

本文介绍了两种处理超时请求的方法,一种是使用eventlet库指定超时时间,如果请求超时则直接跳过并继续执行;另一种是使用timeout-decorator库,在函数上设置超时装饰器,超时后可选择抛出异常或使用多进程策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

处理超时请求

  1. 在某些情况下,我们调用第三方接口时,响应时间无法估计,但我们还要考虑到下面代码的执行,此时就可以使用该方法,指定超时时间,如果超时未处理成功,则直接跳过他,继续向下执行。当然也可以使用异步任务进行处理。

方式一:

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值