Flask运行时报The method is not allowed for the requested URL错误如何解决
Flask接口405报错排查方案
你遇到的The method is not allowed for the requested URL属于HTTP 405状态码,核心原因是请求使用的HTTP方法和路由定义的允许方法不匹配,你的/predict路由明确只允许POST请求,可按以下步骤排查:
- 确认请求方法正确
直接在浏览器地址栏输入接口地址访问时,浏览器默认发送GET请求,必然触发405报错。请使用POST方法请求接口,可通过curl工具测试,示例命令:
也可以使用Postman、Apifox等接口调试工具,选择POST方法后发送请求。curl -X POST -d "solute=测试溶质&solvent=测试溶剂" http://localhost:3000/predict - 确认请求路径拼写正确
检查请求的路径是否完全匹配/predict,大小写、前后缀错误(比如请求/Predict、/predict/、/prediction)都会导致路由匹配失败,返回405错误。 - 确认路由定义无冲突
检查代码中是否存在多个/predict路由定义,如果之前的同名路由没有配置methods=["POST"],默认仅允许GET请求,会覆盖后续的路由配置导致报错。 - 可选:适配JSON格式请求
你当前代码使用request.form读取参数,仅支持application/x-www-form-urlencoded格式的请求,如果需要接收JSON格式的请求,可修改参数读取逻辑:@app.route('/predict', methods=["POST"]) def predict(): # 优先从JSON请求体取参数,取不到再从form取 if request.is_json: solute = request.json.get("solute") solvent = request.json.get("solvent") else: solute = request.form.get("solute") solvent = request.form.get("solvent") results = predictions(solute, solvent) response = { "response": { 'energy': str(results) } } return flask.jsonify(response)
内容的提问来源于stack exchange,提问作者harsh
相关产品推荐
相关产品推荐

