使用flask中的ajax技术实现简单的增删改查这里写部分代码作为参考
- 在web网页中写好脚本 提供一个可视化操作界面
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户管理</title> <script type="text/javascript" src="{{ url_for('static',filename='js/jquery-3.2.1.min.js') }}"></script> <script type="text/javascript" src="{{ url_for('static',filename='js/formvalidator.js') }}"></script> </head> <body> <form action="/gouserinfo.do" method="post"> 用户名:<input type="text" name="userName" /> 性别:<input type="text" name="userSex" /> <input type="submit" value="查询"> </form> <table align="center"> <caption>{{ message }}</caption> <thead> <tr> <th> <input type="button" value="全选"/> <input type="button" value="反选"/> </th> <th>用户ID</th> <th>用户名</th> <th>用户性别</th> <th>操作</th> </tr> </thead> <tbody> {% for user in userList %} <tr> <td align="center"><input type="checkbox" name="userId" value="{{ user.userId }}" /></td> <td>{{ user.userId }}</td> <td>{{ user.userName }}</td> <td>{{ user.userSex }}</td> <td> <a href="javascript:submitRemoveUser('{{ user.userId }}')">删除</a> <a href="/gomodifyuser.do?userId={{ user.userId }}">修改</a> </td> </tr> {% endfor %} </tbody> </table> </body> </html>
- userservice.py脚本文件中写入修改数据库数据信息的脚本方法
-
from dao.userdao import UserDao from entity.user import User class UserService: def findUserByUserName(self, userName): userDao = UserDao() return userDao.findUserByUserName(userName) pass def createUser(self, user): userDao = UserDao() return userDao.createUser(user) pass def findUserList(self, user): userDao = UserDao() userlist = [] result = userDao.findUserList(user) for temp in result: tuser = User() tuser.userId = temp[0] tuser.userName = temp[1] tuser.userSex = temp[4] userlist.append(tuser) pass return userlist pass def removeUser(self, userId): userDao = UserDao() return userDao.removeUser(userId) pass def findUserByUserId(self, userId): userDao = UserDao() result = userDao.findUserByUserId(userId) user = None if result: user = User() user.userId = result[0][0] user.userName = result[0][1] user.userSex = result[0][4] pass return user pass # 修改用户信息 def updateUser(self, user): userDao = UserDao() return userDao.updateUser(user) pass def findPageUserList(self, user, pageSize, currentPage): userDao = UserDao() return userDao.findPageUserList(user, pageSize, currentPage) pass def countUsers(self, user): userDao = UserDao() return userDao.countUsers(user)[0] pass pass
- 在user.py脚本文件中定义修改数据的函数
-
# 封装数据类 VO:value object entity 类 class User(): def __init__(self): self.__userId = None self.__userName = None self.__userPwd = None self.__userSex = None pass @property def userId(self): return self.__userId pass @userId.setter def userId(self, userId): self.__userId = userId pass @property def userName(self): return self.__userName pass @userName.setter def userName(self, userName): self.__userName = userName pass @property def userPwd(self): return self.__userPwd pass @userPwd.setter def userPwd(self, userPwd): self.__userPwd = userPwd pass @property def userSex(self): return self.__userSex pass @userSex.setter def userSex(self, userSex): self.__userSex = userSex pass pass
- 在basedao.py脚本文件中写入用于执行sql语句的通用方法,sql注入
-
# 引入pymysql import pymysql import json import logging import os class BaseDao(): # DAO: database access object def __init__(self, configFile='pymysql.json'): self.__connection = None self.__cursor = None self.__config = json.load(open(os.path.dirname(__file__) + os.sep + configFile, 'r')) # 通过json配置获得数据的连接配置信息 print(self.__config) pass # 获取数据库连接的方法 def getConnection(self): # 当有连接对象时,直接返回连接对象 if self.__connection: return self.__connection # 否则通过建立新的连接对象 try: self.__connection = pymysql.connect(**self.__config) return self.__connection except pymysql.MySQLError as e: print("Exception:" + str(e)) pass pass # 用于执行sql语句的通用方法 # sql注入 def execute(self, sql, params=None): try: self.__cursor = self.getConnection().cursor() # result返回sql语句影响到的条数 if params: # 带参数sql语句 result = self.__cursor.execute(sql, params) else: # 不带参数sql语句 result = self.__cursor.execute(sql) return result except (pymysql.MySQLError, pymysql.DatabaseError, Exception) as e: print("出现数据库访问异常:" + str(e)) self.rollback() pass finally: pass pass def fetch(self): if self.__cursor: return self.__cursor.fetchall() pass def fetchOne(self): if self.__cursor: return self.__cursor.fetchone() pass def commit(self): if self.__connection: self.__connection.commit() pass def rollback(self): if self.__connection: self.__connection.rollback() pass # 返回最后的自增主键 def getLastRowId(self): if self.__cursor: return self.__cursor.lastrowid pass def close(self): if self.__cursor: self.__cursor.close() if self.__connection: self.__connection.close() pass pass
- 在usercontroller.py脚本文件中写修改数据的方法
from flask import Blueprint, Flask, render_template,request,session, url_for,Response, jsonify
import hashlib
from service.userservice import UserService
from entity.user import User
import json
usercontroller = Blueprint('usercontroller', __name__)
userService = UserService()
@usercontroller.route("/login.do", methods=['POST', 'GET'])
def login():
userName = request.form.get('userName') # 表单提交的数据使用request.form[]
userPwd = request.form.get('userPwd')
result = userService.findUserByUserName(userName)
print(result)
if result and result[0][2] == userPwd:
session['user'] = userName
print(hashlib.md5('123456'.encode(encoding='utf-8')).hexdigest())
# 登录成功,则保存Cookies信息
resp = Response(render_template('index.html', messasge='登录成功'))
resp.set_cookie('userName', userName, max_age=7*24*3600)
resp.set_cookie('userPwd', userPwd, max_age=7*24*3600)
return resp
pass
elif result and result[2] != userPwd:
return render_template('login.html', message='用户名或密码错误')
pass
return render_template('login.html')
pass
@usercontroller.route('/logout.do', methods=['POST', 'GET'])
def logout():
session.clear()
print('==========', session.get('user'))
resp = Response(render_template('index.html'))
resp.delete_cookie('userName')
resp.delete_cookie('userPwd')
return resp
pass
@usercontroller.route('/goregist.do')
def goRegist():
return render_template('regist.html')
pass
@usercontroller.route('/regist.do', methods=['POST', 'GET'])
def regist():
userName = request.form.get('userName') # 表单提交的数据使用request.form[]
userPwd = request.form.get('userPwd')
user = User()
user.userName = userName
user.userPwd = userPwd
result = userService.createUser(user)
if result > 0:
return render_template('login.html', message='注册成功')
pass
else:
return render_template('regist.html', message='注册失败')
pass
pass
# 查询用户,并且显示
@usercontroller.route('/gouserinfo.do', methods=['POST', 'GET'])
def goUserInfo():
userName = request.form.get('userName')
userSex = request.form.get('userSex')
user = User()
user.userName = userName
user.userSex = userSex
userList = userService.findUserList(user)
return render_template('systeminfo/userinfo.html', userList = userList, user=user)
pass
# 删除用户,并且显示
@usercontroller.route('/removeruser.do', methods=['POST', 'GET'])
def goRemoveUser():
userId = request.args.get('userId')
userName = request.form.get('userName')
userSex = request.form.get('userSex')
user = User()
user.userName = userName
user.userSex = userSex
result = userService.removeUser(userId)
userList = userService.findUserList(user)
return render_template('systeminfo/userinfo.html', userList = userList, message='删除成功' if result >0 else '删除失败')
pass
@usercontroller.route('/gomodifyuser.do', methods=['POST', 'GET'])
def goModifyUser():
userId = request.args.get('userId')
user = userService.findUserByUserId(userId)
return render_template('systeminfo/modifyuser.html', user=user)
pass
@usercontroller.route('/gomodifysubmit.do', methods=['POST', 'GET'])
def goSubmitModifyUser():
userId = request.form.get('userId')
userName = request.form.get('userName')
userSex = request.form.get('userSex')
user = User()
user.userName = userName
user.userSex = userSex
user.userId = userId
result = userService.updateUser(user)
userList = userService.findUserList(user)
return render_template('systeminfo/userinfo.html', userList=userList, message='修改成功' if result > 0 else '修改失败')
pass
@usercontroller.route('/checkusername.do', methods=['POST', 'GET'])
def checkUserName():
userData = request.get_data()
userDict = json.loads(userData)
user = userService.findUserByUserName(userDict.get('userName'))
dicts = {}
if user:
dicts = {'code':1}
pass
else:
dicts = {'code':0}
pass
return json.dumps(dicts)
pass
@usercontroller.route('/goajaxuserinfo.do', methods=['POST', 'GET'])
def goAjaxUserInfo():
return render_template("systeminfo/userinfoajax.html")
pass
@usercontroller.route('/ajaxuserinfo.do', methods=['POST', 'GET'])
def getUserInfo():
userData = request.get_data()
userDict = json.loads(userData)
tData = {}
user = User()
user.userName = userDict.get('userName')
user.userSex = userDict.get('userSex')
currentPage = int(userDict.get('currentPage'))
pageSize = int(userDict.get('pageSize'))
opr = userDict.get('opr')
userId = int(userDict.get('userId'))
user.userId = userId
delResult = 0
if opr == 'del':
delResult = userService.removeUser(userId)
pass
elif opr == 'update':
tUser = userService.findUserByUserId(userId)
tData['userId'] = tUser.userId
tData['userName'] = tUser.userName
tData['userSex'] = tUser.userSex
returnData = {'code': 1, 'userData': tData, 'pageSize': pageSize, 'currentPage': currentPage, 'opr':'update'}
return json.dumps(returnData)
elif opr == 'submitUpdate':
userService.updateUser(user)
pass
result = userService.findPageUserList(user, pageSize, currentPage)
counts = userService.countUsers(user)
totalPage = 0
if(counts%pageSize == 0):
totalPage = counts//pageSize
else:
totalPage = counts // pageSize + 1
pass
returnData = {'code':1, 'userData':result, 'pageSize':pageSize, 'currentPage':currentPage, 'totalPage':totalPage, 'delcode':delResult, 'opr':'search'}
return json.dumps(returnData)
pass
实现的大致效果图:
这里的代码只是其中的一些关键部分 真正的完整实现还需要大量代码完善其中的细节这里提供一些仅供参考。
有不足请指正!