Skip to main content

A funcguard for Python.

Project description

FuncGuard

FuncGuard是一个Python库,提供了函数执行超时控制和重试机制的实用工具。

功能特点

  • 函数执行超时控制
  • 函数执行失败自动重试
  • HTTP请求封装(支持自动重试)
  • 格式化打印工具(分隔线和块打印)

安装/升级

pip install --upgrade funcguard

使用方法

超时控制

使用timeout_handler函数可以控制函数的执行时间,防止函数运行时间过长:

from funcguard.core import timeout_handler

def long_running_function():
    # 模拟一个耗时操作
    import time
    time.sleep(10)
    return "操作完成"

try:
    # 设置超时时间为5秒
    result = timeout_handler(long_running_function, execution_timeout=5)
    print(result)
except TimeoutError as e:
    print(f"捕获到超时错误: {e}")

重试机制

使用retry_function函数可以在函数执行失败时自动重试:

from funcguard.core import retry_function

def unstable_function():
    # 模拟一个可能失败的操作
    import random
    if random.random() < 0.7:  # 70%的概率失败
        raise Exception("随机错误")
    return "操作成功"

try:
    # 最多重试3次,每次执行超时时间为10秒
    result = retry_function(unstable_function, max_retries=3, execute_timeout=10, task_name="测试任务")
    print(result)
except Exception as e:
    print(f"重试后仍然失败: {e}")

HTTP请求

使用send_request函数发送HTTP请求,支持自动重试:

from funcguard.tools import send_request

# 不使用重试
response = send_request(
    method="GET",
    url="https://api.example.com/data",
    headers={"Content-Type": "application/json"},
    timeout=30
)
print(response)

# 使用重试
response = send_request(
    method="POST",
    url="https://api.example.com/data",
    headers={"Content-Type": "application/json"},
    data={"key": "value"},
    timeout=30,
    auto_retry={
        "task_name": "API请求",
        "max_retries": 3,
        "execute_timeout": 60
    }
)
print(response)

格式化打印

使用print_lineprint_block函数进行格式化打印,便于查看和调试:

from funcguard.printer import print_line, print_block

# 打印分隔线
print_line()  # 默认使用40个'-'字符
print_line("*", 30)  # 使用30个'*'字符

# 打印块内容
print_block("用户信息", {"name": "张三", "age": 25})

# 自定义分隔符
print_block("配置信息", {"debug": True, "port": 8080}, "=", 50)

# 打印复杂内容
result = {
    "status": "success",
    "data": [1, 2, 3, 4, 5],
    "message": "操作完成"
}
print_block("API响应", result)

API文档

funcguard.core

timeout_handler(func, args=(), kwargs=None, execution_timeout=90)

  • 参数:
    • func: 需要执行的目标函数
    • args: 目标函数的位置参数,默认为空元组
    • kwargs: 目标函数的关键字参数,默认为None
    • execution_timeout: 函数执行的超时时间,单位为秒,默认为90秒
  • 返回值: 目标函数的返回值
  • 异常: TimeoutError - 当函数执行超过指定时间时抛出

retry_function(func, max_retries=5, execute_timeout=90, task_name="", *args, **kwargs)

  • 参数:
    • func: 需要重试的函数
    • max_retries: 最大重试次数,默认为5
    • execute_timeout: 执行超时时间,默认为90秒
    • task_name: 任务名称,用于打印日志
    • args: func的位置参数
    • kwargs: func的关键字参数
  • 返回值: func的返回值
  • 异常: 当重试次数用尽后仍然失败时,抛出最后一次的异常

funcguard.tools

send_request(method, url, headers, data=None, return_type="json", timeout=60, auto_retry=None)

  • 参数:
    • method: HTTP方法(GET, POST等)
    • url: 请求URL
    • headers: 请求头
    • data: 请求数据,默认为None
    • return_type: 返回类型,可选"json"、"response"或"text",默认为"json"
    • timeout: 请求超时时间,单位为秒,默认为60
    • auto_retry: 自动重试配置,格式为{"task_name": "", "max_retries": 5, "execute_timeout": 90},默认为None
  • 返回值: 根据return_type参数返回不同格式的响应数据
  • 异常: 当请求失败且重试次数用尽后,抛出相应的异常

funcguard.printer

print_line(separator_char: str = "-", separator_length: int = 40) -> None

  • 参数:
    • separator_char: 分隔符字符,默认为'-'
    • separator_length: 分隔符长度,默认为40
  • 返回值: 无
  • 功能: 打印分隔线,用于分隔不同的打印块

print_block(title: str, content: Any, separator_char: str = "-", separator_length: int = 40) -> None

  • 参数:
    • title: 标题
    • content: 打印的内容
    • separator_char: 分隔符字符,默认为'-'
    • separator_length: 分隔符长度,默认为40
  • 返回值: 无
  • 功能: 使用分隔符打印标题和内容,便于查看

许可证

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

funcguard-0.1.3.tar.gz (9.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

funcguard-0.1.3-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

Details for the file funcguard-0.1.3.tar.gz.

File metadata

  • Download URL: funcguard-0.1.3.tar.gz
  • Upload date:
  • Size: 9.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.18

File hashes

Hashes for funcguard-0.1.3.tar.gz
Algorithm Hash digest
SHA256 74e0832d2807f9bd53961539a206d8696d9e1747123560f44143802c0164eed9
MD5 b1714651799c69bddb1ef405656aaf33
BLAKE2b-256 eb319baaeb286dcdea3bcb2fd726b48e2f7b973d0342a2b2dc4823ae5c8f96cb

See more details on using hashes here.

File details

Details for the file funcguard-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: funcguard-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 11.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.18

File hashes

Hashes for funcguard-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 f8092554c2370b99a488c940a21a7ed58bb2e5b167dcea75c9f2edb1567d04f6
MD5 6d4dbeec7c8d819d06a45e9b32507c3d
BLAKE2b-256 c5327dbfc467de74d78bd87ef9bfba409b5d684d9fa71878e891d24790be6ed8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page