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

Python多行GraphQL字符串格式化出现KeyError问题求助

解决GraphQL多行字符串格式化引发的KeyError问题

问题场景

调用Python函数发起GraphQL请求时,遇到KeyError报错,指向查询字符串中的willObfuscateQuestions (questionIdList部分,核心问题出在多行GraphQL字符串的格式化处理上。

代码示例

def verify_obs():
    question_list = ["baae592c-ec9e-11e3-99de-021505f49f8a","37b5556a-b229-4010-8920-6fc72e5f629e","df3c569b-3bb7-4376-8c33-7f20603a2790","a6bfd272-aad0-4e5d-9a5e-c4a1268ea4ba","e1e9ca6a-4ceb-476e-a87c-7d591486c8da"]

    my_query = '''query {
  willObfuscateQuestions (questionIdList: {0}) {
    questionId
    state
    examId
    endTime
    startTime
  }
}'''.format(question_list)

    ds_response = requests.post(
        url='<end point here>',
        headers={'Content-Type': 'application/json'},
        json={'query': my_query}
    )
    response_list = ds_response.json()['data']['willObfuscateQuestions']
    print(response_list)
    for item in response_list:
        state = item['state']
        if state == 'Obfuscated' and int(ds_response.status_code) == 200:
            print('Question is obfuscated')
            return 0
        else:
            raise Exception('Obfuscation failed with response - ', ds_response.json())

报错信息

Traceback (most recent call last):
  File "/Users/ubhatia/Documents/RFSetup/karma-moderation-pipeline/robot-tests/KarmaModeration/Config/methods.py", line 198, in <module>
    print(verify_obs())
  File "/Users/ubhatia/Documents/RFSetup/karma-moderation-pipeline/robot-tests/KarmaModeration/Config/methods.py", line 49, in verify_obs
    }'''.format(question_list)
KeyError: '\n  willObfuscateQuestions (questionIdList'

原因分析

Python的str.format()方法会把字符串中的{}识别为格式占位符,而你的GraphQL查询里有大量未转义的{和},这些符号被format误判为需要解析的占位符,导致程序找不到对应键,抛出KeyError。

解决方法

1. 转义GraphQL中的大括号

把查询字符串里所有非占位符的{改成{{,}改成}},让format将它们视为普通字符处理:

my_query = '''query {{
  willObfuscateQuestions (questionIdList: {0}) {{
    questionId
    state
    examId
    endTime
    startTime
  }}
}}'''.format(question_list)

2. 稳妥序列化列表参数

直接传入Python列表给format虽然暂时能满足格式要求,但如果列表包含特殊字符可能出问题,建议用json.dumps()序列化列表,确保GraphQL能正确解析:

import json

# ...

my_query = '''query {{
  willObfuscateQuestions (questionIdList: {0}) {{
    questionId
    state
    examId
    endTime
    startTime
  }}
}}'''.format(json.dumps(question_list))

3. 完善错误处理逻辑

原代码先取响应数据再判断状态码,容易在请求失败时崩溃,建议先检查状态码和GraphQL错误信息:

ds_response = requests.post(...)
if ds_response.status_code != 200:
    raise Exception(f'请求失败,状态码:{ds_response.status_code},响应:{ds_response.json()}')
response_data = ds_response.json()
if 'errors' in response_data:
    raise Exception(f'GraphQL执行错误:{response_data["errors"]}')
response_list = response_data['data']['willObfuscateQuestions']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:53:20