manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
views.py
from django.shortcuts import render,redirect
from django.http.response import HttpResponse
from shopapp.service.userservice import UserService
from shopapp.service.jobtaskservice import JobTaskService
from shopapp.entity.jobtask import JobTask
import json
import hashlib
from .models import TUser
from .models import JobDept
from django.core import serializers
import os
from datetime import datetime
# Create your views here.
userService = UserService()
jobTaskService = JobTaskService()
def index(request):
return render(request, 'index.html')
pass
def goLogin(request):
return render(request, 'login.html')
pass
def login(request):
userName = request.POST.get('userName')
userPwd = request.POST.get('userPwd')
remeberMe = request.POST.get('rememberMe')
result = userService.findUserByUserName(userName)
isLogin = False
if result and (remeberMe == None or remeberMe == 'false'):
if result[0][2] == hashlib.md5(userPwd.encode(encoding='utf-8')).hexdigest():
isLogin = True
pass
elif result and remeberMe == 'true':
if result[0][2] == userPwd:
isLogin = True
pass
pass
if isLogin:
userItem = {}
userItem['userId'] = result[0][0]
userItem['userName'] = result[0][1]
userItem['userPic'] = result[0][9]
userItem['userRole'] = result[0][10]
request.session['user'] = userItem
response = render(request, 'main.html')
if remeberMe == 'false':
response.set_cookie('userName', userName)
response.set_cookie('userPwd', result[0][2])
response.set_cookie('rememberMe', 'true')
pass
elif remeberMe == None:
response = render(request, 'main.html')
response.delete_cookie('userName')
response.delete_cookie('userPwd')
response.delete_cookie('rememberMe')
pass
return response
else:
return render(request, 'login.html')
pass
def regist(request):
userDict = json.loads(request.body.decode('utf-8'))
'''
user = TUser()
user.user_name = userDict.get('userName') # 表单提交的数据使用request.form[]
user.user_pwd = hashlib.md5((userDict.get('userPwd')).encode(encoding='utf-8')).hexdigest()
user.user_pic = userDict.get('userPic')
user.user_birth = datetime.strptime(userDict.get('userBirth'), '%Y-%m-%d')
user.user_sex = userDict.get('userSex')
user.user_intro = userDict.get('userIntro')
result = user.save()
'''
result = TUser.objects.create(
user_name = userDict.get('userName'),
user_pwd=hashlib.md5((userDict.get('userPwd')).encode(encoding='utf-8')).hexdigest(),
user_pic=userDict.get('userPic'),
user_birth=datetime.strptime(userDict.get('userBirth'), '%Y-%m-%d'),
user_sex=userDict.get('userSex'),
user_intro=userDict.get('userIntro')
)
if result:
result = 1
else:
result = 0
return HttpResponse(json.dumps({'result': result}), content_type="application/json")
pass
def logout(request):
request.session.flush()
return render(request, 'login.html')
pass
def goJobTaskInfo(request):
return render(request, "jobinfo/jobtaskinfo.html")
pass
def getJobTaskInfo(request):
jobTaskData = request.body.decode('utf-8')
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 HttpResponse(json.dumps(returnData), content_type="application/json")
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 HttpResponse(json.dumps(returnData), content_type="application/json")
pass
def getJobSalary(request):
result = jobTaskService.findJobMeanSalary()
returnData = {'code':1, 'salary':result}
r = json.dumps(returnData)
return HttpResponse(json.dumps(returnData), content_type="application/json")
pass
def goAjaxUserInfo(request):
return render(request, "systeminfo/userinfo.html")
pass
def getUserInfo(request):
userData = request.body.decode('utf-8')
userDict = json.loads(userData)
tData = {}
user = TUser()
user.user_name = userDict.get('userName')
user.user_sex = userDict.get('userSex')
currentPage = int(userDict.get('currentPage'))
pageSize = int(userDict.get('pageSize'))
opr = userDict.get('opr')
userId = int(userDict.get('userId'))
user.user_id= userId
user.jobDept_id = int(userDict.get('userDeptId'))
updateResult = 0
if opr == 'del':
updateResult = user.delete()
pass
elif opr == 'update':
tUser = TUser.objects.filter(user_id=userId).values('user_id', 'user_name', 'user_sex', 'jobDept_id', 'jobDept__dept_name')
tData['userId'] = tUser[0].get('user_id')
tData['userName'] = tUser[0].get('user_name')
tData['userSex'] = tUser[0].get('user_sex')
tData['userDeptId'] = tUser[0].get('jobDept_id')
tData['userDeptName'] = tUser[0].get('jobDept__dept_name')
returnData = {'code': 1, 'userData': tData, 'pageSize': pageSize, 'currentPage': currentPage, 'opr':'update'}
return HttpResponse(json.dumps(returnData), content_type="application/json")
elif opr == 'submitUpdate':
currentPage = 1
updateResult = TUser.objects.filter(user_id=userId).update(user_sex=user.user_sex, jobDept_id=user.jobDept_id)
pass
query = TUser.objects
if user.user_name:
query = query.filter(user_name__contains=user.user_name)
if user.user_sex:
query = query.filter(user_sex=user.user_sex)
pass
startRow = (currentPage - 1)*pageSize
endRow = currentPage*pageSize
result = query.values('user_id', 'user_name', 'user_sex', 'jobDept__dept_name')[startRow:endRow] # 会生成 LIMIT 2 OFFSET 1
counts = query.count()
totalPage = 0
if(counts%pageSize == 0):
totalPage = counts//pageSize
else:
totalPage = counts // pageSize + 1
pass
# data = serializers.serialize("json", result, use_natural_foreign_keys=True)
# data = json.loads(data)
data = []
for tempUser in result:
dictItem = {'pk':tempUser.get('user_id')}
fieldsItem ={'user_name':tempUser.get('user_name'), 'user_sex':tempUser.get('user_sex'), 'user_deptname':tempUser.get('jobDept__dept_name')}
dictItem['fields'] = fieldsItem
data.append(dictItem)
pass
'''
for tempUser, tdata in zip(result, data):
tdata['fields']['user_deptname'] = tempUser.jobDept.dept_name # 获取外键关联的时候,是第二次查询
pass
'''
returnData = {'code':1, 'userData':data, 'pageSize':pageSize, 'currentPage':currentPage, 'totalPage':totalPage, 'updateResult':updateResult, 'opr':'search','counts':counts}
return HttpResponse(json.dumps(returnData), content_type="application/json")
pass
def getDeptList(request):
parentId = int(request.GET.get('parentId'))
if parentId ==0:
result = JobDept.objects.filter(dept_parentid__isnull=True).all()
else:
result = JobDept.objects.filter(dept_parentid=parentId).all()
data = serializers.serialize("json", result)
data = json.loads(data)
return HttpResponse(json.dumps({'code':1, 'data':data}), content_type="application/json")
pass
def uploadFile(request):
# 后缀需要检查的
file = request.FILES.get('upload')
if file:
try:
with open(os.path.dirname(__file__) + os.sep + '..' + os.sep + 'static' + os.sep + 'uploads'+ os.sep + file.name, "wb+") as fp:
for chunk in file.chunks():
fp.write(chunk)
pass
except Exception as e:
return HttpResponse(json.dumps({'uploaded': 0, 'fileName': "", 'url': ""}), content_type="application/json")
pass
return HttpResponse(json.dumps({'uploaded': 1, 'fileName':file.name, 'url': os.sep + 'static' + os.sep + 'uploads'+ os.sep + file.name}), content_type="application/json")
else:
return HttpResponse(json.dumps({'uploaded': 0, 'fileName': "", 'url': ""}), content_type="application/json")
pass
def getGoodsType(request):
return render(request,'goodsinfo/goodstypeinfo.html')
pass
def goGoodsInfo(request):
return render(request,'goodsinfo/goodsinfo.html')
pass
def gerGoodsInfo(request):
goodsData = request.body.decode('utf-8')
goodsdict = json.loads(goodsData)
tGoods = TGoods()
tGoods.goods_id = goodsDict.get('goodsId')
tGoods.goods_name = goodsDict.get('currentPage')
startRow = (currentPage - 1)*pageSize
endRow = pageSize*currentPage
querySet = TGoods.objects
if tGoods.goods_name:
querySet.filter(goods_naem__contains = tGoods.goods_name)
pass
pass
models.py
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
class JobDept(models.Model):
dept_id = models.IntegerField(primary_key=True)
dept_name = models.CharField(unique=True, max_length=45, blank=True, null=True)
dept_parentid = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'job_dept'
class TUser(models.Model):
user_id = models.AutoField(db_column='USER_ID', primary_key=True) # Field name made lowercase.
user_name = models.CharField(db_column='USER_NAME', unique=True, max_length=32) # Field name made lowercase.
user_pwd = models.CharField(db_column='USER_PWD', max_length=512) # Field name made lowercase.
user_age = models.IntegerField(db_column='USER_AGE', blank=True, null=True) # Field name made lowercase.
user_sex = models.IntegerField(db_column='USER_SEX', blank=True, null=True) # Field name made lowercase.
user_qq = models.IntegerField(db_column='USER_QQ', blank=True, null=True) # Field name made lowercase.
user_cellphone = models.CharField(db_column='USER_CELLPHONE', max_length=20, blank=True, null=True) # Field name made lowercase.
user_money = models.FloatField(db_column='USER_MONEY', blank=True, null=True) # Field name made lowercase.
user_status = models.IntegerField(db_column='USER_STATUS', blank=True, null=True) # Field name made lowercase.
user_pic = models.CharField(db_column='USER_PIC', max_length=128, blank=True, null=True) # Field name made lowercase.
user_role = models.IntegerField(db_column='USER_ROLE', blank=True, null=True) # Field name made lowercase.
jobDept= models.ForeignKey(JobDept, db_column='', on_delete=models.CASCADE, blank=True, null=True, to_field='dept_id') # null=True生成left join
user_birth = models.DateTimeField(db_column='USER_BIRTH', blank=True, null=True) # Field name made lowercase.
user_intro = models.TextField(db_column='USER_INTRO', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 't_user'
jobtask.py
# 封装数据类 VO:value object entity 类
class JobTask():
def __init__(self):
self.__taskId = None
self.__taskTitle = None
self.__taskURL = None
self.__taskState = None
pass
@property
def taskId(self):
return self.__taskId
pass
@taskId.setter
def taskId(self, taskId):
self.__taskId = taskId
pass
@property
def taskTitle(self):
return self.__taskTitle
pass
@taskTitle.setter
def taskTitle(self, taskTitle):
self.__taskTitle = taskTitle
pass
@property
def taskURL(self):
return self.__taskURL
pass
@taskURL.setter
def taskURL(self, taskURL):
self.__taskURL = taskURL
pass
@property
def taskState(self):
return self.__taskState
pass
@taskState.setter
def taskState(self, taskState):
self.__taskState = taskState
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
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
userdao.py
from .basedao import BaseDao
class UserDao(BaseDao):
def findUserByUserName(self, userName):
try:
sql = "select * from t_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 t_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 t_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 t_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 t_user left join job_dept on t_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 t_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 t_user left join job_dept on t_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 t_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
basedao.py
# 引入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
urls.py
"""djangoproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from shopapp.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('', index),
path('gologin/', goLogin),
path('login/', login),
path('logout/', logout),
path('regist.do', regist),
path('upload.do', uploadFile),
path('goajaxjobtaskinfo/', goJobTaskInfo),
path('ajaxjobtaskinfo/', getJobTaskInfo),
path('ajaxjobsalary/', getJobSalary),
path('goajaxuserinfo/', goAjaxUserInfo),
path('ajaxuserinfo/', getUserInfo),
path('ajaxdeptinfo/', getDeptList),
path('ajaxgoodstypeinfo/', getGoodsType),
path('gogoodsinfo/', goGoodsInfo),
]