脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python 超时请求或计算的处理方案

Python 超时请求或计算的处理方案

2024-06-04 17:02Buffedon Python

这篇文章主要介绍了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 超时请求内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_46684578/article/details/139422667

延伸 · 阅读

精彩推荐