我想使用 python 、flask 、rest api 更新 mysql 表中的数据,但当我使用 postman 时它不起作用

问题描述 投票:0回答:1

我在flask_sqlalchemy中创建了一个表

class Cafe(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), unique=True, nullable=False)
    map_url = db.Column(db.String(500), nullable=False)
    img_url = db.Column(db.String(500), nullable=False)
    location = db.Column(db.String(250), nullable=False)
    seats = db.Column(db.String(250), nullable=False)
    has_toilet = db.Column(db.Boolean, nullable=False)
    has_wifi = db.Column(db.Boolean, nullable=False)
    has_sockets = db.Column(db.Boolean, nullable=False)
    can_take_calls = db.Column(db.Boolean, nullable=False)
    coffee_price = db.Column(db.String(250), nullable=True)

    def to_dict(self):
        #Method 1. 
        dictionary = {}
        # Loop through each column in the data record
        for column in self.__table__.columns:
            #Create a new dictionary entry;
            # where the key is the name of the column
            # and the value is the value of the column
            dictionary[column.name] = getattr(self, column.name)
        return dictionary

我为此创建了 REST API 以添加更多咖啡馆数据。

使用此代码

@app.route("/add",methods=["POST"])
def add_cafe():
    body = request.form
    try:
        new_cafe = Cafe(
            name=request.form['name'],
            location=request.form['location'],
            seats=request.form['seats'],
            img_url=request.form['img_url'],
            map_url=request.form['map_url'],
            coffee_price=request.form['coffee_price'],
            has_wifi=bool(request.form['has_wifi']),
            has_toilet=bool(request.form['has_toilet']),
            has_sockets=bool(request.form['has_sockets']),
            can_take_calls=bool(request.form['can_take_calls']),
        )
    except KeyError:
        return jsonify(error={"Bad Request": "Some or all fields were incorrect or missing."})
    else:
        with app.app_context():
            db.session.add(new_cafe)
            db.session.commit()
        return jsonify(response={"success": f"Successfully added the new cafe."})

值得庆幸的是,这两段代码运行良好。但问题出在这段代码中

@app.route("/update-price/<int:cafe_id>",methods=["PATCH"])
def patch_new_cafe():
    new_price = request.args.get("new_price")
    cafe = db.session.query(Cafe).get("cafe_id")
    cafe.coffee.price = new_price
    if cafe:
        with app.app_context():
            db.session.commit()
        return jsonify(response={"Success":"Successfully updated the price"}),200
    else:
        return jsonify(response={"Not Found":"Sorry a cafe with that id was not found in the database."}),404

所以假设我想将 ID 为 4 的咖啡馆的咖啡价格更改为 5 美元,这是可行的,这就是响应

{ “回复”: { "success": "价格更新成功。" } }

而且效果很好。当我使用数据库浏览器检查时,mysql表中的数据发生了变化

但是当我从字面上复制粘贴相同的代码时,对邮递员补丁中的价格进行了微小的更改。这就是我得到的-_-。我很可能犯了一个愚蠢的错误或其他错误,但请原谅我,我是创建 api 的新手,我为此花了一整天的时间。

this is the error.

python mysql flask sqlalchemy
1个回答
0
投票

你们。我找到了解决方案😅。显然我有两个名为 patch_new_cafe() 的函数,一个带有参数,另一个不带参数。所以python读取了第一个没有参数的函数并给出了错误。就像我说的,我犯了一个愚蠢的错误,这意味着我需要睡觉。谢谢 Barmar 你的解决方案修复了它,并感谢你的 to_dict() 方法提示。还要感谢 Detlef 的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.