野生的Python装饰器案例

翻译:https://www.bitecode.dev/p/xmas-decorations-part-3

装饰器案例

下面介绍了三种装饰器的真实应用场景。

  1. 1. 拦截调用:在函数运行前拦截,进行检查

  2. 2. 函数注册存储函数的引用以便在后面使用。通常用于事件系统、模式匹配、路由等。

  3. 3. 增强函数功能:增强函数的功能。比如显示函数执行时间。

拦截调用

在函数执行前对函数进行检查。标准库的functools.cache实现了函数缓存的功能。在函数第一次执行时,会正常执行。在函数使用相同参数执行第二次时,检测到函数已经执行过,会跳过执行函数,直接返回缓存值。

from functools import cache
@cache
def expensive_function(a, b):
    print("The expensive function runs")
    return a + b


expensive_function(12)  # 第一次运行
expensive_function(12)  # 相同参数第二次,函数不会执行

运行结果,函数只执行了一次:

The expensive function runs

这种思路在许多流行的框架经常出现:

  1. 1. Django使用装饰器验证用户是否通过身份验证。如果通过验证,则返回正常的网页;否则返回登陆页面。

from django.contrib.auth.decorators import login_required
@login_required
def my_view(request): ...

# https://docs.djangoproject.com/en/5.0/topics/auth/default/#the-login-required-decorator
  1. 2. 验证库 pydantic 提供了一个装饰器来检查函数输入。如果输入与类型提示匹配,则运行原始函数。如果没有,pydantics 会引发错误。

  2. 3. call-throttle 是一个用于速率限制代码的库,它允许您将函数限制为每秒调用的次数。如果达到限制,则原始函数根本不会运行。下面是一个简化的实现:

import time
import functools

def basic_throttle(calls_per_second):
    def decorator(func):

        last_called = 0.0
        count = 0

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            nonlocal last_called, count
            current_time = time.time()

            # Reset counter if new second
            if current_time - last_called >= 1:
                last_called = current_time
                count = 0

            # Enforce the limit
            if count < calls_per_second:
                count += 1
                return func(*args, **kwargs)

            return None

        return wrapper
    return decorator
>>> @basic_throttle(5)
... def send_alert():
...     print(f"Alert !")
...
... for i in range(10):
...     send_alert()
...     time.sleep(0.1)
...
Alert !
Alert !
Alert !
Alert !
Alert !

注册函数

存储函数的引用以便在后面使用。通常用于事件系统、模式匹配、路由等。

  1. 1. doit-api 提供 decorar 来注册 doit 任务。如果从与其名称匹配的命令行运行任务,则稍后会调用修饰函数。

  2. 2. Flask 的路由将 URL 路径与终结点相关联。当用户浏览 URL 时,关联的函数会生成网页。

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'
  1. 3. pytest 允许您使用装饰器定义夹具(fixtures)。如果编写带有夹具函数名称的测试参数,则会自动调用该参数,并将结果注入测试中。

import pytest


class Fruit:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return self.name == other.name


@pytest.fixture
def my_fruit():
    return Fruit("apple")


@pytest.fixture
def fruit_basket(my_fruit):
    return [Fruit("banana"), my_fruit]


def test_my_fruit_in_basket(my_fruit, fruit_basket):
    assert my_fruit in fruit_basket

增强函数功能

我们希望让函数更强大一些,比如显示函数执行时间。

  1. 1. tenacity 的装饰器将函数设置为在失败时重试。您可以指定异常、失败次数、重试前的延迟以及各种策略。对于自然会出现暂时性错误(如网络调用)的操作很有用。

  2. 2. Fabric 使用装饰器来配置部署,例如告诉函数应在哪个主机上运行。然后,代码将在远处的计算机上运行,而不是在您的计算机上运行。

@hosts('user1@host1''host2''user2@host3')
def my_func():
    pass
  1. 3. Huey 提供装饰器来注册任务。如果尝试调用该函数,则它不会运行,而是会放入任务队列中,这些任务在不同的进程中一个接一个地异步执行。


原文始发于微信公众号(一只大鸽子):野生的Python装饰器案例

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/237809.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!