defupdate_user(user_id, new_username, new_email): user = User.query.get(user_id) if user: user.username = new_username user.email = new_email db.session.commit() return user
删除(Delete)
删除记录同样需要查询到记录后进行删除。
1 2 3 4 5 6
defdelete_user(user_id): user = User.query.get(user_id) if user: db.session.delete(user) db.session.commit() return user
四、示例应用
现在我们将这些 CRUD 方法整合到一个简单的 Flask 路由中,演示如何在应用中使用这些操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
@app.route('/create/<username>/<email>') defcreate(username, email): user = create_user(username, email) returnf'Created user: {user.username}'
@app.route('/users') defusers(): users = get_all_users() return'<br>'.join([user.username for user in users])
@app.route('/update/<int:user_id>/<new_username>/<new_email>') defupdate(user_id, new_username, new_email): user = update_user(user_id, new_username, new_email) returnf'Updated user: {user.username}'if user else'User not found!'
@app.route('/delete/<int:user_id>') defdelete(user_id): user = delete_user(user_id) returnf'Deleted user: {user.username}'if user else'User not found!'