【开源】使用Python+Flask+Mysql快速开发一个用户增删改查系统

news2025/2/27 8:21:16

项目演示

项目本身很简单,增删改查是几乎所有系统的骨架。正所谓万丈高楼平地起,学会了增删改查,航母就指日可待了:),光速入门,直接看演示图:
在这里插入图片描述

项目地址

https://github.com/mudfish/python-flask-user-crud

Flask框架介绍

说白了就是一个Web框架,能够让你快速开发出Python web应用。简单易用,大家直接看官网就行:
https://flask.palletsprojects.com/en/3.0.x/quickstart/

开发步骤

开发工具

懒得折腾Pycharm了,直接Vscode安装pyhon和flask插件即可,也是比较丝滑的。

准备静态文件

主要用了Bootstrap5和Jquery这两个前端框架,一个是UI,一个是js。
都放到static文件夹下面:
在这里插入图片描述

开发入口文件

这个就是flask运行的文件,里面包括了启动入口,端口号和业务逻辑接口。
在这里插入图片描述

from flask import Flask, render_template, request, redirect, url_for, flash
import pymysql.cursors



# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='123456',
                             db='user_test',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
    
app = Flask(__name__)

# 保持数据库连接
def getconnection():
    connection.ping(reconnect=True)
    return connection
    
# 首页
@app.route('/')
def index():
    try:
        with getconnection().cursor() as cursor:
            sql = "SELECT * FROM `tb_user`"
            cols = ['id', 'name', 'age','gender','phone']
            cursor.execute(sql)
            result = cursor.fetchall()
            cursor.close()
            return render_template("index.html", items=result, cols=cols, success='')
    except Exception as e:
        cursor.close()
        return render_template("index.html", items=[], cols=[], success='Can\'t view index: ' + str(e))
    
# 搜索
@app.route('/search')
def search():
    keyword = request.args.get('keyword').strip()
    try:
        with getconnection().cursor() as cursor:
            sql = "SELECT * FROM `tb_user` where name like concat('%%',%s,'%%')"
            cols = ['id', 'name', 'age','gender','phone']
            cursor.execute(sql,(keyword))
            result = cursor.fetchall()
            # print(result)
            cursor.close()
            return render_template("index.html", items=result, keyword=keyword, cols=cols, success='')
    except Exception as e:
        cursor.close()
        return render_template("index.html", items=[], cols=[], success='search error: ' + str(e))


@app.route('/toAddPage')
def toAddPage():
 return render_template('add.html')

@app.route('/toEditPage/<int:id>')
def toEditPage(id):
    # print(id)
    try:
        with getconnection().cursor() as cursor:
            sql = "select * from `tb_user` where id=%s"
            cursor.execute(sql, (id))
            result = cursor.fetchone()
            cursor.close()
            return render_template("edit.html", item=result, success='')
    except Exception as e:
        cursor.close()
        return render_template("edit.html", success='Can\'t edit User: ' + str(e))

@app.route('/add', methods=['POST'])
def add():
    name = request.form['name'].strip()
    age = request.form['age'].strip()
    gender = request.form['gender'].strip()
    phone = request.form['phone'].strip()
    try:
        with getconnection().cursor() as cursor:
            sql = "INSERT INTO `tb_user` (`name`, `age`,`gender`,`phone`) VALUES (%s, %s,%s,%s)"
            cursor.execute(sql, (name, age,gender,phone))
            cursor.close()
            return redirect(url_for("index"))
    except Exception as e:
        cursor.close()
        return render_template("add.html", success='Can\'t add User: ' + str(e))

@app.route('/edit',methods=['POST'])
def edit():
    id = request.form['id'].strip()
    name = request.form['name'].strip()
    age = request.form['age'].strip()
    phone = request.form['phone'].strip()
    gender = request.form['gender'].strip()
    try:
        with getconnection().cursor() as cursor:
            sql = "update `tb_user` set name=%s,age=%s,gender=%s,phone=%s where id=%s"
            cursor.execute(sql, (name, age,gender,phone,id))
            cursor.close()
            return redirect(url_for("index"))
    except Exception as e:
        cursor.close()
        return render_template("edit.html", success='Can\'t edit User: ' + str(e))

@app.route('/remove/<int:id>/')
def remove(id):
    try:
        with getconnection().cursor() as cursor:
            sql = "delete from `tb_user` where id=%s"
            cursor.execute(sql, (id))
            cursor.close()
            return redirect(url_for("index"))
    except Exception as e:
        cursor.close()
        return render_template("index.html", success='Can\'t remove User: ' + str(e))

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

@app.errorhandler(500)
def system_error(error):
    return render_template('500.html'), 500

if __name__ == '__main__':
    # 静态文件缓存自动刷新
    app.jinja_env.auto_reload = True
    app.run(host='127.0.0.1',port=8001, debug=True)

开发html文件

后端接口有了,接下来就是web端发起调用,完成增删改查交互操作了。
此处flask提供了简单易用的渲染语法,请看:

首页

<!DOCTYPE html>
<html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <link href="{{ url_for('static', filename = 'css/bootstrap.min.css') }}"
           rel="stylesheet">
       <title>首页</title>
   </head>
   <body>
       <div class="container">
           <div class="row justify-content-center align-items-center g-1">
               <div class="col-6 pt-5">
                   <!-- search -->
                   <form action="/search" method="get">
                       <div class="input-group mb-3">
                           <input type="text" class="form-control" placeholder
                               aria-label="Example text with button addon"
                               aria-describedby="button-addon1" name="keyword" {% if keyword%} value="{{keyword}}" {% endif %}>
                           <button class="btn btn-primary" type="submit"
                               id="button-addon1">查询</button>
                               <a class="btn btn-warning " href="/toAddPage">新增</a>
                       </div>
                   </form>

                   

                   <div
                       class="table-responsive">
                       <table
                           class="table table-primary">
                           <thead>
                               <tr>
                                   <th scope="col">ID</th>
                                   <th scope="col">姓名</th>
                                   <th scope="col">性别</th>
                                   <th scope="col">年龄</th>
                                   <th scope="col">联系方式</th>
                                   <th scope="col">操作</th>
                               </tr>
                           </thead>
                           <tbody>
                               {% for item in items %}
                               <tr>
                                   {% for col in cols %}
                                   <td>{{ item[col] }}</td>
                                   {% endfor %}
                                   <!-- 补操作列 -->
                                   <td>
                                       <a class="btn btn-sm btn-primary"
                                           href="{{url_for('toEditPage',id=item['id'])}}">编辑</a>
                                       <a class="btn btn-sm btn-danger"
                                           href="{{url_for('remove',id=item['id'])}}"
                                           onclick="return confirm('确定删除吗');" >删除</a>
                                   </td>
                               </tr>
                               {% endfor %}

                           </tbody>
                       </table>
                       <div class="bg-warning  ">{{success}}</div>

                   </div>
               </div>
           </div>
       </div>

       <script
           src="{{url_for('static',filename='js/jquery.min.js')}}"></script>

   </body>
</html>

新增页面

<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>新增用户</title>
   <link href="{{ url_for('static', filename = 'css/bootstrap.min.css') }}"
     rel="stylesheet">
 </head>
 <body>
   <div class="container">
     <div class="row justify-content-center align-items-center g-1">
       <div class="col-6 pt-5">
         <div class="card">
           <div class="card-header">
             新增用户
           </div>
           <div class="card-body">

             <form action="/add" method="post">
               <div class="row mb-3">
                 <label for="colFormLabelSm"
                   class="col-sm-2 col-form-label col-form-label">姓名</label>
                 <div class="col-sm-10">
                   <input type="text" class="form-control form-control-sm"
                     id="colFormLabelSm" name="name" required>
                 </div>
               </div>
               <div class="row mb-3">
                 <label for="age" class="col-sm-2 col-form-label">年龄</label>
                 <div class="col-sm-10">
                   <input type="text" class="form-control" id="age" name="age"
                     required>
                 </div>
               </div>
               <div class="row mb-3">
                 <label for="inlineRadio1"
                   class="col-sm-2 col-form-label">性别</label>
                 <div class="col-3">
                   <input class="form-check-input" type="radio" name="gender"
                     id="gender01" value="">
                   <label class="form-check-label" for="inlineRadio1"></label>
                 </div>
                 <div class="col-2">
                   <input class="form-check-input" type="radio" name="gender"
                     id="gender02" value="">
                   <label class="form-check-label" for="inlineRadio2"></label>
                 </div>
               </div>
               <div class="row mb-3">
                 <label for="phone"
                   class="col-sm-2 col-form-label">联系电话</label>
                 <div class="col-sm-10">
                   <input type="text" class="form-control" id="phone"
                     name="phone" required>
                 </div>
               </div>
               <div
                 class="row mb-3 justify-content-center align-items-center ">
                 <div class="col-6">
                   <a type="button" class="btn btn-secondary " href="/">
                     取消
                   </a>
                   <button type="submit" class="btn btn-primary ">
                     保存
                   </button>
                 </div>

               </div>
             </form>

           </div>

           <div class="bg-warning  ">{{success}}</div>
         </div>
       </div>

     </div>
   </div>
 </body>
</html>

编辑页面

<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>修改用户</title>
   <link href="{{ url_for('static', filename = 'css/bootstrap.min.css') }}"
     rel="stylesheet">
 </head>
 <body>
   <div class="container">
     <div class="row justify-content-center align-items-center g-1">
       <div class="col-6 pt-5">
         <div class="card">
           <div class="card-header">
             新增用户
           </div>
           <div class="card-body">
             <form action="/edit" method="post">
               {% if item %}
               <input type="hidden" name="id" value="{{item.id}}">
               <div class="row mb-3">
                 <!-- {{item}} -->
                 <label for="colFormLabelSm"
                   class="col-sm-2 col-form-label col-form-label">姓名</label>
                 <div class="col-sm-10">
                   <input type="text" class="form-control form-control-sm"
                     id="colFormLabelSm" name="name" value="{{item.name}}"
                     required>
                 </div>
               </div>
               <div class="row mb-3">
                 <label for="age" class="col-sm-2 col-form-label">年龄</label>
                 <div class="col-sm-10">
                   <input type="text" class="form-control" id="age" name="age"
                     value="{{item.age}}" required>
                 </div>
               </div>
               <div class="row mb-3">
                 <label for="gender" class="col-sm-2 col-form-label">性别</label>
                 <div class="col-3">
                   <input class="form-check-input" type="radio" name="gender"
                     id="gender01" value="男" {% if item.gender=="男" %} checked
                     {% endif %}>
                   <label class="form-check-label" for="gender01"></label>
                 </div>
                 <div class="col-2">
                   <input class="form-check-input" type="radio" name="gender"
                     id="gender02" value="女" {% if item.gender=="女" %} checked
                     {% endif %}>
                   <label class="form-check-label" for="gender02"></label>
                 </div>
               </div>
               <div class="row mb-3">
                 <label for="phone"
                   class="col-sm-2 col-form-label">联系电话</label>
                 <div class="col-sm-10">
                   <input type="text" class="form-control" id="phone"
                     name="phone" value="{{item.phone}}" required>
                 </div>
               </div>
               <div
                 class="row mb-3 justify-content-center align-items-center ">
                 <div class="col-6">
                   <a type="button" class="btn btn-secondary  " href="/">
                     取消
                   </a>
                   <button type="submit" class="btn btn-primary ">
                     保存
                   </button>
                 </div>
               </div>
               {% endif %}
             </form>
           </div>
         </div>
         <div class="bg-warning  ">{{success}}</div>
       </div>
     </div>
   </div>
 </body>
</html>

收工

看完觉着有帮助的朋友,一键三连哈~~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1608640.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[C++][算法基础]欧拉函数(常规求质数)

给定 n 个正整数 &#xff0c;请你求出每个数的欧拉函数。 欧拉函数的定义 1∼N 中与 N 互质的数的个数被称为欧拉函数&#xff0c;记为 ϕ(N)。 若在算数基本定理中&#xff0c;N…&#xff0c;则&#xff1a; ϕ(N) N… 输入格式 第一行包含整数 n。 接下来 n 行&#xf…

雨云:让你的服务器体验不再“阴霾”

引言 在当今数字化的时代&#xff0c;服务器已经成为了我们生活中不可或缺的一部分。无论是个人网站、企业应用还是游戏服务器&#xff0c;都需要一个稳定可靠的平台来运行。然而&#xff0c;在选择服务器提供商时&#xff0c;很多人常常陷入选择困难&#xff0c;不知道哪家更适…

IO进程(线程Thread)

线程Thread 1.什么是线程 1.1 概念 线程是一个轻量级的进程&#xff0c;为了提高系统的性能引入线程。 线程和进程都参与统一的调度。 在同一个进程中可以创建的多个线程, 共享进程资源。 &#xff08;Linux里同样用task_struct来描述一个线程&#xff09; 1.2 进程和线程的区别…

精益思维驱动人工智能革新:理论到实践的跃迁之旅

随着科技的飞速发展&#xff0c;人工智能&#xff08;AI&#xff09;已成为引领未来的关键力量。在这个变革的时代&#xff0c;如何将精益思维与人工智能相结合&#xff0c;推动AI从理论走向实践&#xff0c;成为行业内外关注的焦点。本文&#xff0c;天行健精益生产顾问将分享…

拷贝构造函数与运算符重载

目录 一、拷贝构造函数 1.概念 2.特性 二、运算符重载 1.运算符重载 2.运算符重载实现的形式 3.赋值运算符重载 一、拷贝构造函数 1.概念 拷贝构造函数是一种特殊的构造函数&#xff0c;它在创建对象时&#xff0c;使用同一类中之前创建的对象来初始化新创建的对象…

Vitis HLS 学习笔记--scal 函数-探究

目录 1. Vitis HLS重器-Vitis_Libraries 2. 初识scal() 3. 函数具体实现 3.1 变量命名规则 3.2 t_ParEntries解释 3.3 流类型详解 3.4 双重循环 4. 总结 1. Vitis HLS重器-Vitis_Libraries 在深入探索Vitis HLS&#xff08;High-Level Synthesis&#xff09;的旅程中&…

【单调栈】力扣85.最大矩形

好久没更新了 ~ 我又回来啦&#xff01; 两个好消息&#xff1a; 我考上研了&#xff0c;收到拟录取通知啦&#xff01;开放 留言功能 了&#xff0c;小伙伴对于内容有什么疑问可以在文章底部评论&#xff0c;看到之后会及时回复大家的&#xff01; 前面更新过的算法&#x…

kafka的概念以及Zookeeper集群 + Kafka集群 +elfk集群

目录 zookeeper同步过程 分布式通知和协调 zookeeper同步过程 分布式通知和协调 准备 3 台服务器做 Zookeeper 集群 192.168.68.5 192.168.68.6 192.168.68.7 安装前准备 //关闭防火墙 systemctl stop firewalld systemctl disable firewalld setenforce 0 node1服务器&a…

了解8大Python小陷阱,深入理解Python

学习了解python常见的使用陷阱&#xff0c;避免二次踩坑 Python是最流行的且适合初学者学习的语言之一。它的语法非常优雅简洁。只要知道python基础知识&#xff0c;阅读代码几无障碍。 然而&#xff0c;就像其他语言一样&#xff0c;Python确实有一些古怪特殊的地方。本文将介…

ssm062会员管理系统+jsp

会员管理系统 摘 要 随着科学技术的飞速发展&#xff0c;各行各业都在努力与现代先进技术接轨&#xff0c;通过科技手段提高自身的优势&#xff1b;对于会员管理系统当然也不能排除在外&#xff0c;随着网络技术的不断成熟&#xff0c;带动了会员管理系统&#xff0c;它彻底改…

关于二级指针void**的一点问题与思考

前言 这两天写一个高并发内存池的项目时&#xff0c;遇到了一个关于二级指针的问题&#xff0c;剖析清楚后发觉有必要记录一下&#xff0c;这让我加深了对于C/C中指针的理解&#xff08;果然学到老活到老&#xff09;。 问题的分析 在我的内存池项目中&#xff0c;有一个需求…

2024华中杯C题光纤传感器平面曲线重建原创论文分享

大家好&#xff0c;从昨天肝到现在&#xff0c;终于完成了2024华中杯数学建模C题的完整论文啦。 给大家看一下目录吧&#xff1a; 目录 摘 要&#xff1a; 10 一、问题重述 12 二&#xff0e;问题分析 13 2.1问题一 13 2.2问题二 14 2.3问题三 14 三、模型假设 15 四、…

Spring Task 定时任务调度

一、概念 Spring Task 是 Spring 框架的一个组件&#xff0c;它为任务调度提供了支持&#xff0c;使得开发者能够创建后台任务或定期执行的任务。通过 Spring Task&#xff0c;您可以方便地在 Java 应用程序中实现定时任务&#xff0c;比如每天凌晨进行数据同步、每小时执行一…

day02-新增员工

day01 新增员工业务逻辑整理 EmployeeController.java PostMappingApiOperation("新增员工")public Result save(RequestBody EmployeeDTO employeeDTO){System.out.println("当前线程的ID:" Thread.currentThread().getId());log.info("新增员工&a…

2024年华中杯数模竞赛A题完整解析(附代码)

2024年华中杯数模竞赛A题 基于动态优化的太阳能路灯光伏板朝向以最大化能量收集研究摘要问题重述问题分析模型假设符号说明 代码问题一 完整资料获取 基于动态优化的太阳能路灯光伏板朝向以最大化能量收集研究 摘要 随着可再生能源技术的发展&#xff0c;太阳能作为一种清洁的…

2024新版淘宝客PHP网站源码

源码介绍 2024超好看的淘客PHP网站源码&#xff0c;可以做优惠券网站&#xff0c;上传服务器&#xff0c;访问首页进行安装 安装好了之后就可以使用了&#xff0c;将里面的信息配置成自己的就行 喜欢的朋友们拿去使用把 效果截图 源码下载 2024新版淘宝客网站源码

【云计算】云数据中心网络(七):负载均衡

《云网络》系列&#xff0c;共包含以下文章&#xff1a; 云网络是未来的网络基础设施云网络产品体系概述云数据中心网络&#xff08;一&#xff09;&#xff1a;VPC云数据中心网络&#xff08;二&#xff09;&#xff1a;弹性公网 IP云数据中心网络&#xff08;三&#xff09;…

MySQL数据库-优化慢查询

1、什么是慢查询&#xff1f; 慢查询就是SQL执行时间过长&#xff0c;严重影响用户体验的SQL查询语句。当它频繁出现时数据库的性能和稳定性都会受到威胁 慢查询是数据库性能瓶颈的常见原因&#xff0c;是指SQL执行时间超过阈值&#xff1b;可能由于复杂的连接、缺少索引、不恰…

保持领先:四个ChatGPT小技巧助你成为不可替代的数据分析师

在前文中&#xff0c;我们初步探讨了为何ChatGPT无法完全替代数据分析师的原因&#xff0c;而本文将深入探讨如何利用GPT辅助数据分析师提升工作效率。 **场景一&#xff1a;SQL数据提取** 许多数据分析师需使用SQL语言从数据库中抽取数据。尽管SQL操作简便&#xff0c;但编写…

类和对象-封装-设计案例1-立方体类

#include<bits/stdc.h> using namespace std; class Cube{public://设置长void setL(int l){m_Ll;} //获取长int getL(){return m_L;}//设置宽 void setW(int w){m_Ww;}//获取宽 int getW(){return m_W;}//设置高 void setH(int h){m_Hh;}//获取高int getH(){return m_H;…