码迷,mamicode.com
首页 > Web开发 > 详细

flask实现关于json的get/post/put/delete方法

时间:2018-10-13 18:14:25      阅读:417      评论:0      收藏:0      [点我收藏+]

标签:tst   form   method   query   status   message   gets   out   request   

@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方法

标签:tst   form   method   query   status   message   gets   out   request   

原文地址:https://www.cnblogs.com/q02062418/p/9783501.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!