💕💕作者:计算机源码社
💕💕个人简介:本人七年开发经验,擅长Java、微信小程序、Python、Android等,大家有这一块的问题可以一起交流!
💕💕学习资料、程序开发、技术解答、代码讲解、文档报告
1、绪论
1.1 项目背景
目前在本课题范围内,分析了汽车维修管理人员对汽车的管理现状和现有的用户对汽车维修管理人员的服务的要求。针对两者的要求,设计了一套基于Django的汽车维修保养系统。本系统的集成开发环境是Pycharm,使用MySQL作为数据库管理系统实现。系统具有专门的供用户使用和专门供汽车维修管理人员使用。python汽车维修管理系统,首页展示汽车维修管理系统的欢迎界面,管理员对车辆进行管理、查看、修改等操作,车辆对自己信息进行查看、修改等操作,对于用户而言可体验日常汽车管理的流程以及在线查询汽车的信息。
2、核心功能模块
Python基于Django的汽车维修保养系统采用Django框架,Python语言进行设计,后台上采用Mysql数据库。
Python基于Django的汽车维修保养系统的主要使用者分为管理员、员工、维修人员、用户,实现功能包括:
①用户:注册、登录、查看汽车信息、在线预约维修、查看维修单、查看维修台账信息等功能。
②管理员:登录、个人信息管理、用户管理、员工管理、维修人员管理、维修项目类型管理、维修项目管理、车辆信息管理、维修预约管理、汽车维修单管理、配件领用管理、汽车维修台账管理、汽车配件类型管理、汽车配件库存管理、采购进货管理、配件申请管理、配件统计、采购统计等功能。
③员工:登录、个人信息管理、维修项目管理、车辆信息管理、维修预约管理、汽车维修单管理、配件领用管理、汽车维修台账管理汽车配件库存管理、采购进货管理、配件申请管理等功能。
④维修人员:登录、个人信息管理、维修预约管理、汽车维修单管理、配件领用管理、汽车维修台账管理、汽车配件库存管理、配件申请管理等功能。
3、项目页面展示
4、 核心代码
4.1 维修预约
#coding:utf-8
__author__ = "ila"
import base64, copy, logging, os, time, xlrd
from django.http import JsonResponse
from django.apps import apps
from django.db.models.aggregates import Count,Sum
from .models import weixiuyuyue
from util.codes import *
from util.auth import Auth
from util.common import Common
import util.message as mes
from django.db import connection
import random
from django.core.mail import send_mail
from alipay import AliPayConfig, AliPay
from django.conf import settings
from django.shortcuts import redirect
def weixiuyuyue_register(request):
if request.method in ["POST", "GET"]:
msg = {'code': normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
error = weixiuyuyue.createbyreq(weixiuyuyue, weixiuyuyue, req_dict)
if error != None:
msg['code'] = crud_error_code
msg['msg'] = "用户已存在,请勿重复注册!"
return JsonResponse(msg)
def weixiuyuyue_login(request):
if request.method in ["POST", "GET"]:
msg = {'code': normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
datas = weixiuyuyue.getbyparams(weixiuyuyue, weixiuyuyue, req_dict)
if not datas:
msg['code'] = password_error_code
msg['msg'] = mes.password_error_code
return JsonResponse(msg)
try:
__sfsh__= weixiuyuyue.__sfsh__
except:
__sfsh__=None
if __sfsh__=='是':
if datas[0].get('sfsh')=='否':
msg['code']=other_code
msg['msg'] = "账号已锁定,请联系管理员审核!"
return JsonResponse(msg)
req_dict['id'] = datas[0].get('id')
return Auth.authenticate(Auth, weixiuyuyue, req_dict)
def weixiuyuyue_logout(request):
if request.method in ["POST", "GET"]:
msg = {
"msg": "登出成功",
"code": 0
}
return JsonResponse(msg)
def weixiuyuyue_resetPass(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
columns= weixiuyuyue.getallcolumn( weixiuyuyue, weixiuyuyue)
try:
__loginUserColumn__= weixiuyuyue.__loginUserColumn__
except:
__loginUserColumn__=None
username=req_dict.get(list(req_dict.keys())[0])
if __loginUserColumn__:
username_str=__loginUserColumn__
else:
username_str=username
if 'mima' in columns:
password_str='mima'
else:
password_str='password'
init_pwd = '123456'
recordsParam = {}
recordsParam[username_str] = req_dict.get("username")
records=weixiuyuyue.getbyparams(weixiuyuyue, weixiuyuyue, recordsParam)
if len(records)<1:
msg['code'] = 400
msg['msg'] = '用户不存在'
return JsonResponse(msg)
eval('''weixiuyuyue.objects.filter({}='{}').update({}='{}')'''.format(username_str,username,password_str,init_pwd))
return JsonResponse(msg)
def weixiuyuyue_session(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}
req_dict={"id":request.session.get('params').get("id")}
msg['data'] = weixiuyuyue.getbyparams(weixiuyuyue, weixiuyuyue, req_dict)[0]
return JsonResponse(msg)
def weixiuyuyue_default(request):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
req_dict.update({"isdefault":"是"})
data=weixiuyuyue.getbyparams(weixiuyuyue, weixiuyuyue, req_dict)
if len(data)>0:
msg['data'] = data[0]
else:
msg['data'] = {}
return JsonResponse(msg)
def weixiuyuyue_page(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
#获取全部列名
columns= weixiuyuyue.getallcolumn( weixiuyuyue, weixiuyuyue)
#当前登录用户所在表
tablename = request.session.get("tablename")
#authColumn=list(__authTables__.keys())[0]
#authTable=__authTables__.get(authColumn)
# if authTable==tablename:
#params = request.session.get("params")
#req_dict[authColumn]=params.get(authColumn)
'''__authSeparate__此属性为真,params添加userid,后台只查询个人数据'''
try:
__authSeparate__=weixiuyuyue.__authSeparate__
except:
__authSeparate__=None
if __authSeparate__=="是":
tablename=request.session.get("tablename")
if tablename!="users" and 'userid' in columns:
try:
req_dict['userid']=request.session.get("params").get("id")
except:
pass
#当项目属性hasMessage为”是”,生成系统自动生成留言板的表messages,同时该表的表属性hasMessage也被设置为”是”,字段包括userid(用户id),username(用户名),content(留言内容),reply(回复)
#接口page需要区分权限,普通用户查看自己的留言和回复记录,管理员查看所有的留言和回复记录
try:
__hasMessage__=weixiuyuyue.__hasMessage__
except:
__hasMessage__=None
if __hasMessage__=="是":
tablename=request.session.get("tablename")
if tablename!="users":
req_dict["userid"]=request.session.get("params").get("id")
# 判断当前表的表属性isAdmin,为真则是管理员表
# 当表属性isAdmin=”是”,刷出来的用户表也是管理员,即page和list可以查看所有人的考试记录(同时应用于其他表)
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
# 当前表也是有管理员权限的表
if __isAdmin__ == "是":
if req_dict.get("userid"):
del req_dict["userid"]
else:
#非管理员权限的表,判断当前表字段名是否有userid
if tablename!="users" and 'weixiuyuyue'[:7]!='discuss'and "userid" in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue):
req_dict["userid"] = request.session.get("params").get("id")
#当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
try:
__authTables__=weixiuyuyue.__authTables__
except:
__authTables__=None
if __authTables__!=None and __authTables__!={}:
try:
del req_dict['userid']
except:
pass
for authColumn,authTable in __authTables__.items():
if authTable==tablename:
params = request.session.get("params")
req_dict[authColumn]=params.get(authColumn)
break
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] =weixiuyuyue.page(weixiuyuyue, weixiuyuyue, req_dict, request)
return JsonResponse(msg)
def weixiuyuyue_autoSort(request):
'''
.智能推荐功能(表属性:[intelRecom(是/否)],新增clicktime[前端不显示该字段]字段(调用info/detail接口的时候更新),按clicktime排序查询)
主要信息列表(如商品列表,新闻列表)中使用,显示最近点击的或最新添加的5条记录就行
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
if "clicknum" in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue):
req_dict['sort']='clicknum'
else:
req_dict['sort']='clicktime'
req_dict['order']='desc'
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] = weixiuyuyue.page(weixiuyuyue,weixiuyuyue, req_dict)
return JsonResponse(msg)
def weixiuyuyue_list(request):
'''
前台分页
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
#获取全部列名
columns= weixiuyuyue.getallcolumn( weixiuyuyue, weixiuyuyue)
#表属性[foreEndList]前台list:和后台默认的list列表页相似,只是摆在前台,否:指没有此页,是:表示有此页(不需要登陆即可查看),前要登:表示有此页且需要登陆后才能查看
try:
__foreEndList__=weixiuyuyue.__foreEndList__
except:
__foreEndList__=None
if __foreEndList__=="前要登":
tablename=request.session.get("tablename")
if tablename!="users" and 'userid' in columns:
try:
req_dict['userid']=request.session.get("params").get("id")
except:
pass
#forrEndListAuth
try:
__foreEndListAuth__=weixiuyuyue.__foreEndListAuth__
except:
__foreEndListAuth__=None
#authSeparate
try:
__authSeparate__=weixiuyuyue.__authSeparate__
except:
__authSeparate__=None
if __foreEndListAuth__ =="是" and __authSeparate__=="是":
tablename=request.session.get("tablename")
if tablename!="users":
req_dict['userid']=request.session.get("params",{"id":0}).get("id")
tablename = request.session.get("tablename")
if tablename == "users" and req_dict.get("userid") != None:#判断是否存在userid列名
del req_dict["userid"]
else:
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
if __isAdmin__ == "是":
if req_dict.get("userid"):
del req_dict["userid"]
else:
#非管理员权限的表,判断当前表字段名是否有userid
if "userid" in columns:
try:
# 本接口可以匿名访问,所以try判断是否为匿名
req_dict['userid']=request.session.get("params").get("id")
except:
pass
#当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
try:
__authTables__=weixiuyuyue.__authTables__
except:
__authTables__=None
if __authTables__!=None and __authTables__!={} and __foreEndListAuth__=="是":
try:
del req_dict['userid']
except:
pass
for authColumn,authTable in __authTables__.items():
if authTable==tablename:
params = request.session.get("params")
req_dict[authColumn]=params.get(authColumn)
break
if weixiuyuyue.__tablename__[:7]=="discuss":
try:
del req_dict['userid']
except:
pass
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] = weixiuyuyue.page(weixiuyuyue, weixiuyuyue, req_dict)
return JsonResponse(msg)
def weixiuyuyue_save(request):
'''
后台新增
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
if 'clicktime' in req_dict.keys():
del req_dict['clicktime']
tablename=request.session.get("tablename")
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
#获取全部列名
columns= weixiuyuyue.getallcolumn( weixiuyuyue, weixiuyuyue)
if tablename!='users' and req_dict.get("userid")!=None and 'userid' in columns and __isAdmin__!='是':
params=request.session.get("params")
req_dict['userid']=params.get('id')
error= weixiuyuyue.createbyreq(weixiuyuyue,weixiuyuyue, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def weixiuyuyue_add(request):
'''
前台新增
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
#获取全部列名
columns= weixiuyuyue.getallcolumn( weixiuyuyue, weixiuyuyue)
try:
__authSeparate__=weixiuyuyue.__authSeparate__
except:
__authSeparate__=None
if __authSeparate__=="是":
tablename=request.session.get("tablename")
if tablename!="users" and 'userid' in columns:
try:
req_dict['userid']=request.session.get("params").get("id")
except:
pass
try:
__foreEndListAuth__=weixiuyuyue.__foreEndListAuth__
except:
__foreEndListAuth__=None
if __foreEndListAuth__ and __foreEndListAuth__!="否":
tablename=request.session.get("tablename")
if tablename!="users":
req_dict['userid']=request.session.get("params").get("id")
error= weixiuyuyue.createbyreq(weixiuyuyue,weixiuyuyue, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def weixiuyuyue_thumbsup(request,id_):
'''
点赞:表属性thumbsUp[是/否],刷表新增thumbsupnum赞和crazilynum踩字段,
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
id_=int(id_)
type_=int(req_dict.get("type",0))
rets=weixiuyuyue.getbyid(weixiuyuyue,weixiuyuyue,id_)
update_dict={
"id":id_,
}
if type_==1:#赞
update_dict["thumbsupnum"]=int(rets[0].get('thumbsupnum'))+1
elif type_==2:#踩
update_dict["crazilynum"]=int(rets[0].get('crazilynum'))+1
error = weixiuyuyue.updatebyparams(weixiuyuyue,weixiuyuyue, update_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def weixiuyuyue_info(request,id_):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
data = weixiuyuyue.getbyid(weixiuyuyue,weixiuyuyue, int(id_))
if len(data)>0:
msg['data']=data[0]
#浏览点击次数
try:
__browseClick__= weixiuyuyue.__browseClick__
except:
__browseClick__=None
if __browseClick__=="是" and "clicknum" in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue):
try:
clicknum=int(data[0].get("clicknum",0))+1
except:
clicknum=0+1
click_dict={"id":int(id_),"clicknum":clicknum}
ret=weixiuyuyue.updatebyparams(weixiuyuyue,weixiuyuyue,click_dict)
if ret!=None:
msg['code'] = crud_error_code
msg['msg'] = ret
return JsonResponse(msg)
def weixiuyuyue_detail(request,id_):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
data =weixiuyuyue.getbyid(weixiuyuyue,weixiuyuyue, int(id_))
if len(data)>0:
msg['data']=data[0]
#浏览点击次数
try:
__browseClick__= weixiuyuyue.__browseClick__
except:
__browseClick__=None
if __browseClick__=="是" and "clicknum" in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue):
try:
clicknum=int(data[0].get("clicknum",0))+1
except:
clicknum=0+1
click_dict={"id":int(id_),"clicknum":clicknum}
ret=weixiuyuyue.updatebyparams(weixiuyuyue,weixiuyuyue,click_dict)
if ret!=None:
msg['code'] = crud_error_code
msg['msg'] = retfo
return JsonResponse(msg)
def weixiuyuyue_update(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
if req_dict.get("mima") and req_dict.get("password"):
if "mima" not in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue) :
del req_dict["mima"]
if "password" not in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue) :
del req_dict["password"]
try:
del req_dict["clicknum"]
except:
pass
error = weixiuyuyue.updatebyparams(weixiuyuyue, weixiuyuyue, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def weixiuyuyue_delete(request):
'''
批量删除
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
error=weixiuyuyue.deletes(weixiuyuyue,
weixiuyuyue,
req_dict.get("ids")
)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def weixiuyuyue_vote(request,id_):
'''
浏览点击次数(表属性[browseClick:是/否],点击字段(clicknum),调用info/detail接口的时候后端自动+1)、投票功能(表属性[vote:是/否],投票字段(votenum),调用vote接口后端votenum+1)
统计商品或新闻的点击次数;提供新闻的投票功能
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code}
data= weixiuyuyue.getbyid(weixiuyuyue, weixiuyuyue, int(id_))
for i in data:
votenum=i.get('votenum')
if votenum!=None:
params={"id":int(id_),"votenum":votenum+1}
error=weixiuyuyue.updatebyparams(weixiuyuyue,weixiuyuyue,params)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def weixiuyuyue_importExcel(request):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": "成功", "data": {}}
excel_file = request.FILES.get("file", "")
file_type = excel_file.name.split('.')[1]
if file_type in ['xlsx', 'xls']:
data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())
table = data.sheets()[0]
rows = table.nrows
try:
for row in range(1, rows):
row_values = table.row_values(row)
req_dict = {}
weixiuyuyue.createbyreq(weixiuyuyue, weixiuyuyue, req_dict)
except:
pass
else:
msg.code = 500
msg.msg = "文件类型错误"
return JsonResponse(msg)
def weixiuyuyue_sendemail(request):
if request.method in ["POST", "GET"]:
req_dict = request.session.get("req_dict")
code = random.sample(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 4)
to = []
to.append(req_dict['email'])
send_mail('用户注册', '您的注册验证码是【'+''.join(code)+'】,请不要把验证码泄漏给其他人,如非本人请勿操作。', 'yclw9@qq.com', to, fail_silently = False)
cursor = connection.cursor()
cursor.execute("insert into emailregistercode(email,role,code) values('"+req_dict['email']+"','用户','"+''.join(code)+"')")
msg = {
"msg": "发送成功",
"code": 0
}
return JsonResponse(msg)
def weixiuyuyue_autoSort2(request):
if request.method in ["POST", "GET"]:
req_dict = request.session.get("req_dict")
cursor = connection.cursor()
leixing = set()
try:
cursor.execute("select inteltype from storeup where userid = %d"%(request.session.get("params").get("id"))+" and tablename = 'weixiuyuyue' order by addtime desc")
rows = cursor.fetchall()
for row in rows:
for item in row:
if item != None:
leixing.add(item)
except:
leixing = set()
L = []
cursor.execute("select * from weixiuyuyue where $intelRecomColumn in ('%s"%("','").join(leixing)+"') union all select * from weixiuyuyue where $intelRecomColumn not in('%s"%("','").join(leixing)+"')")
desc = cursor.description
data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
for online_dict in data_dict:
for key in online_dict:
if 'datetime.datetime' in str(type(online_dict[key])):
online_dict[key] = online_dict[key].strftime(
"%Y-%m-%d %H:%M:%S")
else:
pass
L.append(online_dict)
return JsonResponse({"code": 0, "msg": '', "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":5,"list": L[0:6]}})
def weixiuyuyue_value(request, xColumnName, yColumnName, timeStatType):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": "成功", "data": {}}
where = ' where 1 = 1 '
sql = ''
if timeStatType == '日':
sql = "SELECT DATE_FORMAT({0}, '%Y-%m-%d') {0}, sum({1}) total FROM weixiuyuyue {2} GROUP BY DATE_FORMAT({0}, '%Y-%m-%d')".format(xColumnName, yColumnName, where, '%Y-%m-%d')
if timeStatType == '月':
sql = "SELECT DATE_FORMAT({0}, '%Y-%m') {0}, sum({1}) total FROM weixiuyuyue {2} GROUP BY DATE_FORMAT({0}, '%Y-%m')".format(xColumnName, yColumnName, where, '%Y-%m')
if timeStatType == '年':
sql = "SELECT DATE_FORMAT({0}, '%Y') {0}, sum({1}) total FROM weixiuyuyue {2} GROUP BY DATE_FORMAT({0}, '%Y')".format(xColumnName, yColumnName, where, '%Y')
L = []
cursor = connection.cursor()
cursor.execute(sql)
desc = cursor.description
data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
for online_dict in data_dict:
for key in online_dict:
if 'datetime.datetime' in str(type(online_dict[key])):
online_dict[key] = online_dict[key].strftime(
"%Y-%m-%d %H:%M:%S")
else:
pass
L.append(online_dict)
msg['data'] = L
return JsonResponse(msg)
def weixiuyuyue_o_value(request, xColumnName, yColumnName):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": "成功", "data": {}}
where = ' where 1 = 1 '
sql = "SELECT {0}, sum({1}) AS total FROM weixiuyuyue {2} GROUP BY {0}".format(xColumnName, yColumnName, where)
L = []
cursor = connection.cursor()
cursor.execute(sql)
desc = cursor.description
data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
for online_dict in data_dict:
for key in online_dict:
if 'datetime.datetime' in str(type(online_dict[key])):
online_dict[key] = online_dict[key].strftime(
"%Y-%m-%d %H:%M:%S")
else:
pass
L.append(online_dict)
msg['data'] = L
return JsonResponse(msg)
def weixiuyuyue_alipay(request):
if request.method in ["POST", "GET"]:
alipay = AliPay(
appid=settings.ALIPAY_APP_ID,
app_notify_url=None,
app_private_key_string=settings.APP_PRIVATE_KEY_STRING,
alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,
sign_type=settings.ALIPAY_SIGN_TYPE,
debug=True,
config=AliPayConfig(timeout=15)
)
req_dict = request.session.get("req_dict")
order_string = alipay.api_alipay_trade_page_pay(
out_trade_no=req_dict['tradeno'],
total_amount=req_dict['totalamount'],
subject=req_dict['subject'],
return_url='http://127.0.0.1:8080/django78p27/weixiuyuyue/notify',
#notify_url=''
)
pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
pay_url = '<form name="punchout_form" method="post" action="{0}"><input type="hidden" name="biz_content" ><input type="submit" value="立即支付" style="display: none"></form>'.format(pay_url)
return JsonResponse({'code': 0, "data": pay_url})
def weixiuyuyue_notify(request):
if request.method in ["POST", "GET"]:
req_dict = request.session.get("req_dict")
out_trade_no = req_dict['out_trade_no']
cursor = connection.cursor()
return redirect('http://127.0.0.1:8080/django78p27/admin/dist/index.html#/weixiuyuyue')
def weixiuyuyue_groupby(request):
'''
管理员用户:当表属性isAdmin=”是”,刷出来的用户表也是管理员,即page和list可以查看所有人的考试记录(同时应用于其他表)
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
#处理参数
try:
page1 = int(req_dict.get("page"))
except:
page1 = 1
try:
limit1 = int(req_dict.get("limit"))
except:
limit1 = 10
#值为"是"仅能查看自己的记录和add接口后台赋值userid的值
try:
__authSeparate__ = weixiuyuyue.__authSeparate__
except:
__authSeparate__ = None
# print(weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue))
if __authSeparate__=="是":
#print("req_dict==============>",req_dict)
#如果当前表有userid字段,且通过身份认证
if "userid" in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue) and request.session.get("params")!=None:
#参数增加userid
req_dict["userid"]=request.session.get("params").get("id")
#如果当前表没有userid字段,且参数里有userid键值对
if "userid" not in weixiuyuyue.getallcolumn(weixiuyuyue,weixiuyuyue) and "userid" in list(req_dict.keys()):
#删除参数userid
del req_dict["userid"]
try:
del req_dict["page"]
del req_dict["limit"]
except:
pass
tablename=request.session.get("tablename")
if tablename=="users" and req_dict.get("userid")!=None:
del req_dict["userid"]
else:
#判断当前登陆表是否具有管理员权限
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
#是,则删除userid参数
if __isAdmin__=="是":
del req_dict["userid"]
else:
#否,则赋值userid参数
req_dict["userid"]=request.session.get("params").get("id")
print("req_dict===========>",req_dict)
#20200928 去掉总记录数查询.因为只有一条记录,所以总记录数从查询所的记录获取
#本次查询所有,求总记录数
# alldata = weixiuyuyue.objects.filter(**req_dict). \
# annotate(userids=Count('userid'),paperids=Count('paperid'),papernames=Count('papername')). \
# values("userid", "paperid", "papername","myscore","userids"). \
# all()
# print("alldata=============>",alldata)
# print("alldata=============>",alldata. aggregate(myscore=Sum('myscore')))
#本次分页查询
start=limit1 * (page1 - 1)
end=limit1 * (page1 - 1)+limit1+1
datas = weixiuyuyue.objects.filter(**req_dict).\
annotate(userids=Count('userid'),usernames=Count('username'),paperids=Count('paperid'),papernames=Count('papername')). \
values("userid", "username", "paperid", "papername","myscore"). \
all()[start:end]
print("datas=============>", datas)
print("datas=============>", datas.aggregate(myscore=Sum('myscore')))
#处理分页查询所得数据
try:
data = [model_to_dict(i) for i in datas]
except:
data = datas
dataDict = {}
for i in data:
keyName1="{}#{}#{}#{}".format(i.get("userid"),i.get("username"),i.get("paperid"),i.get("papername"))
if dataDict.get(keyName1)==None:
dataDict[keyName1]={"userid":i.get("userid"),"username":i.get("username"),"paperid":i.get("paperid"),"papername":i.get("papername"),"myscore":i.get("myscore")}
else:
dataDict[keyName1]["myscore"]=dataDict.get(keyName1).get("myscore")+i.get("myscore")
#赋值分页查询所得数据
dataList =list(dataDict.values())
# 处理所有查询,计算总页数
total = len(dataList)
try:
div = divmod(total, limit1)
if div[1] > 0:
totalPage = div[0] + 1
else:
totalPage = div[0]
except:
totalPage = 1
# 赋值分页参数
msg["data"] = {"pageSize": limit1,
"total": total,
"totalPage": totalPage,
"currPage": page1,
"list":dataList
}
return JsonResponse(msg)
def weixiuyuyue_deleterecords(request):
'''
按键值对参数添加删除记录
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
error=weixiuyuyue.deletebyparams(weixiuyuyue,weixiuyuyue,req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def weixiuyuyue_flist(request):
'''
查看所有开放的帖列表(无需登录)
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] = weixiuyuyue.page(weixiuyuyue, weixiuyuyue, req_dict)
return JsonResponse(msg)
def weixiuyuyue_list_id(request,id_):
'''
查看主贴和所有回帖内容(无需登录)
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {"currPage":1,"totalPage":1,"total":1,"pageSize":10,"childs":[]},"id":int(id_)}
params = {"id":int(id_)}
datas = weixiuyuyue.retrieve(weixiuyuyue, weixiuyuyue)
parent_id=0#当前id,也就是parent_id,找到了下一级,把下一级id赋值给current_id,当做下下一级id的paretn_id
current_id=0
start_index=0
#获取parentid
for index,i in enumerate(datas):
if i.get('id')==params.get('id'):
current_id=parent_id=i.get('id')
start_index=index
msg['data'].update(i)
break
#把疑似回帖的id放进ids数组
id_data_dict={}#id和详情的键值对
for i in datas:
id_data_dict[i.get('id')]=i
dict1={}#部分层级,只获取上下级关系
for v in id_data_dict.values():
parentid_=copy.deepcopy(v.get("parentid"))
id_=copy.deepcopy(v.get("id"))
if dict1.get(parentid_)==None:
dict1[parentid_]=[]
dict1[parentid_].append(id_)
childs=[]#msg.data.childs
#填充第一层回帖
for i in dict1.get(parent_id,[]):
child1=copy.deepcopy(id_data_dict.get(i))
#填充第二层回帖
if dict1.get(i)!=None:#判断第二次是否还有回帖
child2=[]
for j in dict1.get(i):
child3=copy.deepcopy(id_data_dict.get(j))
id_=copy.deepcopy(child3.get("id"))
if dict1.get(id_)!=None:#判断第三次是否还有回帖
child3["childs"]=[]
for k in dict1.get(id_):
child4=copy.deepcopy(id_data_dict.get(k))
id__=copy.deepcopy(child4.get("id"))
if dict1.get(id__)!=None:#判断第四次是否还有回帖
child4['childs']=[]
for l in dict1.get(id__):
child5=copy.deepcopy(id_data_dict.get(l))
id___=copy.deepcopy(child5.get("id"))
if dict1.get(id___)!=None:#判断第五次是否还有回帖
child5['childs']=[]
for m in dict1.get(id___):
child6=copy.deepcopy(id_data_dict.get(m))
id____=copy.deepcopy(child6.get("id"))
if dict1.get(id____)!=None:#判断第六次是否还有回帖
child6['childs']=[]
child7=copy.deepcopy(id_data_dict.get(m))
child7['childs']=[]
for n in dict1.get(id____):
child7['childs'].append(id_data_dict.get(n))
child6['childs'].append(child7)
child5['childs'].append(child6)
child4["childs"].append(child5)
child3["childs"].append(child4)
child2.append(child3)
child1['childs']=child2
else:
child1['childs']=None
childs.append(child1)
print(childs)
msg['data']['childs']=childs
return JsonResponse(msg)
4.2 汽车配件入库
#coding:utf-8
__author__ = "ila"
import base64, copy, logging, os, time, xlrd
from django.http import JsonResponse
from django.apps import apps
from django.db.models.aggregates import Count,Sum
from .models import qichepeijiankucun
from util.codes import *
from util.auth import Auth
from util.common import Common
import util.message as mes
from django.db import connection
import random
from django.core.mail import send_mail
from alipay import AliPayConfig, AliPay
from django.conf import settings
from django.shortcuts import redirect
def qichepeijiankucun_register(request):
if request.method in ["POST", "GET"]:
msg = {'code': normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
error = qichepeijiankucun.createbyreq(qichepeijiankucun, qichepeijiankucun, req_dict)
if error != None:
msg['code'] = crud_error_code
msg['msg'] = "用户已存在,请勿重复注册!"
return JsonResponse(msg)
def qichepeijiankucun_login(request):
if request.method in ["POST", "GET"]:
msg = {'code': normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
datas = qichepeijiankucun.getbyparams(qichepeijiankucun, qichepeijiankucun, req_dict)
if not datas:
msg['code'] = password_error_code
msg['msg'] = mes.password_error_code
return JsonResponse(msg)
try:
__sfsh__= qichepeijiankucun.__sfsh__
except:
__sfsh__=None
if __sfsh__=='是':
if datas[0].get('sfsh')=='否':
msg['code']=other_code
msg['msg'] = "账号已锁定,请联系管理员审核!"
return JsonResponse(msg)
req_dict['id'] = datas[0].get('id')
return Auth.authenticate(Auth, qichepeijiankucun, req_dict)
def qichepeijiankucun_logout(request):
if request.method in ["POST", "GET"]:
msg = {
"msg": "登出成功",
"code": 0
}
return JsonResponse(msg)
def qichepeijiankucun_resetPass(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
columns= qichepeijiankucun.getallcolumn( qichepeijiankucun, qichepeijiankucun)
try:
__loginUserColumn__= qichepeijiankucun.__loginUserColumn__
except:
__loginUserColumn__=None
username=req_dict.get(list(req_dict.keys())[0])
if __loginUserColumn__:
username_str=__loginUserColumn__
else:
username_str=username
if 'mima' in columns:
password_str='mima'
else:
password_str='password'
init_pwd = '123456'
recordsParam = {}
recordsParam[username_str] = req_dict.get("username")
records=qichepeijiankucun.getbyparams(qichepeijiankucun, qichepeijiankucun, recordsParam)
if len(records)<1:
msg['code'] = 400
msg['msg'] = '用户不存在'
return JsonResponse(msg)
eval('''qichepeijiankucun.objects.filter({}='{}').update({}='{}')'''.format(username_str,username,password_str,init_pwd))
return JsonResponse(msg)
def qichepeijiankucun_session(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}
req_dict={"id":request.session.get('params').get("id")}
msg['data'] = qichepeijiankucun.getbyparams(qichepeijiankucun, qichepeijiankucun, req_dict)[0]
return JsonResponse(msg)
def qichepeijiankucun_default(request):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code,"msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
req_dict.update({"isdefault":"是"})
data=qichepeijiankucun.getbyparams(qichepeijiankucun, qichepeijiankucun, req_dict)
if len(data)>0:
msg['data'] = data[0]
else:
msg['data'] = {}
return JsonResponse(msg)
def qichepeijiankucun_page(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
#获取全部列名
columns= qichepeijiankucun.getallcolumn( qichepeijiankucun, qichepeijiankucun)
#当前登录用户所在表
tablename = request.session.get("tablename")
#authColumn=list(__authTables__.keys())[0]
#authTable=__authTables__.get(authColumn)
# if authTable==tablename:
#params = request.session.get("params")
#req_dict[authColumn]=params.get(authColumn)
'''__authSeparate__此属性为真,params添加userid,后台只查询个人数据'''
try:
__authSeparate__=qichepeijiankucun.__authSeparate__
except:
__authSeparate__=None
if __authSeparate__=="是":
tablename=request.session.get("tablename")
if tablename!="users" and 'userid' in columns:
try:
req_dict['userid']=request.session.get("params").get("id")
except:
pass
#当项目属性hasMessage为”是”,生成系统自动生成留言板的表messages,同时该表的表属性hasMessage也被设置为”是”,字段包括userid(用户id),username(用户名),content(留言内容),reply(回复)
#接口page需要区分权限,普通用户查看自己的留言和回复记录,管理员查看所有的留言和回复记录
try:
__hasMessage__=qichepeijiankucun.__hasMessage__
except:
__hasMessage__=None
if __hasMessage__=="是":
tablename=request.session.get("tablename")
if tablename!="users":
req_dict["userid"]=request.session.get("params").get("id")
# 判断当前表的表属性isAdmin,为真则是管理员表
# 当表属性isAdmin=”是”,刷出来的用户表也是管理员,即page和list可以查看所有人的考试记录(同时应用于其他表)
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
# 当前表也是有管理员权限的表
if __isAdmin__ == "是":
if req_dict.get("userid"):
del req_dict["userid"]
else:
#非管理员权限的表,判断当前表字段名是否有userid
if tablename!="users" and 'qichepeijiankucun'[:7]!='discuss'and "userid" in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun):
req_dict["userid"] = request.session.get("params").get("id")
#当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
try:
__authTables__=qichepeijiankucun.__authTables__
except:
__authTables__=None
if __authTables__!=None and __authTables__!={}:
try:
del req_dict['userid']
except:
pass
for authColumn,authTable in __authTables__.items():
if authTable==tablename:
params = request.session.get("params")
req_dict[authColumn]=params.get(authColumn)
break
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] =qichepeijiankucun.page(qichepeijiankucun, qichepeijiankucun, req_dict, request)
return JsonResponse(msg)
def qichepeijiankucun_autoSort(request):
'''
.智能推荐功能(表属性:[intelRecom(是/否)],新增clicktime[前端不显示该字段]字段(调用info/detail接口的时候更新),按clicktime排序查询)
主要信息列表(如商品列表,新闻列表)中使用,显示最近点击的或最新添加的5条记录就行
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
if "clicknum" in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun):
req_dict['sort']='clicknum'
else:
req_dict['sort']='clicktime'
req_dict['order']='desc'
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] = qichepeijiankucun.page(qichepeijiankucun,qichepeijiankucun, req_dict)
return JsonResponse(msg)
def qichepeijiankucun_list(request):
'''
前台分页
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
#获取全部列名
columns= qichepeijiankucun.getallcolumn( qichepeijiankucun, qichepeijiankucun)
#表属性[foreEndList]前台list:和后台默认的list列表页相似,只是摆在前台,否:指没有此页,是:表示有此页(不需要登陆即可查看),前要登:表示有此页且需要登陆后才能查看
try:
__foreEndList__=qichepeijiankucun.__foreEndList__
except:
__foreEndList__=None
if __foreEndList__=="前要登":
tablename=request.session.get("tablename")
if tablename!="users" and 'userid' in columns:
try:
req_dict['userid']=request.session.get("params").get("id")
except:
pass
#forrEndListAuth
try:
__foreEndListAuth__=qichepeijiankucun.__foreEndListAuth__
except:
__foreEndListAuth__=None
#authSeparate
try:
__authSeparate__=qichepeijiankucun.__authSeparate__
except:
__authSeparate__=None
if __foreEndListAuth__ =="是" and __authSeparate__=="是":
tablename=request.session.get("tablename")
if tablename!="users":
req_dict['userid']=request.session.get("params",{"id":0}).get("id")
tablename = request.session.get("tablename")
if tablename == "users" and req_dict.get("userid") != None:#判断是否存在userid列名
del req_dict["userid"]
else:
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
if __isAdmin__ == "是":
if req_dict.get("userid"):
del req_dict["userid"]
else:
#非管理员权限的表,判断当前表字段名是否有userid
if "userid" in columns:
try:
# 本接口可以匿名访问,所以try判断是否为匿名
req_dict['userid']=request.session.get("params").get("id")
except:
pass
#当列属性authTable有值(某个用户表)[该列的列名必须和该用户表的登陆字段名一致],则对应的表有个隐藏属性authTable为”是”,那么该用户查看该表信息时,只能查看自己的
try:
__authTables__=qichepeijiankucun.__authTables__
except:
__authTables__=None
if __authTables__!=None and __authTables__!={} and __foreEndListAuth__=="是":
try:
del req_dict['userid']
except:
pass
for authColumn,authTable in __authTables__.items():
if authTable==tablename:
params = request.session.get("params")
req_dict[authColumn]=params.get(authColumn)
break
if qichepeijiankucun.__tablename__[:7]=="discuss":
try:
del req_dict['userid']
except:
pass
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] = qichepeijiankucun.page(qichepeijiankucun, qichepeijiankucun, req_dict)
return JsonResponse(msg)
def qichepeijiankucun_save(request):
'''
后台新增
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
if 'clicktime' in req_dict.keys():
del req_dict['clicktime']
tablename=request.session.get("tablename")
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
#获取全部列名
columns= qichepeijiankucun.getallcolumn( qichepeijiankucun, qichepeijiankucun)
if tablename!='users' and req_dict.get("userid")!=None and 'userid' in columns and __isAdmin__!='是':
params=request.session.get("params")
req_dict['userid']=params.get('id')
error= qichepeijiankucun.createbyreq(qichepeijiankucun,qichepeijiankucun, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def qichepeijiankucun_add(request):
'''
前台新增
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
#获取全部列名
columns= qichepeijiankucun.getallcolumn( qichepeijiankucun, qichepeijiankucun)
try:
__authSeparate__=qichepeijiankucun.__authSeparate__
except:
__authSeparate__=None
if __authSeparate__=="是":
tablename=request.session.get("tablename")
if tablename!="users" and 'userid' in columns:
try:
req_dict['userid']=request.session.get("params").get("id")
except:
pass
try:
__foreEndListAuth__=qichepeijiankucun.__foreEndListAuth__
except:
__foreEndListAuth__=None
if __foreEndListAuth__ and __foreEndListAuth__!="否":
tablename=request.session.get("tablename")
if tablename!="users":
req_dict['userid']=request.session.get("params").get("id")
error= qichepeijiankucun.createbyreq(qichepeijiankucun,qichepeijiankucun, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def qichepeijiankucun_thumbsup(request,id_):
'''
点赞:表属性thumbsUp[是/否],刷表新增thumbsupnum赞和crazilynum踩字段,
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
id_=int(id_)
type_=int(req_dict.get("type",0))
rets=qichepeijiankucun.getbyid(qichepeijiankucun,qichepeijiankucun,id_)
update_dict={
"id":id_,
}
if type_==1:#赞
update_dict["thumbsupnum"]=int(rets[0].get('thumbsupnum'))+1
elif type_==2:#踩
update_dict["crazilynum"]=int(rets[0].get('crazilynum'))+1
error = qichepeijiankucun.updatebyparams(qichepeijiankucun,qichepeijiankucun, update_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def qichepeijiankucun_info(request,id_):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
data = qichepeijiankucun.getbyid(qichepeijiankucun,qichepeijiankucun, int(id_))
if len(data)>0:
msg['data']=data[0]
#浏览点击次数
try:
__browseClick__= qichepeijiankucun.__browseClick__
except:
__browseClick__=None
if __browseClick__=="是" and "clicknum" in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun):
try:
clicknum=int(data[0].get("clicknum",0))+1
except:
clicknum=0+1
click_dict={"id":int(id_),"clicknum":clicknum}
ret=qichepeijiankucun.updatebyparams(qichepeijiankucun,qichepeijiankucun,click_dict)
if ret!=None:
msg['code'] = crud_error_code
msg['msg'] = ret
return JsonResponse(msg)
def qichepeijiankucun_detail(request,id_):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
data =qichepeijiankucun.getbyid(qichepeijiankucun,qichepeijiankucun, int(id_))
if len(data)>0:
msg['data']=data[0]
#浏览点击次数
try:
__browseClick__= qichepeijiankucun.__browseClick__
except:
__browseClick__=None
if __browseClick__=="是" and "clicknum" in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun):
try:
clicknum=int(data[0].get("clicknum",0))+1
except:
clicknum=0+1
click_dict={"id":int(id_),"clicknum":clicknum}
ret=qichepeijiankucun.updatebyparams(qichepeijiankucun,qichepeijiankucun,click_dict)
if ret!=None:
msg['code'] = crud_error_code
msg['msg'] = retfo
return JsonResponse(msg)
def qichepeijiankucun_update(request):
'''
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
if req_dict.get("mima") and req_dict.get("password"):
if "mima" not in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun) :
del req_dict["mima"]
if "password" not in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun) :
del req_dict["password"]
try:
del req_dict["clicknum"]
except:
pass
error = qichepeijiankucun.updatebyparams(qichepeijiankucun, qichepeijiankucun, req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def qichepeijiankucun_delete(request):
'''
批量删除
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
error=qichepeijiankucun.deletes(qichepeijiankucun,
qichepeijiankucun,
req_dict.get("ids")
)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def qichepeijiankucun_vote(request,id_):
'''
浏览点击次数(表属性[browseClick:是/否],点击字段(clicknum),调用info/detail接口的时候后端自动+1)、投票功能(表属性[vote:是/否],投票字段(votenum),调用vote接口后端votenum+1)
统计商品或新闻的点击次数;提供新闻的投票功能
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code}
data= qichepeijiankucun.getbyid(qichepeijiankucun, qichepeijiankucun, int(id_))
for i in data:
votenum=i.get('votenum')
if votenum!=None:
params={"id":int(id_),"votenum":votenum+1}
error=qichepeijiankucun.updatebyparams(qichepeijiankucun,qichepeijiankucun,params)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def qichepeijiankucun_importExcel(request):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": "成功", "data": {}}
excel_file = request.FILES.get("file", "")
file_type = excel_file.name.split('.')[1]
if file_type in ['xlsx', 'xls']:
data = xlrd.open_workbook(filename=None, file_contents=excel_file.read())
table = data.sheets()[0]
rows = table.nrows
try:
for row in range(1, rows):
row_values = table.row_values(row)
req_dict = {}
qichepeijiankucun.createbyreq(qichepeijiankucun, qichepeijiankucun, req_dict)
except:
pass
else:
msg.code = 500
msg.msg = "文件类型错误"
return JsonResponse(msg)
def qichepeijiankucun_sendemail(request):
if request.method in ["POST", "GET"]:
req_dict = request.session.get("req_dict")
code = random.sample(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 4)
to = []
to.append(req_dict['email'])
send_mail('用户注册', '您的注册验证码是【'+''.join(code)+'】,请不要把验证码泄漏给其他人,如非本人请勿操作。', 'yclw9@qq.com', to, fail_silently = False)
cursor = connection.cursor()
cursor.execute("insert into emailregistercode(email,role,code) values('"+req_dict['email']+"','用户','"+''.join(code)+"')")
msg = {
"msg": "发送成功",
"code": 0
}
return JsonResponse(msg)
def qichepeijiankucun_autoSort2(request):
if request.method in ["POST", "GET"]:
req_dict = request.session.get("req_dict")
cursor = connection.cursor()
leixing = set()
try:
cursor.execute("select inteltype from storeup where userid = %d"%(request.session.get("params").get("id"))+" and tablename = 'qichepeijiankucun' order by addtime desc")
rows = cursor.fetchall()
for row in rows:
for item in row:
if item != None:
leixing.add(item)
except:
leixing = set()
L = []
cursor.execute("select * from qichepeijiankucun where $intelRecomColumn in ('%s"%("','").join(leixing)+"') union all select * from qichepeijiankucun where $intelRecomColumn not in('%s"%("','").join(leixing)+"')")
desc = cursor.description
data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
for online_dict in data_dict:
for key in online_dict:
if 'datetime.datetime' in str(type(online_dict[key])):
online_dict[key] = online_dict[key].strftime(
"%Y-%m-%d %H:%M:%S")
else:
pass
L.append(online_dict)
return JsonResponse({"code": 0, "msg": '', "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":5,"list": L[0:6]}})
def qichepeijiankucun_value(request, xColumnName, yColumnName, timeStatType):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": "成功", "data": {}}
where = ' where 1 = 1 '
sql = ''
if timeStatType == '日':
sql = "SELECT DATE_FORMAT({0}, '%Y-%m-%d') {0}, sum({1}) total FROM qichepeijiankucun {2} GROUP BY DATE_FORMAT({0}, '%Y-%m-%d')".format(xColumnName, yColumnName, where, '%Y-%m-%d')
if timeStatType == '月':
sql = "SELECT DATE_FORMAT({0}, '%Y-%m') {0}, sum({1}) total FROM qichepeijiankucun {2} GROUP BY DATE_FORMAT({0}, '%Y-%m')".format(xColumnName, yColumnName, where, '%Y-%m')
if timeStatType == '年':
sql = "SELECT DATE_FORMAT({0}, '%Y') {0}, sum({1}) total FROM qichepeijiankucun {2} GROUP BY DATE_FORMAT({0}, '%Y')".format(xColumnName, yColumnName, where, '%Y')
L = []
cursor = connection.cursor()
cursor.execute(sql)
desc = cursor.description
data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
for online_dict in data_dict:
for key in online_dict:
if 'datetime.datetime' in str(type(online_dict[key])):
online_dict[key] = online_dict[key].strftime(
"%Y-%m-%d %H:%M:%S")
else:
pass
L.append(online_dict)
msg['data'] = L
return JsonResponse(msg)
def qichepeijiankucun_o_value(request, xColumnName, yColumnName):
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": "成功", "data": {}}
where = ' where 1 = 1 '
sql = "SELECT {0}, sum({1}) AS total FROM qichepeijiankucun {2} GROUP BY {0}".format(xColumnName, yColumnName, where)
L = []
cursor = connection.cursor()
cursor.execute(sql)
desc = cursor.description
data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
for online_dict in data_dict:
for key in online_dict:
if 'datetime.datetime' in str(type(online_dict[key])):
online_dict[key] = online_dict[key].strftime(
"%Y-%m-%d %H:%M:%S")
else:
pass
L.append(online_dict)
msg['data'] = L
return JsonResponse(msg)
def qichepeijiankucun_alipay(request):
if request.method in ["POST", "GET"]:
alipay = AliPay(
appid=settings.ALIPAY_APP_ID,
app_notify_url=None,
app_private_key_string=settings.APP_PRIVATE_KEY_STRING,
alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,
sign_type=settings.ALIPAY_SIGN_TYPE,
debug=True,
config=AliPayConfig(timeout=15)
)
req_dict = request.session.get("req_dict")
order_string = alipay.api_alipay_trade_page_pay(
out_trade_no=req_dict['tradeno'],
total_amount=req_dict['totalamount'],
subject=req_dict['subject'],
return_url='http://127.0.0.1:8080/django78p27/qichepeijiankucun/notify',
#notify_url=''
)
pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
pay_url = '<form name="punchout_form" method="post" action="{0}"><input type="hidden" name="biz_content" ><input type="submit" value="立即支付" style="display: none"></form>'.format(pay_url)
return JsonResponse({'code': 0, "data": pay_url})
def qichepeijiankucun_notify(request):
if request.method in ["POST", "GET"]:
req_dict = request.session.get("req_dict")
out_trade_no = req_dict['out_trade_no']
cursor = connection.cursor()
return redirect('http://127.0.0.1:8080/django78p27/admin/dist/index.html#/qichepeijiankucun')
def qichepeijiankucun_groupby(request):
'''
管理员用户:当表属性isAdmin=”是”,刷出来的用户表也是管理员,即page和list可以查看所有人的考试记录(同时应用于其他表)
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {}}
req_dict = request.session.get("req_dict")
#处理参数
try:
page1 = int(req_dict.get("page"))
except:
page1 = 1
try:
limit1 = int(req_dict.get("limit"))
except:
limit1 = 10
#值为"是"仅能查看自己的记录和add接口后台赋值userid的值
try:
__authSeparate__ = qichepeijiankucun.__authSeparate__
except:
__authSeparate__ = None
# print(qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun))
if __authSeparate__=="是":
#print("req_dict==============>",req_dict)
#如果当前表有userid字段,且通过身份认证
if "userid" in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun) and request.session.get("params")!=None:
#参数增加userid
req_dict["userid"]=request.session.get("params").get("id")
#如果当前表没有userid字段,且参数里有userid键值对
if "userid" not in qichepeijiankucun.getallcolumn(qichepeijiankucun,qichepeijiankucun) and "userid" in list(req_dict.keys()):
#删除参数userid
del req_dict["userid"]
try:
del req_dict["page"]
del req_dict["limit"]
except:
pass
tablename=request.session.get("tablename")
if tablename=="users" and req_dict.get("userid")!=None:
del req_dict["userid"]
else:
#判断当前登陆表是否具有管理员权限
__isAdmin__ = None
allModels = apps.get_app_config('main').get_models()
for m in allModels:
if m.__tablename__==tablename:
try:
__isAdmin__ = m.__isAdmin__
except:
__isAdmin__ = None
break
#是,则删除userid参数
if __isAdmin__=="是":
del req_dict["userid"]
else:
#否,则赋值userid参数
req_dict["userid"]=request.session.get("params").get("id")
print("req_dict===========>",req_dict)
#20200928 去掉总记录数查询.因为只有一条记录,所以总记录数从查询所的记录获取
#本次查询所有,求总记录数
# alldata = qichepeijiankucun.objects.filter(**req_dict). \
# annotate(userids=Count('userid'),paperids=Count('paperid'),papernames=Count('papername')). \
# values("userid", "paperid", "papername","myscore","userids"). \
# all()
# print("alldata=============>",alldata)
# print("alldata=============>",alldata. aggregate(myscore=Sum('myscore')))
#本次分页查询
start=limit1 * (page1 - 1)
end=limit1 * (page1 - 1)+limit1+1
datas = qichepeijiankucun.objects.filter(**req_dict).\
annotate(userids=Count('userid'),usernames=Count('username'),paperids=Count('paperid'),papernames=Count('papername')). \
values("userid", "username", "paperid", "papername","myscore"). \
all()[start:end]
print("datas=============>", datas)
print("datas=============>", datas.aggregate(myscore=Sum('myscore')))
#处理分页查询所得数据
try:
data = [model_to_dict(i) for i in datas]
except:
data = datas
dataDict = {}
for i in data:
keyName1="{}#{}#{}#{}".format(i.get("userid"),i.get("username"),i.get("paperid"),i.get("papername"))
if dataDict.get(keyName1)==None:
dataDict[keyName1]={"userid":i.get("userid"),"username":i.get("username"),"paperid":i.get("paperid"),"papername":i.get("papername"),"myscore":i.get("myscore")}
else:
dataDict[keyName1]["myscore"]=dataDict.get(keyName1).get("myscore")+i.get("myscore")
#赋值分页查询所得数据
dataList =list(dataDict.values())
# 处理所有查询,计算总页数
total = len(dataList)
try:
div = divmod(total, limit1)
if div[1] > 0:
totalPage = div[0] + 1
else:
totalPage = div[0]
except:
totalPage = 1
# 赋值分页参数
msg["data"] = {"pageSize": limit1,
"total": total,
"totalPage": totalPage,
"currPage": page1,
"list":dataList
}
return JsonResponse(msg)
def qichepeijiankucun_deleterecords(request):
'''
按键值对参数添加删除记录
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code}
req_dict = request.session.get("req_dict")
error=qichepeijiankucun.deletebyparams(qichepeijiankucun,qichepeijiankucun,req_dict)
if error!=None:
msg['code'] = crud_error_code
msg['msg'] = error
return JsonResponse(msg)
def qichepeijiankucun_flist(request):
'''
查看所有开放的帖列表(无需登录)
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data":{"currPage":1,"totalPage":1,"total":1,"pageSize":10,"list":[]}}
req_dict = request.session.get("req_dict")
msg['data']['list'], msg['data']['currPage'], msg['data']['totalPage'], msg['data']['total'], \
msg['data']['pageSize'] = qichepeijiankucun.page(qichepeijiankucun, qichepeijiankucun, req_dict)
return JsonResponse(msg)
def qichepeijiankucun_list_id(request,id_):
'''
查看主贴和所有回帖内容(无需登录)
'''
if request.method in ["POST", "GET"]:
msg = {"code": normal_code, "msg": mes.normal_code, "data": {"currPage":1,"totalPage":1,"total":1,"pageSize":10,"childs":[]},"id":int(id_)}
params = {"id":int(id_)}
datas = qichepeijiankucun.retrieve(qichepeijiankucun, qichepeijiankucun)
parent_id=0#当前id,也就是parent_id,找到了下一级,把下一级id赋值给current_id,当做下下一级id的paretn_id
current_id=0
start_index=0
#获取parentid
for index,i in enumerate(datas):
if i.get('id')==params.get('id'):
current_id=parent_id=i.get('id')
start_index=index
msg['data'].update(i)
break
#把疑似回帖的id放进ids数组
id_data_dict={}#id和详情的键值对
for i in datas:
id_data_dict[i.get('id')]=i
dict1={}#部分层级,只获取上下级关系
for v in id_data_dict.values():
parentid_=copy.deepcopy(v.get("parentid"))
id_=copy.deepcopy(v.get("id"))
if dict1.get(parentid_)==None:
dict1[parentid_]=[]
dict1[parentid_].append(id_)
childs=[]#msg.data.childs
#填充第一层回帖
for i in dict1.get(parent_id,[]):
child1=copy.deepcopy(id_data_dict.get(i))
#填充第二层回帖
if dict1.get(i)!=None:#判断第二次是否还有回帖
child2=[]
for j in dict1.get(i):
child3=copy.deepcopy(id_data_dict.get(j))
id_=copy.deepcopy(child3.get("id"))
if dict1.get(id_)!=None:#判断第三次是否还有回帖
child3["childs"]=[]
for k in dict1.get(id_):
child4=copy.deepcopy(id_data_dict.get(k))
id__=copy.deepcopy(child4.get("id"))
if dict1.get(id__)!=None:#判断第四次是否还有回帖
child4['childs']=[]
for l in dict1.get(id__):
child5=copy.deepcopy(id_data_dict.get(l))
id___=copy.deepcopy(child5.get("id"))
if dict1.get(id___)!=None:#判断第五次是否还有回帖
child5['childs']=[]
for m in dict1.get(id___):
child6=copy.deepcopy(id_data_dict.get(m))
id____=copy.deepcopy(child6.get("id"))
if dict1.get(id____)!=None:#判断第六次是否还有回帖
child6['childs']=[]
child7=copy.deepcopy(id_data_dict.get(m))
child7['childs']=[]
for n in dict1.get(id____):
child7['childs'].append(id_data_dict.get(n))
child6['childs'].append(child7)
child5['childs'].append(child6)
child4["childs"].append(child5)
child3["childs"].append(child4)
child2.append(child3)
child1['childs']=child2
else:
child1['childs']=None
childs.append(child1)
print(childs)
msg['data']['childs']=childs
return JsonResponse(msg)