Python 超时请求或计算的处理方案
更新时间:2024年06月04日 10:42:18 作者:Buffedon
这篇文章主要介绍了Python 超时请求或计算的处理方案,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
超时机制
一般应用于处理阻塞问题
场景:
- 复杂度较大的计算(解析)某个数值、加解密计算等
- 请求中遇到阻塞,避免长时间等待
- 网络波动,避免长时间请求,浪费时间
1. requests 请求超时机制
reqeusts 依赖中的Post请求中自带 timeout 参数,可以直接设置
response = requests.post(url, data=request_body, headers=headers, timeout=timeout)
2. 其他函数时间超时机制
自定义一个超时函数 timeout()
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 超时请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python常见错误:IndexError: list index out of range解决
最近在写一个爬虫程序,但是却出现了错误提示IndexError: list index out of range,所以下面这篇文章主要给大家介绍了关于Python常见错误:IndexError: list index out of range的解决方法,需要的朋友可以参考下2023-01-01
django authentication 登录注册的实现示例
本文主要介绍了使用Django内置的authentication功能实现用户注册和登录功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-11-11


最新评论