flask实现关于json的get/post/put/delete方法
Posted zzxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask实现关于json的get/post/put/delete方法相关的知识,希望对你有一定的参考价值。
@blue.route(‘/user/<int:id>/‘,methods=["GET","POST","PUT","DELETE"])
def user(id):
# 查询数据
if request.method == "GET":
user = User.query.get(id)
userdict = user.getstr()
data = {
"message":"successfully",
"status":"201",
}
if user:
data["user"] = userdict
return jsonify(data),200
data["message"] = "该用户不存在"
data[‘status‘] = "404"
return jsonify(data),404
# 添加数据
elif request.method == "POST":
username = request.form.get("username")
userage = request.form.get("userage")
users = User.query.filter(User.u_name == username).all()
data = {
}
if len(users) > 0:
data["message"] = "用户已存在"
data["status"] = "777"
return jsonify(data),409
user = User()
user.u_name = username
user.u_age = userage
data["message"] = "用户创建成功"
data["status"] = "201"
db.session.add(user)
db.session.commit()
return jsonify(data),201
# 修改数据
elif request.method == "PUT":
username = request.form.get("username")
userage = request.form.get("userage")
user = User.query.get(id)
print(user)
data = {
}
if user:
data["message"] = "信息修改成功"
data["status"] = ‘200‘
user.u_name = username
user.u_age = userage
db.session.add(user)
db.session.commit()
return jsonify(data),200
data["message"] = "用户不存在"
data["status"] = "404"
return jsonify(data),404
# 删除数据
elif request.method == "DELETE":
user = User.query.get(id)
data = {
}
if user:
data["message"] = "信息删除成功"
data["status"] = "200"
db.session.delete(user)
db.session.commit()
return jsonify(data),200
以上是关于flask实现关于json的get/post/put/delete方法的主要内容,如果未能解决你的问题,请参考以下文章