Streamlit提交GraphQL mutation请求无响应无报错问题求助
问题原因
你的代码有3个核心问题导致写入失败:
- 模板字符串未做变量替换:你写在mutation里的
${name}、${age}这类占位符Python不会自动替换为表单拿到的用户输入值,实际发出去的请求里全是${name}这类字面量字符串,完全不符合接口字段要求。 - 未读取接口响应:GraphQL接口哪怕执行出错默认也会返回200 HTTP状态码,错误信息放在响应体的
errors字段中,你发完请求直接丢弃响应对象,自然看不到任何报错。 - 字段类型不匹配:你表单里拿到的
drinking、smoking等值都是'true'/'false'格式的字符串,GraphQL的布尔类型字段需要接收真实布尔值,传字符串会被判定为类型错误。另外你表单收集的smoking、history_of_ibd字段没有写入mutation参数,如果接口要求必填也会触发报错。
修复方案
不要用字符串拼接的方式写GraphQL请求,改用官方推荐的变量传参方式,同时增加响应解析逻辑,修复后代码如下:
import streamlit as st import requests url = "https://graphql-newone.herokuapp.com/" # 标准GraphQL mutation 带变量定义 query = """ mutation CreateUser($input: CreateUsersInput!) { createUsers(input: $input) { users { user_name } } } """ st.title("Sanjeevan") st.sidebar.markdown("# Main page 🎈") form = st.form(key="my_form") name = form.text_input(label="Enter Name") age = form.number_input(label="Enter Age", min_value=0, step=1) sex = form.selectbox('Sex', ('Male', 'Female')) weight = form.number_input(label="Enter Weight", min_value=0.0, step=0.1) nationality = form.selectbox('Nationality', ('Indian', 'Non-Indian')) birth_type = form.selectbox('Birth Type', ('Normal', 'Cesarean')) smoking = form.selectbox('Smoking', ('true', 'false')) drinking = form.selectbox('Drinking', ('true', 'false')) history_of_ibd = form.selectbox('History', ('true', 'false')) submitted = form.form_submit_button(label="Submit") if submitted: # 组装请求参数,做对应类型转换 variables = { "input": { "user_name": name, "age": int(age), "sex": sex, "weight": float(weight), "nationality": nationality, "birth_type": birth_type, "drinking": drinking == "true" # 若接口要求传smoking、history_of_ibd字段,放开下方注释即可 # "smoking": smoking == "true", # "history_of_ibd": history_of_ibd == "true" } } # 发起请求,同时传递query和variables resp = requests.post(url, json={"query": query, "variables": variables}) resp_data = resp.json() # 页面打印响应方便排查问题 st.write("接口返回内容:", resp_data) # 错误处理 if "errors" in resp_data: st.error(f"提交失败:{resp_data['errors']}") else: st.success(f"用户 {name} 的信息提交成功")
额外排查提示
- 运行后页面会直接打印接口的完整返回,如果还有报错,看
errors字段的描述就能直接定位问题,常见的有字段名拼写错误、缺少必填字段、类型不匹配、接口权限校验失败。 - 不要用f-string、字符串替换的方式拼接GraphQL语句,一旦用户输入的内容包含双引号、特殊符号就会直接触发query语法错误,变量传参是官方推荐的安全写法。
- 提交前可以先确认你的GraphQL schema中
createUsers接口的入参字段和你传的完全一致,注意字段名的大小写、下划线拼写。
内容的提问来源于stack exchange,提问作者daylightisminetocommand
相关产品推荐
相关产品推荐

