石墨烯认证或其他检查所有突变

问题描述 投票:0回答:1

有什么方法可以对所有突变应用装饰器/身份验证或某种其他检查吗?

例如:

class Mutations(graphene.ObjectType):
    some_mutation = SomeMutation.Field()
    some_mutation2 = SomeMutation2.Field()
    some_mutation3 = SomeMutation3.Field()

graphql_schema = graphene.Schema(query=Queries, mutation=Mutations)

我知道我可以在每个突变中应用“mutate”或“mutate_and_get_payload”装饰器,如下所示:

class SomeMutation(relay.ClientIDMutation):
    class Input:
        some_uuid = graphene.UUID()

    success = graphene.Boolean()

    @classmethod
    @login_required
    def mutate_and_get_payload(cls, root, info, *inputs):
        ...

是否有可能以某种方式将其一次性应用到所有事物上? 例如在类突变级别。

将其添加到每个突变中效果很好,但将其应用于 100 个突变就相当累人了。

python graphene-python graphene-django
1个回答
0
投票

这是实现此目的的一种可能方法,可与 Graphene v2.1.9 配合使用。

您可以重新定义

Mutation.Field
类方法,具体是解析器传递部分,如下所示:

from graphene import Mutation, Field


class MutationWithAuth(Mutation):
    class Meta:
        abstract = True

    # App-wide decorators for all mutations
    decorators = [login_required]  # <-- list your desired decorators here

    @classmethod
    def Field(cls, name=None, description=None, deprecation_reason=None, required=False):
        resolver = cls._meta.resolver
        for decorator in cls.decorators:
            resolver = decorator(cls._meta.resolver)  # <-- here we apply them

        return Field(
            cls._meta.output,
            args=cls._meta.arguments,
            resolver=resolver,
            name=name,
            description=description or cls._meta.description,
            deprecation_reason=deprecation_reason,
            required=required,
        )

然后你只需像往常一样用这个基类

MutationWithAuth
编写你的突变:

class SomeMutation(MutationWithAuth):
    ...

    @extra_custom_decorator
    def mutate(self, info, input):
        ...

您还可以在特定突变中覆盖这些“全局”装饰器,例如:

class SomeOtherMutation(MutationWithAuth):
    decorators = []  # <-- like this

我不确定这是否是最优雅的,但它比在每条

def mutate
行的顶部粘贴一个装饰器要好。

即使您仍然希望选择偶尔向突变方法添加一些额外的装饰器,它也可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.