如何修复Android Retrofit调用Flask POST API的「方法不被允许」错误?
修复Flask-RESTful POST接口"方法不允许"的错误
嘿,我看了你遇到的问题,这个"The method is not allowed for the requested URL."错误主要是因为Flask-RESTful的Resource类没正确识别你的POST请求处理方法,另外代码里还有几个小问题需要调整,我来帮你一一修复:
问题根源与修复步骤
1. 必须使用标准的请求处理方法名
Flask-RESTful的Resource类有明确规则:处理POST请求的方法必须命名为post(),而不是你自定义的add_spending。框架会根据HTTP请求方法自动匹配对应的类方法(比如get()对应GET,post()对应POST),你的代码里没定义post()方法,框架找不到处理逻辑,就返回了方法不允许的错误。
2. 修正SQLite的参数占位符
SQLite不支持%s/%d这种占位符,正确的参数占位符是?,否则会触发SQL语法错误。
3. 理顺数据库连接与游标逻辑
你代码里的游标创建和执行逻辑有点混乱,比如重复调用conn.cursor(),还没正确使用游标对象执行SQL语句,这会导致数据库操作失败。
4. 添加规范的响应返回
原代码里没有返回合适的JSON响应,成功和失败的情况都需要明确返回对应的状态码和信息,这样客户端才能正确处理结果。
修复后的完整代码
from flask import Flask, request, jsonify from flask_restful import Resource, Api from sqlalchemy import create_engine db_connect = create_engine('sqlite:///api.db') app = Flask(__name__) api = Api(app) class AddSpending(Resource): def post(self): # 改成标准的post方法名 try: _json = request.json # 先检查请求体是否存在 if not _json: return jsonify({"message": "Missing JSON data"}), 400 _date = _json.get('date') _reason = _json.get('reason') _amount = _json.get('amount') # 验证参数是否齐全 if _date and _reason and _amount: # 使用SQLite正确的占位符? sql = "INSERT INTO spending(date, reason, amount) VALUES(?, ?, ?)" data = (_date, _reason, _amount) conn = db_connect.connect() cursor = conn.cursor() # 正确获取游标 cursor.execute(sql, data) # 用游标执行SQL conn.commit() return jsonify({"message": "Spending added successfully!"}), 201 else: return jsonify({"message": "Missing required parameters"}), 400 except Exception as e: print(f"Error: {e}") return jsonify({"message": "Internal server error"}), 500 finally: # 确保游标和连接正确关闭 if 'cursor' in locals(): cursor.close() if 'conn' in locals(): conn.close() api.add_resource(AddSpending, '/spending_up') # methods=['POST']可省略,框架会自动识别类中的post方法 if __name__ == '__main__': app.run(debug=True) # 添加启动代码,方便本地测试
额外测试提示
- 调用接口时,务必确保请求的
Content-Type是application/json,请求体是合法JSON格式,比如:{ "date": "2024-05-20", "reason": "午餐", "amount": 20 } - 可以用Postman或者curl命令测试,确认请求方法是POST、URL正确。
内容的提问来源于stack exchange,提问作者Katta Omkareshwar
相关产品推荐
相关产品推荐

