完整代码放到了最后,时间紧张的话直接拉到最后或点击目录【🥩 完整代码】看完整代码

🚎前言:

这里先提一下,我们运行后端代码之前需要先建立一个名字为python的数据库,而后在该数据库下创建表 userinfo,因为看到有的朋友后端代码拿过去后会运行不起来或者就是直接报错了。至于使用MySQL可视化工具还是用sql语句创建,这个看自己个人的,如果sql不怎么熟练的,甚至没有基础的,可以参考一下自己的这一篇文章MYSQL的增删改查相关操作


相信看过自己前期的博文python使用flask模块和前端交互基础以及python模块pymysql对数据库进行增删改查的小伙伴已经有了一定基础,这里我们在来对flask、pymsql、前端三个部分通过flask做一个整合。使用python来作为我们的后端来实现前后端的分离。
既然是作为基础,那我们这里主要实现通过前端对我们后端数据库实现增删改查就OK 了。下面我们开始。

🛺工具

后端:python(flask,pymsql)、MySQL、navicat、VScode
前端:VScode、Google浏览器

🚓截图

🚕数据库截图

这里的截图的是navicat,里面的id做了主键自增
在这里插入图片描述

🚙前端截图

前端上样式没有去做过多的修饰,只是做一个大概样式,有兴趣的也可以自己去用CSS修改一下
在这里插入图片描述

可视化截图就截图这两张吧,接下来就是代码了

🚘代码

这里先提一下,这个是需要下载MySQL数据库的,再有一些MySQL数据库的增删改查的代码学习基础。要不然有的代码可能是看不明白的哈,特别是数据库那一块的。restful风格这里对于增删改查使用了不同的方式

🚲增加

增加数据库这里用的也是基本和其它常见后端所用的那种方式,使用了post请求方法,对于前端不是从URL请求上携带的参数,我们都可以使用flask模块中的request的**get_dada()**方法来获取,至于如何取在URL上的数据,可以看下关于【🛴 删除】那里的简介。

🍕前端 HTML
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      border-bottom: 1px solid gray;
      padding-bottom: 10px;
    }

    table {
      width: 100%;
      text-align: center;
      border: solid 1px gray;
    }
  </style>
</head>

<body>
  <div id="add">
    <h3>新增数据</h3>
    姓名:<input type="text">
    年龄:<input type="text">
    专业:<input type="text">
    爱好:<input type="text">
    <button onclick="add()">提交</button>
  </div>
  <script>
    let xhr = new XMLHttpRequest(); //前端使用XMLHttpRequest创建的对象来访问后端
    const add = () => {
      let inputs = document.querySelectorAll("#add input");
      let addJson = {}
      addJson.name = inputs[0].value
      addJson.age = inputs[1].value
      addJson.major = inputs[2].value
      addJson.hobby = inputs[3].value
      // let res = ajax(,)
      xhr.open('post', 'http://localhost:8090/add', true)//最后一个参数表示是否异步请求
      xhr.send(JSON.stringify(addJson))
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText;
            isFirstRender = false
            alert(JSON.parse(res).msg);
            select()
          }
        }
      }
    }
  </script>
</body>

</html>
🍟后端 python
import pymysql
from flask import Flask,request
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app=app) # 跨域设置
app.debug=True # 开启debug模式
db = pymysql.connect(host='localhost',user='root',password='root',database='python') # 建立连接
cursor = db.cursor() #创建游标
@app.route('/add',methods=['post']) #设置请求头和请求方式
def add():
  req_data = request.get_data() # 获取data数据
  data = json.loads(req_data) # 需要使用json.loads来转换一下,返回的数据是字符码
  print(data)
  try:
    sql_data = (data['name'],int(data['age']),data['major'],data['hobby'])
    sql = "insert into userinfo(name,age,major,hobby) values (%s,%s,%s,%s)" #MySQL查询语句
    cursor.execute(sql,sql_data)
    db.commit()
    return {'code':200,'msg':'数据新增成功'}
  except:
    db.rollback()  # 发生错误时回滚 
    return {'code':1000,'msg':"添加失败"}
 if __name__ == '__main__':
  app.run(host="localhost",port='8090')
  cursor.close() #关闭游标
  db.close() # 关闭数据库连接

🛴 删除

删除使用的请求方式是delete。众所周知,前端发送给后端的数据要么在URL中,要么在请求体里面,这里的话,删除我就把数据放在了URL中,flask的request模块可以通过args.get()方法来接收前端放在URL中的数据。

🍕前端 HTML
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      border-bottom: 1px solid gray;
      padding-bottom: 10px;
    }

    table {
      width: 100%;
      text-align: center;
      border: solid 1px gray;
    }
  </style>
</head>

<body>
  
  <div id="del">
    <h3>根据姓名删除数据</h3>
    姓名:<input type="text">
    <button onclick="del()">删除</button>
  </div>
  <script>
    let xhr = new XMLHttpRequest();
    const del = () => {
      let input = document.querySelector("#del input");
      xhr.open('delete', 'http://localhost:8090/del?name=' + input.value, true)
      xhr.send()
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText
            isFirstRender = false
            alert(JSON.parse(res).msg);
            select()
          }
        }
      }
    }
  </script>
</body>
</html>
🍟后端 python
import pymysql
from flask import Flask,request
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app=app)
app.debug=True
db = pymysql.connect(host='localhost',user='root',password='root',database='python')
cursor = db.cursor() #创建游标
@app.route('/del',methods=['delete'])
def delete():
  deleteName = request.args.get('name')
  sql=f'delete from `userinfo` where name="{deleteName}";' # 删除数据的sql语句
  try:
    cursor.execute(sql)
    db.commit()
    return {'code':200,'msg':'删除成功'}
  except:
    db.rollback()  # 发生错误时回滚 
    return {'code':1000,'msg':"删除失败"}
 if __name__ == '__main__':
  app.run(host="localhost",port='8090')
  cursor.close() #关闭游标
  db.close() # 关闭数据库连接

🛵 编辑

修改数据这里就不多说了,直接看源码吧

🍕前端 HTML
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      border-bottom: 1px solid gray;
      padding-bottom: 10px;
    }

    table {
      width: 100%;
      text-align: center;
      border: solid 1px gray;
    }
  </style>
</head>

<body>
  <div id="edit">
    <h3>编辑数据</h3>
    <p>
      姓名:<input type="text" class="name" placeholder="请输入需要修改的姓名"> <input class="name" type="text" placeholder="请输入修改后的姓名">
      <button onclick="edit()">修改</button>
    </p>   
  </div>
  <script>
    let xhr = new XMLHttpRequest();
  const edit = () => {
      let names = document.querySelectorAll("#edit .name");
      let addJson = {}
      addJson.beforeName = names[0].value
      addJson.afterName = names[1].value
      xhr.open('put', 'http://localhost:8090/edit', true)
      xhr.send(JSON.stringify(addJson))
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText;
            isFirstRender = false
            alert(JSON.parse(res).msg);
            select()
          }
        }
      }
    }
  </script>
</body>
</html>
🍟后端 python
import pymysql
from flask import Flask,request
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app=app)
app.debug=True
db = pymysql.connect(host='localhost',user='root',password='root',database='python')
cursor = db.cursor() #创建游标
@app.route('/edit',methods=['put'])
def edit():
  req_data = request.get_data()
  data = json.loads(req_data)
  print('修改消息:',data)
  try:
    sql = f"update userinfo set name='{data['afterName']}' where name='{data['beforeName']}'"
    cursor.execute(sql)
    db.commit()
    return {'code':200,'msg':'修改成功'}
  except:
    db.rollback() 
    return {'code':1000,'msg':"修改失败"}
 if __name__ == '__main__':
  app.run(host="localhost",port='8090')
  cursor.close() #关闭游标
  db.close() # 关闭数据库连接

🛵 查看

🍕前端 HTML

查看数据这里需要注意一下,修改的数据是需要替换或者新增到我们的表里面,所以需要先删除掉原来的表再替换上新修改或增加的数据。有点前端基础的应该都清楚怎么做。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      border-bottom: 1px solid gray;
      padding-bottom: 10px;
    }

    table {
      width: 100%;
      text-align: center;
      border: solid 1px gray;
    }
  </style>
</head>

<body>
  <div id="select">
    <h3>查询数据 <button onclick="select()">查询</button></h3>
    <table border cellspacing="0px" cellpading="0">
      <tr class="tableT">
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>专业</th>
        <th>爱好</th>
      </tr>
    </table>
  </div>
  <script>
    let xhr = new XMLHttpRequest();
 const select = () => {
      xhr.open('get', 'http://localhost:8090/select', true)
      xhr.send()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText;
            let tdData = JSON.parse(res).data
            let tableT = document.querySelector("table");
            if(isFirstRender){

              tdData.forEach(element => {
                let tableB = document.createElement('tr')
                tableB.className = 'tableB'
                tableB.innerHTML = `
                <td>${element.id}</td>
                <td>${element.name}</td>
                <td>${element.age}</td>
                <td>${element.major}</td>
                <td>${element.hobby}</td>
                `
                tableT.appendChild(tableB)
              });
            }else{
              let delTableB = document.querySelectorAll('.tableB')
              for(let i = 0;i<delTableB.length;i++){
                tableT.removeChild(delTableB[i])
              }
              tdData.forEach(element => {
                let tableB = document.createElement('tr')
                tableB.className = 'tableB'
                tableB.innerHTML = `
                <td>${element.id}</td>
                <td>${element.name}</td>
                <td>${element.age}</td>
                <td>${element.major}</td>
                <td>${element.hobby}</td>
                `
                tableT.appendChild(tableB)
              });
            }
          }
        }
      }
    }
  </script>
</body>
</html>
🍟后端 python
import pymysql
from flask import Flask,request
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app=app)
app.debug=True
db = pymysql.connect(host='localhost',user='root',password='root',database='python')
cursor = db.cursor() #创建游标
@app.route('/select',methods=['get'])
def select():
  try:
    cursor.execute("SELECT * FROM userinfo")
    array = []
    data=()
    while isinstance(data,tuple):#循环遍历出data的数据
      data = cursor.fetchone() #fetchone方法用于取出数据库中查询的单个数据
      if(data == None): break
      obj = {}
      obj['id'] = data[0]
      obj['name'] = data[1]
      obj['age'] = data[2]
      obj['major'] = data[3]
      obj['hobby'] = data[4]
      array.append(obj)
    return {'code':200,'msg':'查询成功','data':array}
  except:
    db.rollback() 
    return {'code':1000,'msg':"查询失败"}
 if __name__ == '__main__':
  app.run(host="localhost",port='8090')
  cursor.close() #关闭游标
  db.close() # 关闭数据库连接

🥩 完整代码

🥐前端 HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      border-bottom: 1px solid gray;
      padding-bottom: 10px;
    }

    table {
      width: 100%;
      text-align: center;
      border: solid 1px gray;
    }
  </style>
</head>

<body>
  <div id="select">
    <h3>查询数据</h3>
    <table border cellspacing="0px" cellpading="0">
      <tr class="tableT">
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>专业</th>
        <th>爱好</th>
      </tr>
    </table>
  </div>
  <div id="add">
    <h3>新增数据</h3>
    姓名:<input type="text">
    年龄:<input type="text">
    专业:<input type="text">
    爱好:<input type="text">
    <button onclick="add()">提交</button>
  </div>
 
  <div id="edit">
    <h3>编辑数据</h3>
    <p>
      姓名:<input type="text" class="name" placeholder="请输入需要修改的姓名"> <input class="name" type="text" placeholder="请输入修改后的姓名">
      <button onclick="edit()">修改</button>
    </p>   
  </div>
  <div id="del">
    <h3>根据姓名删除数据</h3>
    姓名:<input type="text">
    <button onclick="del()">删除</button>
  </div>
  <script>
    let xhr = new XMLHttpRequest();

    function ajax(methods, url, data) {
      // xhr.setRequestHeader('Content-Type','text/json;charset=UTF-8')
      xhr.open(methods, url, true)
      xhr.send(data)
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText;
            console.log(JSON.parse(res));
            return JSON.parse(res)
          }
        }
      }
    }
    let isFirstRender = true
    const add = () => {
      let inputs = document.querySelectorAll("#add input");
      let addJson = {}
      addJson.name = inputs[0].value
      addJson.age = inputs[1].value
      addJson.major = inputs[2].value
      addJson.hobby = inputs[3].value
      // let res = ajax(,)
      xhr.open('post', 'http://localhost:8090/add', true)
      xhr.send(JSON.stringify(addJson))
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText;
            isFirstRender = false
            alert(JSON.parse(res).msg);
            select()
          }
        }
      }
    }
    const edit = () => {
      let names = document.querySelectorAll("#edit .name");
      let addJson = {}
      addJson.beforeName = names[0].value
      addJson.afterName = names[1].value
      xhr.open('put', 'http://localhost:8090/edit', true)
      xhr.send(JSON.stringify(addJson))
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText;
            isFirstRender = false
            alert(JSON.parse(res).msg);
            select()
          }
        }
      }
    }
    const select = () => {
      xhr.open('get', 'http://localhost:8090/select', true)
      xhr.send()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText;
            let tdData = JSON.parse(res).data
            let tableT = document.querySelector("table");
            if(isFirstRender){
              tdData.forEach(element => {
                let tableB = document.createElement('tr')
                tableB.className = 'tableB'
                tableB.innerHTML = `
                <td>${element.id}</td>
                <td>${element.name}</td>
                <td>${element.age}</td>
                <td>${element.major}</td>
                <td>${element.hobby}</td>
                `
                tableT.appendChild(tableB)
              });
            }else{
              let delTableB = document.querySelectorAll('.tableB')
              for(let i = 0;i<delTableB.length;i++){
                tableT.removeChild(delTableB[i])
              }
              tdData.forEach(element => {
                let tableB = document.createElement('tr')
                tableB.className = 'tableB'
                tableB.innerHTML = `
                <td>${element.id}</td>
                <td>${element.name}</td>
                <td>${element.age}</td>
                <td>${element.major}</td>
                <td>${element.hobby}</td>
                `
                tableT.appendChild(tableB)
              });
            }
          }
        }
      }
    }
    const del = () => {
      let input = document.querySelector("#del input");
      xhr.open('delete', 'http://localhost:8090/del?name=' + input.value, true)
      xhr.send()
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            let res = xhr.responseText
            isFirstRender = false
            alert(JSON.parse(res).msg);
            select()
          }
        }
      }
    }
    select()
  </script>
</body>

</html>

🥨后端 python

import pymysql
from flask import Flask,request
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app=app)
app.debug=True
db = pymysql.connect(host='localhost',user='root',password='root',database='python')
cursor = db.cursor() #创建游标
@app.route('/add',methods=['post'])
def add():
  req_data = request.get_data()
  data = json.loads(req_data)
  print(data)
  try:
    sql_data = (data['name'],int(data['age']),data['major'],data['hobby'])
    sql = "insert into userinfo(name,age,major,hobby) values (%s,%s,%s,%s)"
    cursor.execute(sql,sql_data)
    db.commit()
    return {'code':200,'msg':'数据新增成功'}
  except:
    db.rollback()  # 发生错误时回滚 
    return {'code':1000,'msg':"添加失败"}

@app.route('/del',methods=['delete'])
def delete():
  deleteName = request.args.get('name')
  sql=f'delete from `userinfo` where name="{deleteName}";'
  try:
    cursor.execute(sql)
    db.commit()
    return {'code':200,'msg':'删除成功'}
  except:
    db.rollback()  # 发生错误时回滚 
    return {'code':1000,'msg':"删除失败"}
@app.route('/edit',methods=['put'])
def edit():
  req_data = request.get_data()
  data = json.loads(req_data)
  print('修改消息:',data)
  try:
    sql = f"update userinfo set name='{data['afterName']}' where name='{data['beforeName']}'"
    cursor.execute(sql)
    db.commit()
    return {'code':200,'msg':'修改成功'}
  except:
    db.rollback() 
    return {'code':1000,'msg':"修改失败"}

@app.route('/select',methods=['get'])
def select():
  try:
    cursor.execute("SELECT * FROM userinfo")
    array = []
    data=()
    while isinstance(data,tuple):#循环遍历出data的数据
      data = cursor.fetchone() #fetchone方法用于取出数据库中查询的单个数据
      if(data == None): break
      obj = {}
      obj['id'] = data[0]
      obj['name'] = data[1]
      obj['age'] = data[2]
      obj['major'] = data[3]
      obj['hobby'] = data[4]
      array.append(obj)
    return {'code':200,'msg':'查询成功','data':array}
  except:
    db.rollback() 
    return {'code':1000,'msg':"查询失败"}
  
if __name__ == '__main__':
  app.run(host="localhost",port='8090')
  cursor.close()
  db.close()

🍗结语

以上是通过python的flask库来实现前后端分离的一个小示例,现在基本的网页格式都是前后端分离的,因此写后端的时候我们只需要专注于后端接口服务的实现,前端实现数据的显示以及布局。
当然这个示例用flask模块取巧来实现后端比之传统的后端来说简单了很多,不过作为python全栈开发基础来说应该是可以作为示例的。可以通过这个示例去做出自己喜欢的网页,开发一些小系统之类的页面。
文章到此结束,谢谢大家!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐