我正在尝试通过添加,修改和删除信息来测试我编写的Flask脚本。但是,如果我运行methods=["GET"]
以外的任何内容,则会收到一条错误消息,提示不允许使用该方法。
我正在运行的脚本是:
#!flask/bin/python
from flask import Flask, jsonify, request, abort, make_response
from flask_cors import CORS
import csv
stocks = [
{"id": 1, "Stock": "BoI", "Price": 300},
{"id": 2, "Stock": "Apple", "Price": 499}
]
Next_ID = len(stocks)
app = Flask(__name__, static_url_path="", static_folder=".")
CORS(app, support_credentials=True)
@app.route("/")
@app.route("/Stocks")
def getAll():
return jsonify(stocks)
# curl http://127.0.0.1:5000
@app.route("/Stocks/<int:id>")
def getById(id):
sel_stock = list(filter(lambda s: s["id"] == id, stocks))
if len(sel_stock) == 0:
return jsonify ({}), 204
else:
return jsonify(sel_stock[0])
# curl http://127.0.0.1:5000/1
@app.route("/Stocks", methods=["POST"])
def create(id):
global Next_ID
if not request.json:
abort(400)
stock = {
"id": Next_ID,
"Stock": request.json["Stock"],
"Price": request.json["Price"],
}
Next_ID += 1
stocks.append(stock)
return jsonify(stock)
# return str(Next_ID)
@app.route("/Stocks", methods=["PUT"])
def update(id):
sel_stock = list(filter(lambda s: s["id"] == id, stocks))
if len(sel_stock) == 0:
abort(400)
sel_stock = sel_stock[0]
if not request.json:
abort(400)
reqJSON = request.json
if reqJSON["Stock"]:
sel_stock["Stock"] = reqJSON["Stock"]
if reqJSON["Price"]:
sel_stock["Price"] = reqJSON["Price"]
return jsonify(sel_stock)
@app.route("/Stocks", methods=["DELETE"])
def delete(id):
return "in delete"
if __name__ == "__main__":
app.run(debug = True)
如果我运行curl命令以获取所有信息或通过ID号获取信息,则没有问题。但是,如果我尝试以下curl命令,则会收到错误消息:
curl -i -H "Content-Type:application/json" -X POST -d "{\"Stock\":\"IBM\",\"Price\":\123}" http://127.0.0.1:5000/Stocks
TypeError:create()缺少1个必需的位置参数:“ id”
答案 0 :(得分:3)
您不需要,无需将id
传递给POST方法,因为其网址中没有id
作为参数:
@app.route("/Stocks", methods=["POST"])
def create(): # removed id
"""some code here"""