使用gql客户端在GraphQL Mutation中声明变量遇错求助
问题解决:GraphQL Mutation变量未定义/类型错误
你的核心问题是客户端的Mutation操作没有声明变量的类型定义,导致服务端无法识别带$前缀的变量;去掉$后,服务端会把w当成字符串值,和Float类型不匹配,因此报错。
修正步骤
1. 在Mutation操作中声明变量类型
必须在mutation createMutation后明确添加变量的类型声明,格式为($变量名: 类型)(必填项可加!标记)。修正后的查询如下:
query = gql( """ mutation createMutation($w: Float, $dt: DateTime, $exchangeId: Int, $strategyId: Int, $marketId: Int) { createTarget(targetData: {weight: $w, dt: $dt, exchangeId: $exchangeId, strategyId: $strategyId, marketId:$marketId }) { target { dt, weight, market, exchange, strategy } } } """ )
2. 确认变量类型与服务端匹配
检查params中每个值的类型是否和声明的变量类型一致:
w必须是浮点型数值dt需为符合GraphQL DateTime格式的字符串或datetime对象(gql客户端通常会自动处理datetime对象)exchangeId、strategyId、marketId必须是整数类型
服务端代码无需修改
你的Graphene服务端代码逻辑正确:TargetInput中的下划线命名会自动映射为客户端的驼峰命名(比如strategy_id对应strategyId),Mutation的实现没有问题。
完整修正后的客户端代码
transport = AIOHTTPTransport(url="http://x.x.x.x:8000/graphql") client = Client(transport=transport, fetch_schema_from_transport=True) query = gql( """ mutation createMutation($w: Float, $dt: DateTime, $exchangeId: Int, $strategyId: Int, $marketId: Int) { createTarget(targetData: {weight: $w, dt: $dt, exchangeId: $exchangeId, strategyId: $strategyId, marketId:$marketId }) { target { dt, weight, market, exchange, strategy } } } """ ) params = {"w": self.weight, "dt": self.dt, "exchangeId": self.exchange.pk, "strategyId": self.strategy.pk, "marketId": self.market.pk } result = client.execute(query, variable_values=params)
内容的提问来源于stack exchange,提问作者Florent
相关产品推荐
相关产品推荐

