如何在中间件的WSGIRequest中获取Graphene的Mutation/Query?
在Django中间件中识别Graphene的Query或Mutation
要在CustomMiddleware的__call__方法里通过WSGIRequest确定当前调用的Graphene Query/Mutation,核心是解析GraphQL请求体里的查询内容,具体实现如下:
实现思路
GraphQL请求通常是POST请求,请求体包含query(查询字符串)和可选的operationName(多操作场景下指定目标操作)。我们需要解析查询字符串的AST(抽象语法树),从中提取操作类型(Query/Mutation)和名称。
代码实现
确保已安装graphene-django,然后修改你的中间件:
from graphene import parse from graphql.language.ast import OperationDefinition import json class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): data = self.doTheMagic(request) if data: request.data = data response = self.get_response(request) return response def doTheMagic(self, request): # 只处理GraphQL请求(假设你的GraphQL端点路径是/graphql) if request.path != "/graphql" or request.method != "POST": return None try: # 解析请求体为JSON格式 request_body = json.loads(request.body.decode("utf-8")) query_str = request_body.get("query") operation_name = request_body.get("operationName") if not query_str: return None # 把GraphQL查询字符串解析为AST document_ast = parse(query_str) # 筛选出所有操作定义节点(Query/Mutation都属于这类) operations = [ node for node in document_ast.definitions if isinstance(node, OperationDefinition) ] target_op = None if operation_name: # 根据指定的operationName匹配对应的操作 target_op = next((op for op in operations if op.name.value == operation_name), None) else: # 未指定operationName时,取第一个操作 target_op = operations[0] if operations else None if not target_op: return None # 返回提取到的操作信息 return { "operation_type": target_op.operation.value, # 结果为"query"或"mutation" "operation_name": target_op.name.value if target_op.name else None } except Exception: # 处理解析失败场景(如请求体非合法JSON、查询语法错误等) return None
关键说明
- 先过滤非GraphQL请求:通过路径和请求方法判断,避免对其他请求做无效处理。
- 异常处理:包裹解析逻辑防止请求格式错误导致中间件崩溃。
- AST解析:借助graphene的
parse工具解析查询字符串,筛选出操作定义节点,精准识别Query/Mutation类型和名称。
内容的提问来源于stack exchange,提问作者ponez
相关产品推荐
相关产品推荐

