野生的Python装饰器案例

简介: 野生的Python装饰器案例

装饰器案例

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

  1. 拦截调用:在函数运行前拦截,进行检查
  2. 函数注册存储函数的引用以便在后面使用。通常用于事件系统、模式匹配、路由等。
  3. 增强函数功能:增强函数的功能。比如显示函数执行时间。

拦截调用

在函数执行前对函数进行检查。

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

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


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

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

The expensive function runs

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

  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. 验证库 pydantic 提供了一个装饰器来检查函数输入。如果输入与类型提示匹配,则运行原始函数。如果没有,pydantics 会引发错误。
  1. 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. doit-api 提供 decorar 来注册 doit 任务。如果从与其名称匹配的命令行运行任务,则稍后会调用修饰函数。
  1. Flask 的路由将 URL 路径与终结点相关联。当用户浏览 URL 时,关联的函数会生成网页。
@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'
  1. 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. tenacity 的装饰器将函数设置为在失败时重试。您可以指定异常、失败次数、重试前的延迟以及各种策略。对于自然会出现暂时性错误(如网络调用)的操作很有用。
  1. Fabric 使用装饰器来配置部署,例如告诉函数应在哪个主机上运行。然后,代码将在远处的计算机上运行,而不是在您的计算机上运行。
@hosts('user1@host1', 'host2', 'user2@host3')
def my_func():
    pass

相关文章
|
9月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
392 100
|
10月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
392 101
|
10月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
316 99
|
9月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
521 88
|
10月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
558 98
|
10月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
10月前
|
存储 缓存 测试技术
理解Python装饰器:简化代码的强大工具
理解Python装饰器:简化代码的强大工具
|
9月前
|
数据采集 监控 数据库
Python异步编程实战:爬虫案例
🌟 蒋星熠Jaxonic,代码为舟的星际旅人。从回调地狱到async/await协程天堂,亲历Python异步编程演进。分享高性能爬虫、数据库异步操作、限流监控等实战经验,助你驾驭并发,在二进制星河中谱写极客诗篇。
Python异步编程实战:爬虫案例
|
10月前
|
缓存 测试技术 Python
解锁Python超能力:深入理解装饰器
解锁Python超能力:深入理解装饰器
232 2
|
10月前
|
设计模式 缓存 运维
Python装饰器实战场景解析:从原理到应用的10个经典案例
Python装饰器是函数式编程的精华,通过10个实战场景,从日志记录、权限验证到插件系统,全面解析其应用。掌握装饰器,让代码更优雅、灵活,提升开发效率。
627 0

推荐镜像

更多