每个查询的 Django GraphQL 深度限制验证

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

我正在使用 django graphql 并且有很多查询。我有一些公开查询,任何人都可以对其进行深入查询。

我想限制每个查询的深度。在文档中找到了这个https://docs.graphene-python.org/en/latest/execution/queryvalidation/但没有找到任何正确的使用方法。

另外,有没有办法将动态字段传递给石墨烯字段,如下所示:

jobs = graphene.List(JobGQLType, fields=['title', 'location'])

任何帮助将不胜感激。

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

根据这个 Github 问题,看起来没有办法修改 graphql-python 在所有查询上运行的默认验证规则。相反,您必须在执行查询时运行的代码中的某个位置添加您自己对

validate
方法的调用。

这是向石墨烯模式

execute
方法添加深度限制验证检查的示例。也许有更有效的方法,但至少我可以确认这是有效的。

import graphene
from graphene.validation import depth_limit_validator
from graphql import ExecutionResult, GraphQLError, parse, validate

GRAPHENE_DEPTH_LIMIT = 9

class DepthLimitValidatingSchema(graphene.Schema):
    def execute(self, *args, **kwargs):
        # If we're not executing a query from a GraphQL View, don't validate the depth
        if "source" not in kwargs:
            return super().execute(*args, **kwargs)

        try:
            document = parse(kwargs["source"])
        except GraphQLError as error:
            return ExecutionResult(data=None, errors=[error])

        validation_errors = validate(
            self.graphql_schema,
            document,
            rules=(depth_limit_validator(max_depth=GRAPHENE_DEPTH_LIMIT),),
        )
        if validation_errors:
            return ExecutionResult(data=None, errors=validation_errors)

        return super().execute(*args, **kwargs)
© www.soinside.com 2019 - 2024. All rights reserved.