from config import app, db
from model import User
import flask_bcrypt
@app.route("/")
def hello_world():
return "hello flask!"
# 添加用户
@app.route("/user/add")
def user_add():
password = flask_bcrypt.generate_password_hash("88888888")
# 创建ORM对象
user = User(name="Tina", email="[email protected]", password=password)
# 将ORM对象添加到db.session中
db.session.add(user)
# 将db.session中的数据同步至数据库.
db.session.commit()
return "用户添加成功!"
# 数据查询
@app.route("/user/query/<int:user_id>")
def user_query(user_id=1):
# # 1. get查询 根据主键值进行查询
# user = User.query.get(user_id)
# if user:
# ret = {"ID": user.id, "name": user.name, "email": user.email}
# return f"数据查找成功{ret}"
# return "未找到该用户信息!"
# 2. filter_by 查找 (普遍用的比较多)
users = User.query.filter_by(id=user_id)
# users: Query对象
ret = []
for user in users:
ret.append({"ID": user.id, "name": user.name, "email": user.email})
if ret:
return f"数据查找成功{ret}"
return "未找到用户信息!"
@app.route("/user/update/<int:user_id>")
def user_update(user_id=1):
user = User.query.filter_by(id=user_id).first()
if user:
user.email = "[email protected]"
db.session.commit()
return "数据更新成功!"
return "未找到用户信息!"
@app.route("/user/delete/<int:user_id>")
def user_delete(user_id=1):
user = User.query.get(user_id)
if user:
db.session.delete(user)
db.session.commit()
return "数据删除成功!"
return "未找到用户信息!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5001, debug=True)
其中的配置文件[config.py,model.py,createdb.py]在上一篇文中已经上传。
标签:session,10,return,db,app,CRUD,ORM,user,id From: https://www.cnblogs.com/pythonex/p/18089711