flask接收post提交的json数据并保存至数据库

时间:2021-09-28 06:09:43

定义数据模型

# 定义数据模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), nullable=False, unique=True)
phone = db.Column(db.Integer, nullable=False) def __repr__(self):
return '<User {}>'.format(self.name)

请求路由

# 请求路由
@app.route('/user', methods=['GET', 'POST'])
def userinfo():
users = User.query.all()
if request.method == 'POST':
name = request.json.get('name')
phone = request.json.get('phone')
user = User(
name=name,
phone=phone
)
if User.query.filter_by(name=name).first():
return jsonify({"msg": "name already in use"})
try:
db.session.add(user)
db.session.commit()
except:
return jsonify({"msg": "error"})
return jsonify({'msg': 'ok'}) user_list = []
for user in users:
data = {}
data['id'] = user.id
data['name'] = user.name
data['phone'] = user.phone
user_list.append(data)
return jsonify({"users": user_list})

POST请求结果如下

flask接收post提交的json数据并保存至数据库