graphene-django v2.0实现查询深度校验时backend参数报错如何解决
graphene-django 2.0查询深度校验实现方案
错误原因
你遇到的参数错误是因为graphene-django 2.0版本的FileUploadGraphQLView类没有内置backend属性,as_view方法会校验传入的参数必须是类已有的属性,所以直接传入backend参数会报错。你参考的自定义后端方案默认适配更高版本的graphene-django,需要调整逻辑适配2.0版本。
解决方案
方案一:通过Graphene中间件实现(兼容性最优,推荐)
直接通过原生支持的中间件实现深度校验,不需要修改视图类:
# 深度计算函数 def measure_depth(selection_set, level=1): max_depth = level for field in selection_set.selections: if field.selection_set: new_depth = measure_depth(field.selection_set, level=level + 1) if new_depth > max_depth: max_depth = new_depth return max_depth # 自定义校验中间件 class QueryDepthCheckMiddleware: def resolve(self, next, root, info, **kwargs): # 仅首次进入时校验,避免重复计算 if not hasattr(info.context, "_depth_checked"): ast = info.context._graphql_query_ast for definition in ast.definitions: # 仅校验查询操作 if getattr(definition, "operation", None) == "query": depth = measure_depth(definition.selection_set) if depth > 3: # 可自定义最大允许深度 raise Exception("查询复杂度超出限制") info.context._depth_checked = True return next(root, info, **kwargs)
路由配置修改为:
url(r'^api', csrf_exempt(FileUploadGraphQLView.as_view( schema=schema, # 将自定义中间件加入中间件列表 middleware=(middleware + (QueryDepthCheckMiddleware,)) ))),
方案二:重写视图类支持backend参数
如果你要沿用原有自定义后端的逻辑,只需给FileUploadGraphQLView新增backend属性即可:
from graphene_django.views import FileUploadGraphQLView class BackendSupportGraphQLView(FileUploadGraphQLView): # 新增backend属性,允许as_view传入该参数 backend = None def execute_graphql_request(self, *args, **kwargs): if self.backend: kwargs["backend"] = self.backend return super().execute_graphql_request(*args, **kwargs)
路由配置修改为:
url(r'^api', csrf_exempt(BackendSupportGraphQLView.as_view( schema=schema, middleware=middleware, backend=DepthAnalysisBackend() ))),
内容的提问来源于stack exchange,提问作者domanskyi
相关产品推荐
相关产品推荐

