在python中使用泛型类型来重构代码

时间:2018-06-10 03:39:23

标签: refactoring graphene-python

我一直在尝试多种方法来重构以下代码,因为这些类在我的应用中重复出现:

class CreateRecord(Mutation):
    record = Field(lambda: Unit)

    class Arguments:
        input = CreateInput(required=True)

    def mutate(self, info, input):
        data = input_to_dictionary(input)
        data['createdAt'] = datetime.utcnow()
        # data['createdBy'] = <user>  # TODO: <user> input

        record = UnitModel(**data)
        db_session.add(record)
        db_session.commit()

        return CreateRecord(record=record)


class UpdateRecord(Mutation):
    record = Field(lambda: Unit)

    class Arguments:
        input = UpdateInput(required=True)

    def mutate(self, info, input):
        data = input_to_dictionary(input)
        data['updatedAt'] = datetime.utcnow()
        # data['updatedBy'] = <user>  # TODO: <user> input

        record = db_session.query(UnitModel).filter_by(id=data['id'])
        record.update(data)
        db_session.commit()

        record = db_session.query(UnitModel).filter_by(id=data['id']).first()

        return UpdateRecord(record=record)


class DeleteRecord(Mutation):
    record = Field(lambda: Unit)

    class Arguments:
        input = DeleteInput(required=True)

    def mutate(self, info, input):
        data = input_to_dictionary(input)
        data['deletedAt'] = datetime.utcnow()
        # data['deletedBy'] = <user>  # TODO: <user> input
        data['isDeleted'] = True

        record = db_session.query(UnitModel).filter_by(id=data['id'])
        record.update(data)
        db_session.commit()

        record = db_session.query(UnitModel).filter_by(id=data['id']).first()

        return DeleteRecord(record=record)

我正在考虑使用泛型类型,但我有点'坚持如何实现它。我已经尝试在

中创建一个大师班
def mutate:

方法我只是检查它是创建,更新还是删除操作,但在我这样做之前我还是想使用泛型类型。

非常感谢任何帮助。 TIA。

1 个答案:

答案 0 :(得分:0)

我已经使用包含以下方法的mixin类为自己解决了这个特殊问题:

from graphene.utils.str_converters import to_snake_case

class MutationResponseMixin(object):
    @classmethod
    def get_operation_type(cls):
        """
        Determine the CRUD type from the mutation class name.
        Uses mutation's class name to determine correct operation.
        ( create / update / delete )
        """
        return to_snake_case(cls.__name__).split('_')[0]

这允许我在mixin中包含一个由create,update和delete方法共享的变异方法,并根据get_operation_type的值采取条件操作。

我还需要一种方法来确定mixin的突变(在你的情况下是UnitModel)的基本记录,所以我的情况我最终明确地将其声明为每个突变类的属性