MVC是一种架构设计模式,是一种设计理念。是为了达到分层设计的目的,从而使代码解耦,便于维护和代码的复用。MVC是3个单词的缩写,全称:Model-View-Controller(模型-视图-控制器)。
1、Model
模型层,可以简单理解就是数据层,用于提供数据。在项目中,(简单理解)一般把数据访问和操作,比如将对象关系映射这样的代码作为Model层,也就是对数据库的操作这一些列的代码作为Model层。比如代码中我们会写DAO和DTO类型的代码,那这个DAO和DTO我们可以理解为是属于Model层的代码。
2、View
视图层,就是UI界面,用于跟用户进行交互。一般所有的JSP、Html等页面就是View层。
3、Controller
控制层,Controller层的功能就是将Model和View层进行关联。比如View主要是显示数据的,但是数据又需要Model去访问,这样的话,View会先告诉Controller,然后Controller再告诉Model,Model请求完数据之后,再告诉View。这样View就可以显示数据了。
实现效果:
代码 及结构:
话不多说上代码:
controller
——usercontroller.py
from flask import Blueprint, Flask, render_template,request,session, url_for,Response, jsonify,redirect
import hashlib
from service.userservice import UserService
from entity.user import User
import json
from filter.sessionfilter import sessionFilter
import os
from filter.rolefilter import roleFilter
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) # 业务逻辑层 dao:database access object model
print(result)
if result and result[0][2] == hashlib.md5(userPwd.encode(encoding='utf-8')).hexdigest():
userItem = {}
userItem['userId'] = result[0][0]
userItem['userName'] = result[0][1]
userItem['userPic'] = result[0][9]
userItem['userRole'] = result[0][13]
session['user'] = userItem # session是http协议的状态跟踪技术,http协议是tcp短连接
# sessionDict[sessionid][user]= userItem
print(hashlib.md5('123456'.encode(encoding='utf-8')).hexdigest())
# 登录成功,则保存Cookies信息
resp = Response(render_template('main.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('login.html'))
resp.delete_cookie('userName')
resp.delete_cookie('userPwd')
return resp
pass
@usercontroller.route('/regist.do', methods=['POST', 'GET'])
def regist():
userData = request.get_data()
userDict = json.loads(userData)
user = User()
user.userName = userDict.get('userName') # 表单提交的数据使用request.form[]
user.userPwd = hashlib.md5((userDict.get('userPwd')).encode(encoding='utf-8')).hexdigest()
user.userPic = userDict.get('userPic')
user.userBirth = userDict.get('userBirth')
user.userSex = userDict.get('userSex')
user.userIntro = userDict.get('userIntro')
result = userService.createUser(user)
return json.dumps({'result':result})
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') # 超链接http默认是get请求
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'], endpoint='goAjaxUserInfo')
@sessionFilter
@roleFilter
def goAjaxUserInfo():
return render_template("systeminfo/userinfo.html")
pass
@usercontroller.route('/ajaxuserinfo.do', methods=['POST', 'GET'], endpoint='getUserInfo')
@sessionFilter
@roleFilter
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
user.userDeptId = int(userDict.get('userDeptId'))
updateResult = 0
if opr == 'del':
updateResult = userService.removeUser(userId)
pass
elif opr == 'update':
tUser = userService.findUserByUserId(userId)
tData['userId'] = tUser.userId
tData['userName'] = tUser.userName
tData['userSex'] = tUser.userSex
tData['userDeptId'] = tUser.userDeptId
tData['userDeptName'] = tUser.userDeptName
returnData = {'code': 1, 'userData': tData, 'pageSize': pageSize, 'currentPage': currentPage, 'opr':'update'}
return json.dumps(returnData)
elif opr == 'submitUpdate':
updateResult = 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, 'updateResult':updateResult, 'opr':'search','counts':counts}
return json.dumps(returnData)
pass
@usercontroller.route('/upload.do', methods=['POST', 'GET'], strict_slashes=False)
def uploadFile():
# 后缀需要检查的
file = request.files.get('upload')
if file:
try:
file.save(os.path.dirname(__file__) + os.sep + '..' + os.sep + 'static' + os.sep + 'uploads'+ os.sep + file.filename) # 保存文件到upload目录
except Exception as e:
return json.dumps({'uploaded': 0, 'fileName': "", 'url': ""})
pass
return json.dumps({'uploaded': 1, 'fileName':file.filename, 'url': os.sep + 'static' + os.sep + 'uploads'+ os.sep + file.filename})
else:
return json.dumps({'uploaded': 0, 'fileName': "", 'url': ""})
pass
——jobcontroller.py
from flask import Blueprint, Flask, render_template,request,session, url_for,Response, jsonify
import hashlib
from service.jobtaskservice import JobTaskService
from entity.jobtask import JobTask
import json
from filter.sessionfilter import sessionFilter
jobtaskcontroller = Blueprint('jobtaskcontroller', __name__)
jobTaskService = JobTaskService()
@jobtaskcontroller.route('/goajaxjobtaskinfo.do', methods=['POST', 'GET'])
@sessionFilter
def goJobTaskInfo():
return render_template("jobinfo/jobtaskinfo.html")
pass
@jobtaskcontroller.route('/ajaxjobtaskinfo.do', methods=['POST', 'GET'])
def getJobTaskInfo():
jobTaskData = request.get_data()
jobTaskDict = json.loads(jobTaskData)
tData = {}
jobTask = JobTask()
jobTask.taskTitle = jobTaskDict.get('taskTitle')
jobTask.taskURL = jobTaskDict.get('taskURL')
currentPage = int(jobTaskDict.get('currentPage'))
pageSize = int(jobTaskDict.get('pageSize'))
opr = jobTaskDict.get('opr')
taskId = int(jobTaskDict.get('taskId'))
jobTask.taskId = taskId
updateResult = 0
if opr == 'del':
updateResult = jobTaskService.removeJobTask(taskId)
pass
elif opr == 'update':
tTask = jobTaskService.findJobTaskByJobTaskId(taskId)
tData['taskId'] = tTask.taskId
tData['taskTitle'] = tTask.taskTitle
tData['taskURL'] = tTask.taskURL
returnData = {'code': 1, 'jobTaskData': tData, 'pageSize': pageSize, 'currentPage': currentPage, 'opr':'update'}
return json.dumps(returnData)
elif opr == 'submitUpdate':
updateResult = jobTaskService.updateJobTask(jobTask)
pass
result = jobTaskService.findPageJobTaskList(jobTask, pageSize, currentPage)
counts = jobTaskService.countJobTasks(jobTask)
totalPage = 0
if(counts%pageSize == 0):
totalPage = counts//pageSize
else:
totalPage = counts // pageSize + 1
pass
returnData = {'code':1, 'jobTaskData':result, 'pageSize':pageSize, 'currentPage':currentPage, 'totalPage':totalPage, 'updateResult':updateResult, 'opr':'search','counts':counts}
return json.dumps(returnData)
pass
@jobtaskcontroller.route('/ajaxjobsalary.do', methods=['POST', 'GET'])
def getJobSalary():
result = jobTaskService.findJobMeanSalary()
returnData = {'code':1, 'salary':result}
r = json.dumps(returnData)
return json.dumps(returnData)
pass
dao
——pymysql.json
{"host":"127.0.0.1", "user":"root","password":"root", "database":"db_job_data", "port":3306, "charset":"utf8"}
——basedao.py
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
——userdao.py
from .basedao import BaseDao
class UserDao(BaseDao):
def findUserByUserName(self, userName):
try:
sql = "select * from job_user where user_name=%s"
self.getConnection()
self.execute(sql, (userName,))
result = self.fetch()
finally:
self.close()
return result
pass
def createUser(self, user):
try:
params = [user.userName, user.userPwd]
sql = "insert into job_user (user_name, user_pwd"
values = " values (%s, %s"
if user.userSex:
sql += ",user_sex"
values += ",%s"
params.append(user.userSex)
pass
if user.userPic:
sql += ",user_pic"
values += ",%s"
params.append(user.userPic)
pass
if user.userIntro:
sql += ",user_intro"
values += ",%s"
params.append(user.userIntro)
pass
if user.userBirth:
sql += ",user_birth"
values += ",DATE_FORMAT(%s,'%%Y-%%m-%%d')"
params.append(user.userBirth)
pass
sql +=")" + values + ")"
self.getConnection()
result = self.execute(sql, params)
self.commit() # 执行了sql语句之后要commit
return result
except Exception as e:
print(e)
finally:
self.close()
pass
pass
def findUserList(self, user):
try:
params = []
# sql语句和params就需要是动态
sql = "select * from job_user where 1=1 " # where 1=1是为了便于增加and
if user.userName:
sql += " and user_name like %s " # 模糊查询
params.append('%'+user.userName + '%')
pass
if user.userSex:
sql += " and user_sex=%s"
params.append(user.userSex)
pass
self.getConnection()
self.execute(sql, params)
result = self.fetch()
finally:
self.close()
return result
pass
def removeUser(self, userId):
try:
sql = "delete from job_user where user_id=%s"
self.getConnection()
result = self.execute(sql, (userId, ))
self.commit() # 执行了sql语句之后要commit
return result
finally:
self.close()
pass
pass
def findUserByUserId(self, userId):
try:
sql = "select USER_ID,USER_NAME,USER_PWD,USER_AGE,USER_SEX,USER_QQ,USER_CELLPHONE," \
"USER_MONEY,USER_STATUS,USER_PIC,USER_INTRO,date_format(USER_BIRTH, '%%Y-%%m-%%d'),USER_DEPTID , dept_id, dept_name , user_role " \
"from job_user left join job_dept on job_user.user_deptid=job_dept.dept_id where user_id=%s " # where 1=1是为了便于增
self.getConnection()
self.execute(sql, (userId,))
result = self.fetch()
finally:
self.close()
return result
pass
def updateUser(self, user):
try:
params = [user.userSex]
sql = "update job_user set user_sex=%s "
if user.userDeptId > 0:
sql += ", user_deptid=%s"
params.append(user.userDeptId)
sql += ' where user_id=%s'
params.append(user.userId)
self.getConnection()
result = self.execute(sql, params)
self.commit() # 执行了sql语句之后要commit
return result
except Exception as e:
print(e)
finally:
self.close()
pass
pass
def findPageUserList(self, user, pageSize, currentPage):
try:
params = []
# sql语句和params就需要是动态
sql = "select USER_ID,USER_NAME,USER_PWD,USER_AGE,USER_SEX,USER_QQ,USER_CELLPHONE," \
"USER_MONEY,USER_STATUS,USER_PIC,USER_INTRO,date_format(USER_BIRTH, '%%Y-%%m-%%d'),USER_DEPTID , dept_id, dept_name , user_role " \
"from job_user left join job_dept on job_user.user_deptid=job_dept.dept_id where 1=1 " # where 1=1是为了便于增加and
if user.userName:
sql += " and user_name like %s " # 模糊查询
params.append('%' + user.userName + '%')
pass
if user.userSex:
sql += " and user_sex=%s"
params.append(user.userSex)
pass
startRow = (currentPage - 1)*pageSize
sql += "limit %s, %s"
params.append(startRow)
params.append(pageSize)
self.getConnection()
self.execute(sql, params)
result = self.fetch()
finally:
self.close()
return result
pass
def countUsers(self, user):
params = []
# sql语句和params就需要是动态
sql = "select count(*) from job_user u left join job_dept d on u.user_deptid=d.dept_id where 1=1 " # where 1=1是为了便于增加and
if user.userName:
sql += " and user_name like %s " # 模糊查询
params.append('%' + user.userName + '%')
pass
if user.userSex:
sql += " and user_sex=%s"
params.append(user.userSex)
pass
self.getConnection()
self.execute(sql, params)
result = self.fetchOne()
return result
pass
pass
——jobtaskdao.py
from .basedao import BaseDao
class JobTaskDao(BaseDao):
def createJobTask(self, jobTask):
try:
sql = "insert into job_collect_task (task_title, job_url) values(%s, %s)"
self.getConnection()
result = self.execute(sql, (jobTask.taskTitle, jobTask.taskURL))
self.commit() # 执行了sql语句之后要commit
return result
finally:
self.close()
pass
pass
def findJobTaskList(self, jobTask):
try:
params = []
# sql语句和params就需要是动态
sql = "select * from job_collect_task where 1=1 " # where 1=1是为了便于增加and
if jobTask.taskTitle:
sql += " and task_title like %s " # 模糊查询
params.append('%'+jobTask.taskTitle + '%')
pass
if jobTask.taskURL:
sql += " and task_url=%s"
params.append(jobTask.taskURL)
pass
self.getConnection()
self.execute(sql, params)
result = self.fetch()
finally:
self.close()
return result
pass
def removeJobTask(self, taskId):
try:
sql = "delete from job_collect_task where task_id=%s"
self.getConnection()
result = self.execute(sql, (taskId, ))
self.commit() # 执行了sql语句之后要commit
return result
finally:
self.close()
pass
pass
def findJobTaskByJobTaskId(self, taskId):
try:
sql = "select * from job_collect_task where task_id=%s"
self.getConnection()
self.execute(sql, (taskId,))
result = self.fetch()
finally:
self.close()
return result
pass
def updateJobTask(self, jobTask):
try:
sql = "update job_collect_task set task_title=%s, task_url=%s where task_id=%s"
self.getConnection()
result = self.execute(sql, (jobTask.taskTitle, jobTask.taskURL, jobTask.taskId))
self.commit() # 执行了sql语句之后要commit
return result
finally:
self.close()
pass
pass
def findPageJobTaskList(self, jobTask, pageSize, currentPage):
try:
params = []
# sql语句和params就需要是动态
sql = "select task_id, task_title, task_url from job_collect_task where 1=1 " # where 1=1是为了便于增加and
if jobTask.taskTitle:
sql += " and task_title like %s " # 模糊查询
params.append('%' + jobTask.taskTitle + '%')
pass
if jobTask.taskURL:
sql += " and task_url=%s"
params.append(jobTask.taskURL)
pass
startRow = (currentPage - 1)*pageSize
sql += "limit %s, %s"
params.append(startRow)
params.append(pageSize)
self.getConnection()
self.execute(sql, params)
result = self.fetch()
finally:
self.close()
return result
pass
def countJobTasks(self, jobTask):
params = []
# sql语句和params就需要是动态
sql = "select count(*) from job_collect_task where 1=1 " # where 1=1是为了便于增加and
if jobTask.taskTitle:
sql += " and task_title like %s " # 模糊查询
params.append('%' + jobTask.taskTitle + '%')
pass
if jobTask.taskURL:
sql += " and task_url=%s"
params.append(jobTask.taskURL)
pass
self.getConnection()
self.execute(sql, params)
result = self.fetchOne()
return result
pass
pass
entity
——user.py
# 封装数据类 VO:value object entity 类
class User():
def __init__(self):
self.__userId = None
self.__userName = None
self.__userPwd = None
self.__userSex = None
self.__userPic = None
self.__userBirth = None
self.__userIntro = None
self.__userDeptId = None
self.__userDeptName = None
self.__userRole = 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
@property
def userPic(self):
return self.__userPic
pass
@userPic.setter
def userPic(self, userPic):
self.__userPic = userPic
pass
@property
def userBirth(self):
return self.__userBirth
pass
@userBirth.setter
def userBirth(self, userBirth):
self.__userBirth = userBirth
pass
@property
def userIntro(self):
return self.__userIntro
pass
@userIntro.setter
def userIntro(self, userIntro):
self.__userIntro = userIntro
pass
@property
def userDeptId(self):
return self.__userDeptId
pass
@userDeptId.setter
def userDeptId(self, userDeptId):
self.__userDeptId = userDeptId
pass
@property
def userDeptName(self):
return self.__userDeptName
pass
@userDeptName.setter
def userDeptName(self, userDeptName):
self.__userDeptName = userDeptName
pass
@property
def userRole(self):
return self.__userRole
pass
@userRole.setter
def userRole(self, userRole):
self.__userRole = userRole
pass
pass
filter
防止非法访问过滤器
——rolefilter
from flask import Blueprint, Flask, render_template,request,session, url_for,Response, jsonify
rolefilter = Blueprint('rolefilter', __name__)
def roleFilter(funcs):
adminURL = ['ajaxuserinfo.do','goajaxuserinfo.do']
def innerRole(*args, **kw):
user = session.get('user')
if user:
role = user.get('userRole') # restful
url = request.url
url = url.split('/')[-1]
if role != 1 and url in adminURL:
session.clear()
return render_template("login.html")
pass
return funcs(*args, **kw)
pass
return innerRole
pass
——sessionfilter
from flask import Blueprint, Flask, render_template,request,session, url_for,Response, jsonify
sessionfilter = Blueprint('sessionfilter', __name__)
def sessionFilter(func):
def inner(*args, **kw):
user = session.get('user')
if not user:
return render_template("login.html")
pass
return func(*args, **kw)
pass
return inner
pass
service
——userservice
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]
user.userDeptId = result[0][13]
user.userDeptName = result[0][14]
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
——jobtaskservice
from dao.jobtaskdao import JobTaskDao
from dao.jobpostiondao import JobPositionDao
from entity.jobtask import JobTask
class JobTaskService:
def createJobTask(self, jobTask):
jobTaskDao = JobTaskDao()
return jobTaskDao.createJobTask(jobTask)
pass
def findJobTaskList(self, jobTask):
jobTaskDao = JobTaskDao()
jobTasklist = []
result = jobTaskDao.findJobTaskList(jobTask)
for temp in result:
tjobTask = JobTask()
tjobTask.taskId = temp[0]
tjobTask.taskTitle = temp[1]
tjobTask.taskURL = temp[4]
jobTasklist.append(tjobTask)
pass
return jobTasklist
pass
def removeJobTask(self, taskId):
jobTaskDao = JobTaskDao()
return jobTaskDao.removeJobTask(taskId)
pass
def findJobTaskByJobTaskId(self, taskId):
jobTaskDao = JobTaskDao()
result = jobTaskDao.findJobTaskByJobTaskId(taskId)
jobTask = None
if result:
jobTask = JobTask()
jobTask.taskId = result[0][0]
jobTask.taskTitle = result[0][1]
jobTask.taskURL = result[0][2]
pass
return jobTask
pass
# 修改用户信息
def updateJobTask(self, jobTask):
jobTaskDao = JobTaskDao()
return jobTaskDao.updateJobTask(jobTask)
pass
def findPageJobTaskList(self, jobTask, pageSize, currentPage):
jobTaskDao = JobTaskDao()
return jobTaskDao.findPageJobTaskList(jobTask, pageSize, currentPage)
pass
def countJobTasks(self, jobTask):
jobTaskDao = JobTaskDao()
return jobTaskDao.countJobTasks(jobTask)[0]
pass
def findJobMeanSalary(self):
jpd = JobPositionDao()
return jpd.findPositionClassify()
pass
pass
js
——userdata.js
function getUserData(currentPage, pageSize, opr, userId) {
var userName = document.searchForm.userName.value
var userSex = document.searchForm.userSex.value
var userDeptId = 0
if(opr == 'del'){
if(!confirm('确定要删除吗?')){
return false
}
}else if(opr == 'submitUpdate'){
userName = document.userForm.userName.value
userSex = document.userForm.userSex.value
userId = document.userForm.userId.value
userDeptId = document.userForm.userDeptId.value
currentPage = document.userForm.currentPage.value
pageSize = document.userForm.pageSize.value
}
$.ajax({
type: 'post', // 传数据的方式
url: '/ajaxuserinfo.do',
dataType: 'json', // xml、json、script、html
data:JSON.stringify({
'userName': userName, // $('#userName') == document.getElementById('userName')
'userSex' : userSex,
'userId': userId,
'userDeptId': userDeptId,
'pageSize': pageSize,
'currentPage': currentPage,
'opr': opr // 重用一个ajax请求实现增加删除修改查询 CRUD
}),
error: function(xhr, err){
alert('请求失败,请检查,' + err + '!')
},
success: function(data, textStatus){ // success对应的回调函数的第一个参数,是服务器返回的数据
// data = JSON.parse(data)
if(data.code == 1 && opr != 'update'){
var htmlText = ""
for(var i =0;i ' +
' \n' +
' ' + data.userData[i][0] + ' \n' +
' ' + data.userData[i][1] + ' \n' +
' ' + (data.userData[i][4] == 1 ? '男':'女') + ' \n' +
' ' + data.userData[i][14] + ' \n' +
' \n' +
' ' +
' '+
' \n' +
' \n'
}
pageText = ''+ '当前第' + data.currentPage + '页 总共有' + data.totalPage + '页 ';
if(data.currentPage <= 1) {
pageText += '首页 上一页 ';
}else{
pageText += '首页 ' +
'上一页 ';
}
if(data.currentPage >= data.totalPage){
pageText += '下一页 尾页 ';
}else {
pageText += '下一页 ' +
'尾页 ';
}
pageText +='总共有'+ data.counts + '条 '
$('#dataBody').empty()
$('#dataBody').append(htmlText)
$('#dataBody').append(pageText)
document.searchForm.currentPage.value = data.currentPage
document.searchForm.pageSize.value=data.pageSize
if( opr != 'search' && data.updateResult > 0 ) {
alert("操作成功")
$('#modal-default').modal('hide')
}else if(opr != 'search' && data.updateResult <= 0){
alert("操作失败")
}
}else if(data.code == 1 && opr == 'update'){
document.userForm.userName.value = data.userData.userName
if(data.userData.userSex == 1){
document.getElementById('male').checked = 'checked'
}else if(data.userData.userSex == 2){
document.getElementById('female').checked = 'checked'
}
document.userForm.userId.value = data.userData.userId
$('#userDept').html(data.userData.userDeptName)
document.userForm.userDeptId.value = data.userData.userDeptId
document.userForm.currentPage.value = data.currentPage
document.userForm.pageSize.value = data.pageSize
$('#modal-default').modal()
getDeptList(0, null, 1)
}
}
});
}
function getDeptList(parentId, obj, grade){
if(parentId == -1){
parentId = obj.value
document.userForm.userDeptId.value = obj.value
}else if(parentId == -99 || grade == 4){
return false
}
$.ajax({
type: 'get', // 传数据的方式
url: '/getdeptlist.do',
data:{
'parentId': parentId, // $('#userName') == document.getElementById('userName')
},
error: function (xhr, err) {
alert('请求失败,请检查,' + err + '!')
},
success: function (data, textStatus) { // success对应的回调函数的第一个参数,是服务器返回的数据
data = JSON.parse(data)
if(parentId == 0){
if(data.code == 1){
htmlText = ''
for(var i=0;i' + data.data[i][1] + ''
}
$('#parentDept').html(htmlText)
}
}else{
if(data.code == 1 && grade == 2){
if(document.getElementById('gradeTwoDept')){
$('#gradeTwoDept').remove()
}
if(document.getElementById('gradeTreeDept')){
$('#gradeTreeDept').remove()
}
htmlText = '"
$('#deptContainer').append(htmlText)
}else if(data.code == 1 && grade == 3){
if(document.getElementById('gradeTreeDept')){
$('#gradeTreeDept').remove()
}
htmlText = '"
$('#deptContainer').append(htmlText)
}
}
}
})
}
$(document).ready(
function(){
getUserData(1, 10, 'search', 0)
}
)
——jobtask.js
function getJobTaskData(currentPage, pageSize, opr, taskId) {
var taskTitle = document.searchForm.taskTitle.value
var taskURL = document.searchForm.taskURL.value
if(opr == 'del'){
if(!confirm('确定要删除吗?')){
return false
}
}else if(opr == 'submitUpdate'){
taskTitle = document.taskForm.taskTitle.value
taskURL = document.taskForm.taskURL.value
taskId = document.taskForm.taskId.value
currentPage = document.taskForm.currentPage.value
pageSize = document.taskForm.pageSize.value
$('#modal-default').modal('hide')
}
$.ajax({
type: 'post', // 传数据的方式
url: '/ajaxjobtaskinfo.do',
dataType: 'json', // xml、json、script、html
data:JSON.stringify({
'taskTitle': taskTitle, // $('#taskTitle') == document.getElementById('taskTitle')
'taskURL' : taskURL,
'taskId': taskId,
'pageSize': pageSize,
'currentPage': currentPage,
'opr': opr
}),
error: function(xhr, err){
alert('请求失败,请检查,' + err + '!')
},
success: function(data, textStatus){ // success对应的回调函数的第一个参数,是服务器返回的数据
// 查询后、删除后、修改后都走这个if
if(data.code == 1 && opr != 'update'){
var htmlText = ""
for(var i =0;i ' +
' \n' +
' ' + data.jobTaskData[i][0] + ' \n' +
' ' + data.jobTaskData[i][1] + ' \n' +
' ' + data.jobTaskData[i][2] + ' \n' +
' \n' +
' ' +
' '+
' \n' +
' \n'
}
pageText = ''+ '当前第' + data.currentPage + '页 总共有' + data.totalPage + '页 ';
if(data.currentPage <= 1) {
pageText += '首页 上一页 ';
}else{
pageText += '首页 ' +
'上一页 ';
}
if(data.currentPage >= data.totalPage){
pageText += '下一页 尾页 ';
}else {
pageText += '下一页 ' +
'尾页 ';
}
pageText +='总共有'+ data.counts + '条 '
$('#dataBody').empty()
$('#dataBody').append(htmlText)
$('#dataBody').append(pageText)
document.searchForm.currentPage.value = data.currentPage
document.searchForm.pageSize.value=data.pageSize
if( opr != 'search' && data.updateResult > 0 ) {
alert("操作成功")
}else if(opr != 'search' && data.updateResult <= 0){
alert("操作失败")
}
}else if(data.code == 1 && opr == 'update'){
document.taskForm.taskTitle.value = data.jobTaskData.taskTitle
document.taskForm.taskURL.value = data.jobTaskData.taskURL
document.taskForm.taskId.value = data.jobTaskData.taskId
document.taskForm.currentPage.value = data.currentPage
document.taskForm.pageSize.value = data.pageSize
$('#modal-default').modal()
}
}
});
}
$(document).ready(
function(){
getJobTaskData(1, 10, 'search', 0)
}
)
前端页面:
top.html
智能职位数据分析平台
Job
Hutter
职位数据分析平台
left.html
main.html
{% include 'top.html' %}
{% include 'left.html' %}
{% include 'footer.html' %}
login.html
登录
userinfo.html
{% include 'top.html' %}
{% include 'left.html' %}
系统管理
用户信息管理
用户信息
{
{ message }}
用户ID
用户名
用户性别
部门
操作
{% include 'footer.html' %}
userinfo_fresh.html
用户管理
{
{ message }}
用户ID
用户名
用户性别
操作
{% for user in userList %}
{
{ user.userId }}
{
{ user.userName }}
{
{ user.userSex }}
删除
修改
{% endfor %}
footer.html
jobtaskinfo.html
{% include 'top.html' %}
{% include 'left.html' %}
系统管理
任务信息管理
任务信息
{
{ message }}
任务ID
任务名称
操作
{% include 'footer.html' %}
程序启动入口: app.py
from flask import Flask, render_template,request,session, url_for,Response
import config
from config_class import *
from datetime import timedelta
from controller.usercontroller import usercontroller
from filter.sessionfilter import sessionfilter
from controller.jobcontroller import jobtaskcontroller
from controller.deptcontroller import deptcontroller
from controller.goodscontroller import goodscontroller
from controller.goodstypecontroller import goodstypecontroller
from filter.rolefilter import rolefilter
import hashlib
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'AAAGGGGCCFDDDFFFDDDD'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30) #设置session的保存时间。
# 是使用config py文件定义配置
app.config.from_object(config)
# 是使用class定义配置
app.config.from_object(DebugConfig)
app.register_blueprint(usercontroller) # 声明
app.register_blueprint(jobtaskcontroller)
app.register_blueprint(deptcontroller)
app.register_blueprint(goodscontroller)
app.register_blueprint(goodstypecontroller)
@app.route('/') # URL路由
def index():
print(session.get('user'))
return render_template('index.html')
@app.route('/main') # URL路由
def main():
return render_template('main.html')
pass
if __name__ == '__main__':
app.run(host=app.config['SERVER_ADDR'], port=app.config['SERVER_PORT'], debug=True)
'''
关于 PyCharm2018 后续版本中修改 host port 以及 Debug
本人在使用 PyCharm 时,普通教程中给出的修改 host,port 以及 debug 方法都不能在我这里体现出来,
搜索“flask 无法修改服务器端口”,“flask 无法修改 host 和 port ” 以及 “flask cannot change
port or host ” 这样的字段半天之后,终于找到了解决方案
修改 Debug 模式需要点击右上角运行按钮左侧,选择 Edit-Configuration 找到 FLASK_DEBUG 打上勾即可
修改 host 以及 port 有两种方式
1. 修改app.run()代码如下
if __name__ == '__main__'
app.run(host='x.x.x.x',port=8000)
然后进入cmd,找到 app.py 文件所在的位置
'''
有什么不足,还请大神多多指点!