这里先提一下,我们运行后端代码之前需要先建立一个名字为python的数据库,而后在该数据库下创建表 userinfo,因为看到有的朋友后端代码拿过去后会运行不起来或者就是直接报错了。至于使用MySQL可视化工具还是用sql语句创建,这个看自己个人的,如果sql不怎么熟练的,甚至没有基础的,可以参考一下自己的这一篇文章MYSQL的增删改查相关操作
相信看过自己前期的博文python使用flask模块和前端交互基础以及python模块pymysql对数据库进行增删改查的小伙伴已经有了一定基础,这里我们在来对flask、pymsql、前端三个部分通过flask做一个整合。使用python来作为我们的后端来实现前后端的分离。
既然是作为基础,那我们这里主要实现通过前端对我们后端数据库实现增删改查就OK 了。下面我们开始。
后端:python(flask,pymsql)、MySQL、navicat、VScode
前端:VScode、Google浏览器
前端上样式没有去做过多的修饰,只是做一个大概样式,有兴趣的也可以自己去用CSS修改一下
可视化截图就截图这两张吧,接下来就是代码了
这里先提一下,这个是需要下载MySQL数据库的,再有一些MySQL数据库的增删改查的代码学习基础。要不然有的代码可能是看不明白的哈,特别是数据库那一块的。restful风格这里对于增删改查使用了不同的方式
增加数据库这里用的也是基本和其它常见后端所用的那种方式,使用了post请求方法,对于前端不是从URL请求上携带的参数,我们都可以使用flask模块中的request的**get_dada()**方法来获取,至于如何取在URL上的数据,可以看下关于【 删除】那里的简介。
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>Documenttitle>
<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>
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中的数据。
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>Documenttitle>
<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>
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() # 关闭数据库连接
修改数据这里就不多说了,直接看源码吧
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>Documenttitle>
<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>
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() # 关闭数据库连接
查看数据这里需要注意一下,修改的数据是需要替换或者新增到我们的表里面,所以需要先删除掉原来的表再替换上新修改或增加的数据。有点前端基础的应该都清楚怎么做。
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>Documenttitle>
<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>IDth>
<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 = `
${element.id}
${element.name}
${element.age}
${element.major}
${element.hobby}
`
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 = `
${element.id}
${element.name}
${element.age}
${element.major}
${element.hobby}
`
tableT.appendChild(tableB)
});
}
}
}
}
}
script>
body>
html>
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() # 关闭数据库连接
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>Documenttitle>
<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>IDth>
<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.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 = `
${element.id}
${element.name}
${element.age}
${element.major}
${element.hobby}
`
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 = `
${element.id}
${element.name}
${element.age}
${element.major}
${element.hobby}
`
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()
}
}
}
}
script>
body>
html>
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()
最后这里忽然感觉也没什么好说的了
如果文章有什么不正确的地方,希望在评论区指出,我们共同进步。谢谢大家