You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

graphene-python中如何替换占位符以全局禁用Introspection?

在graphene-python中全局禁用Introspection的正确方式

官方文档给出的示例是针对单个查询的验证演示,所以用了THE QUERY占位符。要对所有查询禁用Introspection,你需要在处理每个用户传入的查询时,统一应用DisableIntrospection验证规则,具体实现如下:

1. 基础执行流程中集成验证

如果你手动处理查询执行逻辑,可以封装一个通用执行函数,对每个传入的查询都做验证:

from graphene import Schema
from graphql import validate, parse, DisableIntrospection
from graphql.error import GraphQLError

def execute_with_introspection_disabled(schema: Schema, query: str, **kwargs):
    # 解析用户传入的查询文档
    document_ast = parse(query)
    # 应用禁用Introspection的验证规则
    validation_errors = validate(
        schema=schema.graphql_schema,
        document_ast=document_ast,
        rules=(DisableIntrospection,)
    )
    # 如果有验证错误,直接抛出
    if validation_errors:
        raise GraphQLError(validation_errors[0].message)
    # 执行合法查询
    return schema.execute(query, **kwargs)

2. Django + Graphene场景下的全局配置

如果使用Django集成Graphene,可通过自定义GraphQLView来全局生效:

from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
from graphql import validate, parse, DisableIntrospection

class NoIntrospectionGraphQLView(GraphQLView):
    def execute_graphql_request(self, request, data, query, variables, operation_name, show_graphiql=False):
        # 获取并解析用户传入的查询
        raw_query = data.get('query')
        if raw_query:
            document_ast = parse(raw_query)
            # 执行Introspection禁用验证
            validation_errors = validate(
                schema=self.schema.graphql_schema,
                document_ast=document_ast,
                rules=(DisableIntrospection,)
            )
            # 若验证不通过,直接返回错误
            if validation_errors:
                return self.json_encode(request, {
                    'errors': [err.formatted for err in validation_errors]
                })
        # 调用父类方法执行合法查询
        return super().execute_graphql_request(request, data, query, variables, operation_name, show_graphiql)

# 在urls.py中替换原GraphQLView
urlpatterns = [
    # ... 其他路由
    path("graphql/", csrf_exempt(NoIntrospectionGraphQLView.as_view(graphiql=False))),
]

关键说明

官方文档的示例是为了展示验证规则的使用方式,因此用固定查询字符串作为演示。实际全局禁用时,必须动态解析每个用户传入的查询文档,再应用验证规则,才能拦截所有Introspection请求。

内容的提问来源于stack exchange,提问作者user2205880

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:40:59