简体   繁体   English

将参数传递给 Python 中的装饰器类

[英]Pass parameters to a decorator Class in Python

I'm trying to write a decorator for a Db Model, to makes this Model serializable我正在尝试为 Db 模型编写一个装饰器,以使该模型可序列化

def Schema(cls):
    class Schema(marshmallow.ModelSchema):
        class Meta:
            model = cls

    cls.Schema = Schema
    return cls


@Schema
class SerialInterface(sql.Model, InheritanceModel):
    id = sql.Column(types.Integer, primary_key=True)
    transmission_rate = sql.Column(types.Integer)
    type = sql.Column(sql.String(50))

    mad_id = sql.Column(types.Integer, sql.ForeignKey('mad.id'))

    serial_protocol = sql.relationship(SerialProtocol, uselist=False, cascade="all, delete-orphan")

But I want to pass the nested Objects in this Decorator, Like this:但是我想在这个装饰器中传递嵌套的对象,像这样:

@Schema(nested=['serial_protocol'])
class SerialInterface(sql.Model, InheritanceModel):

You can do something like:您可以执行以下操作:

def Schema(*args, **kwargs):
    def wrapped(cls):
        class Schema(marshmallow.ModelSchema):
            class Meta:
                model = cls

        cls.Schema = Schema
        return cls
    return wrapped

And then doing @Schema(nested=['serial_protocol']) will work.然后做@Schema(nested=['serial_protocol'])会起作用。

How this works is, you create a function that takes arguments and returns a decorator.这是如何工作的,你创建一个函数,它接受参数并返回一个装饰器。 From there the decorator works like a normal Python decorator.从那里装饰器就像普通的 Python 装饰器一样工作。

@Schema(nested=['serial_protocol'])
class SerialInterface:
    ...

The decorator translates to:装饰器翻译为:

SerialInterface = Schema(nested=['serial_protocol'])(SerialInterface)

Extra tip, Use functools.wraps module :) See why额外提示,使用functools.wraps模块 :) 看看原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM