首次使用Twilio可编程语音,如何解析SpeechResult等请求参数?
如何在Starlette中获取Twilio Gather的SpeechResult参数
问题根源:Twilio向你的
/process_response端点发送的是**application/x-www-form-urlencoded格式的POST请求**,参数存储在请求体中,而非路径参数或URL查询参数,因此你之前用path_params、query_params无法获取到数据。解决方法:在Starlette中需通过异步方法
await request.form()获取表单编码的POST数据,示例代码如下:
@router.post("/process_response", tags=[TWILIO], summary="Process caller response") async def process_response(request: Request): # 获取Twilio发送的表单数据 form_data = await request.form() # 提取语音识别结果及相关参数 speech_result = form_data.get("SpeechResult") confidence = form_data.get("Confidence") print(f"语音输入内容: {speech_result}") print(f"识别置信度: {confidence}") # 后续业务逻辑处理... return {"status": "success", "speech_result": speech_result}
- 注意事项:
- 必须使用
await调用request.form(),因为这是异步方法 - 用
form_data.get(key)而非直接索引,可避免参数缺失时抛出KeyError - 若需验证请求是否来自Twilio,可结合
twilio-python库的RequestValidator做合法性校验
- 必须使用
内容的提问来源于stack exchange,提问作者jprusakova
相关产品推荐
相关产品推荐

