前台方法
前台传数据到后台
1. 超链接(get请求,可以通过?添加参数)
<dd data-name="console">
<a lay-href="htmls/shipei_import.html">适配信息录入</a>
</dd>
2. 按钮传递参数到后台
<div class="layui-inline">
<button type="button" class="layui-btn" id="test1">导入</button>
</div>
上传文件
var uploadInst = upload.render({
elem: '#test1' //绑定元素,id选择器
{#,url: 'http://127.0.0.1:8000/data/remoteImport' //上传接口#}
,url: '/data/remoteImport' //上传接口,不需要ip
,accept:'file'//类型:文件
,done: function(res){
//上传完毕回调
}
,error: function(){
//请求异常回调
}
});
获取输入框数据作为参数进行查询
table.render({
elem: '#test-table-reload'
{#,url: "填写后台查询数据的接口地址,注意格式"#}
{#,url: 'http://10.1.171.70:8000/data/'#}
{#,url: 'http://127.0.0.1:8000/data'#}
,url: '/data'
,method:'get'
,id:'table-reload'
{#,headers:{token:}#}
,where:{
'remoteName':$("input[name='remoteName']").val(),
'remoteVersion':$("input[name='remoteVersion']").val(),
'persionName':$("input[name='persionName']").val()
}
{#,contentType:'application/json'#}
,cols: [[
{field:'id', title: '编号', width:60}
,{field:'remoteName', title: '遥控器名称', width:210}
,{field:'remoteVersion', title: '固件版本号', width:230}
,{field:'dongle', title: '单双端', width:120}
,{field:'persionName', title: '借用人', width:120}
,{field:'borrowDate', title: '借用日期', sort: true, width:220}
,{field:'isreturn', title: '是否归还', width:120, edit:'text'}
]]
,page: true
,limit:5
,limits:[5,10]
,height: 480
});
3. 获取后台返回数据
一般后台处理完数据直接返回,前台直接获取进行展示就可以了,不需要在前台在进行处理了,这里需要注意两点
①各种回调方法对后台处理结果的判断,比如入库成功或失败的结果,删除成功或失败的结果,显示操作结果在前台
②layui表格对渲染数据格式的要求,参考如下:
def remoteTestData(request):
"""
查询遥控器适配测试结果
:param request:
:return:
"""
# 获取url中的page参数
print(request.GET)
page = int(request.GET['page'])
# 获取url中的limit参数
limit = int(request.GET['limit'])
# 获取remote表中所有数据条数
# count = models.remote.objects.count()
# 获取遥控器名称
xiriVersion = request.GET['xiriVersion']
# 获取版本号
testFunctions = request.GET['testFunctions']
print(type(testFunctions))
# 分页获取一页数据
if '' == testFunctions:
print("oj")
functionList = models.shipeMsg.objects.filter(xiriVersion=xiriVersion).values()
print(functionList)
# 牌照信息
platformMsg = functionList[0]["platformMsg"]
# 功能信息
testFunctions = functionList[0]["testFunctions"]
print(testFunctions)
testFunctions_all = []
testMSG = {}
for item in testFunctions.split("},"):
list_ModelMsg = item.split(":")
list_Model = list_ModelMsg[0]
list_functions = list_ModelMsg[1]
print('11111')
print(list_Model)
print(list_functions)
r = '[’!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]+'
list_Model = re.sub(r, '', str(list_Model))
list_Model = list_Model.strip()
for i in list_functions.split(","):
function = re.sub(r, '', str(i))
testFunctions_all.append(function)
testMSG[list_Model] = testFunctions_all.copy()
testFunctions_all.clear()
print("cewshi ")
print(testMSG)
result = {}
results = []
for i in testMSG.keys():
result["testFunctions"] = i
result["function"] = testMSG[i]
result["licensor"] = platformMsg
results.append(result.copy())
result.clear()
layui_data = {"code": 0, "count": len(results), "msg": "ok", "data": results}
# print(layui_data)
print()
# print(remoteList)
return HttpResponse(json.dumps(layui_data), content_type="application/json")
4. ajax
$.ajax({
url:"data/report/delete?xiriVersion=" + xiriVersion ,
async: true,
type:"GET",
dataType: "json",
data: checkData,
success:function (result) {
if (result.msg == "删除成功"){
table.reload('LAY-app-content-list');
layer.msg('已删除');
}
}
})
后台方法
1. 获取前台传递数据
#信息导入处理,入库
def data_import(request):
"""
:param request:
:return: 要渲染的界面
"""
# form = UploadExcelForm(request.POST, request.FILES)
# file_contents = request.FILES['excel'].read())
the_file = request.FILES['file']
wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['file'].read())
table = wb.sheets()[0]
rows = table.nrows
# 取报备信息
col_baobei = table.row_values(1)
baobei_msg = col_baobei[15]
baobei_msg = json.loads(baobei_msg)
print(baobei_msg)
#读取行,再列值,并进行数据库操作
testFunctions_init = []
testFunctions_distinct = []
testModel_init = []
testModel_distinct = []
testModel_dict = {}
for i in range(2, rows):
col = table.row_values(i)
testModel_init.append(col[0])
testFunctions_init.append(col[1])
print(testModel_init)
print(testFunctions_init)
i = 0
t = 0
s = 0
for item in testModel_init:
if "" != item:
testModel_distinct.append(item)
if i != 0:
s = t
t = i
print(s,t)
testFunctions_distinct.append(list(filter(None, set(testFunctions_init[s:t]))))
if i == len(testModel_init)-1:
print('test')
testFunctions_distinct.append(list(filter(None, set(testFunctions_init[t:(len(testModel_init))]))))
i = i + 1
print(i)
print(testModel_distinct)
print(testFunctions_distinct)
testModel_dict = dict(zip(testModel_distinct,testFunctions_distinct))
# s = 0
# for i in range(2, rows):
# col = table.row_values(i)
# if initMsg == col[0] or initMsg == '':
# testFunctions_init[s].append(col[1])
# if i == 2:
# testModel_init.append(col[0])
# else:
# testModel_init.append(col[0])
# initMsg = col[0]
# s = s+1
# testFunctions_init.append([])
# testFunctions_init[s].append(col[1])
# testFunctions_distinct = []
# for items in testFunctions_init:
# item = set(items)
# testFunctions_distinct.append(item)
# print(testModel_init)
# print(testFunctions_distinct)
# testModel_dict = dict(zip(testModel_init,testFunctions_distinct))
# print(testModel_dict)
shipei_msg = models.shipeMsg(
channelId=baobei_msg['channelId'],
xiriVersion=baobei_msg['xiriVersion'],
xmversion=baobei_msg['xmversion'],
stbMsg=baobei_msg['stbMsg'],
remoteMsg=baobei_msg['remoteMsg'],
platformMsg=baobei_msg['platformMsg'],
testModel = baobei_msg['testModel'],
testFunctions = testModel_dict,
testResult=col_baobei[16],
testBug=baobei_msg['testBug'],
)
shipei_msg.save()
print(shipei_msg)
return HttpResponse('ok')
这里介绍了一个获取上传文件的方法,其他常用还有get和post请求
the_file = request.FILES['file']
wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['file'].read())
table = wb.sheets()[0]
rows = table.nrows
2. 返回数据到前台
文件下载:
def getJson(request):
xiriVersion_req = request.GET['xiriVersion']
print(xiriVersion_req)
report_list = models.report.objects.filter(xiriVersion = xiriVersion_req).values()
print(report_list)
json_list = []
#假如返回多个结果
for i in report_list:
i.pop('id')
json_list.append(i)
print(json_list)
#json_list = {"code": 1, "msg": "成功", "data": json_list}
#取第一条数据:字典
json_list = json_list[0]
#可以通过http://10.1.171.110:8000/json?xiriVersion=a获取json
#return HttpResponse(json.dumps(json_list), content_type="application/json")
response = StreamingHttpResponse(json.dumps(json_list))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename='+ parse.quote(xiriVersion_req)+'.json'
return response
返回layui类型的json:
return HttpResponse(json.dumps(jsonData), content_type="application/json")
返回渲染的html
return render(request, "htmls/remote_from.html")
3. 创建数据库表
class remoteTest(models.Model):
province = models.CharField(max_length=255, blank=True)
xiriVersion = models.CharField(max_length=255, blank=True)
remoteName = models.CharField(max_length=255, blank=True)
remoteVersion = models.CharField(max_length=255, blank=True)
STBMsg = models.CharField(max_length=3000, blank=True)
remoteError = models.CharField(max_length=3000, blank=True)
在models.py中创建表名的类,通过在IDE的Terminal中输入
python manage.py makemigrations
//在migrations中生成数据库迁移脚本
python manage.py migrate 应用名 0001
//应用名mainapp 0001是最新的迁移文件
4. 获取前台数据并保存到数据库
#遥控器测试结果信息导入处理,入库
def remoteDataImport(request):
"""
:param request:
:return: 要渲染的界面
"""
# form = UploadExcelForm(request.POST, request.FILES)
# file_contents = request.FILES['excel'].read())
#the_file = request.FILES['file']
wb = xlrd.open_workbook(filename=None, file_contents=request.FILES['file'].read())
table = wb.sheets()[0]
rows = table.nrows
# 取报备信息
print("取到表格")
col_baobei = table.row_values(1)
baobei_msg = col_baobei[15]
baobei_msg = json.loads(baobei_msg)
print(baobei_msg)
#读取行,再列值,并进行数据库操作
#不用管,反正取到了想要的数据
# testFunctions_init = [[]]
# testModel_init = []
# initMsg = table.row_values(2)[0]
# s = 0
# for i in range(2, rows):
# col = table.row_values(i)
# if initMsg == col[0]:
# testFunctions_init[s].append(col[1])
# if i == 2:
# testModel_init.append(col[0])
# else:
# testModel_init.append(col[0])
# initMsg = col[0]
# s = s+1
# testFunctions_init.append([])
# testFunctions_init[s].append(col[1])
# testFunctions_distinct = []
# for items in testFunctions_init:
# item = set(items)
# testFunctions_distinct.append(item)
# print(testFunctions_distinct)
# testModel_dict = dict(zip(testModel_init,testFunctions_distinct))
#在这里将赋值给数据库
remoteTest = models.remoteTest(
province=baobei_msg['province'],
xiriVersion=baobei_msg['xiriVersion'],
remoteName=baobei_msg['remoteName'],
remoteVersion=baobei_msg['remoteVersion'],
STBMsg=baobei_msg['STBMsg'],
remoteError=baobei_msg['remoteError'],
)
remoteTest.save()
print(remoteTest)
return HttpResponse('ok')
5. 分页
def showReport(request):
page = int(request.GET['page'])
pagesize = int(request.GET['limit'])
count = models.report.objects.count()
jsonDict ={}
jsonList = []
#之前的分页由根据自增主键:id,删除某个id后,后面的id不会顶上去,导致分页失败,现根据mysql的limit来分页
#构建原生SQL语句环境
#起始序号
start_num = (page-1)*pagesize
cursor = connection.cursor()
#sql语句由张壮和丁稳稳友情支持
sql = "select * from mainapp_report order by id desc limit "+str(start_num)+","+str(pagesize)+""
print(sql)
cursor.execute(sql)
rows = cursor.fetchall()
print(rows)
for item in rows:
jsonDict["channelId"] = item[1]
jsonDict["xiriVersion"] = item[2]
jsonDict["xmversion"] = item[3]
jsonDict["romversion"] = item[4]
jsonDict["manufacture"] = item[5]
jsonDict["stbType"] = item[6]
jsonDict["remountversion"] = item[7]
jsonDict["remountType"] = item[8]
jsonDict["platform"] = item[9]
jsonDict["licensor"] = item[10]
print(jsonDict)
#神来之笔
jsonDict = jsonDict.copy()
print(jsonDict.values())
jsonList.append(jsonDict)
jsonDict = jsonDict.copy()
#这样写list中 的数据都是最后一个dict。打印都是正常的。可能list里的dict存的都是所引.后面看了下。果然如此
print(jsonList)
# reportList = models.report.objects.filter(id__range = (count-page*pagesize+1,count-(page-1)*pagesize)).values()
# for i in reportList:
# jsonList.append(i)
# print(jsonList)
# jsonList = jsonList[::-1]
# print(jsonList)
print(count)
jsonData = {"code": 0, "count": count, "msg": "ok", "data": jsonList}
return HttpResponse(json.dumps(jsonData), content_type="application/json")
#遥控器查询,已弃用
def remote_select(request):
"""
:param request:
:return:
"""
#这里查询不需要使用原生SQL,使用filter更方便
# 获取url中的page参数
page = int(request.GET['page'])
# 获取url中的limit参数
limit = int(request.GET['limit'])
#获取前台的遥控器名称
remoteName = None
#获取前台的遥控器版本号
remoteVersion = None
#获取前台的借用人
persionName = None
# 获取remote表中所有数据条数
count = models.remote.objects.count()
# 分页获取一页数据
# remoteList = models.remote.objects.order_by('-id').filter(id__range = (((page-1)*limit)+1,page*limit)).values()
remoteList = models.remote.objects.filter(remoteName == remoteName).filter(remoteVersion == remoteVersion).filter(persionName == persionName)
remoteList = models.remote.objects.order_by('-id')[(page - 1) * limit:page * limit].values()
# 构建layui表格json
# queryset数据序列化
print(remoteList)
layui_data = []
for i in remoteList:
i["borrowDate"] = str(i["borrowDate"])
layui_data.append(i)
layui_data = {"code": 0, "count": count, "msg": "ok", "data": layui_data}
print(layui_data)
# layui_data = serializers.serialize("json", layui_data)
# print(layui_data)
# remoteList = json.dumps(layui_data)
# print(remoteList)
# print(layui_data)
# print(json.dumps(layui_data))
print(json.dumps(layui_data))
return HttpResponse(json.dumps(layui_data), content_type="application/json")
7. 查询
根据三个输入框内容进行查询
#获取数据库中的数据,,遥控器数据
def getData(request):
#获取url中的page参数
print(request.GET)
page = int(request.GET['page'])
#获取url中的limit参数
limit = int(request.GET['limit'])
#获取remote表中所有数据条数
#count = models.remote.objects.count()
#获取遥控器名称
remoteName = request.GET['remoteName']
#获取版本号
remoteVersion = request.GET['remoteVersion']
#获取借用人
persionName = request.GET['persionName']
#分页获取一页数据
#remoteList = models.remote.objects.order_by('-id').filter(id__range = (((page-1)*limit)+1,page*limit)).values()
if '' == remoteName:
if '' == remoteVersion:
if '' == persionName:
remoteList = models.remote.objects
else:
remoteList = models.remote.objects.filter(persionName = persionName)
else:
if '' == persionName:
remoteList = models.remote.objects.filter(remoteVersion = remoteVersion)
else:
remoteList = models.remote.objects.filter(remoteVersion = remoteVersion).filter(persionName = persionName)
else:
if '' == remoteVersion:
if '' == persionName:
remoteList = models.remote.objects.filter(remoteName = remoteName)
else:
remoteList = models.remote.objects.filter(remoteName = remoteName).filter(persionName = persionName)
else:
if '' == persionName:
remoteList = models.remote.objects.filter(remoteName = remoteName).filter(remoteVersion=remoteVersion)
else:
remoteList = models.remote.objects.filter(remoteName = remoteName).filter(remoteVersion=remoteVersion).filter(
persionName=persionName)
# remoteList = models.remote.objects.filter(remoteName = remoteName).filter(remoteVersion = remoteVersion).filter(persionName = persionName).order_by('-id')[(page-1)*limit:page*limit].values()
#remoteList = models.remote.objects.order_by('-id')[(page-1)*limit:page*limit].values()
#构建layui表格json
#queryset数据序列化
# 查询后的数据条数
count = remoteList.count()
remoteList = remoteList.order_by('-id')[(page - 1) * limit:page * limit].values()
print(remoteList)
layui_data =[]
for i in remoteList:
i["borrowDate"] = str(i["borrowDate"])
layui_data.append(i)
layui_data = {"code": 0, "count": count, "msg": "ok", "data": layui_data}
print(layui_data)
#layui_data = serializers.serialize("json", layui_data)
#print(layui_data)
#remoteList = json.dumps(layui_data)
#print(remoteList)
# print(layui_data)
#print(json.dumps(layui_data))
print(json.dumps(layui_data))
return HttpResponse(json.dumps(layui_data), content_type="application/json")
8. 删除
#删除选中报备信息
def deleReport(request):
xiriVersion_req = request.GET['xiriVersion']
print("删除序号")
models.report.objects.filter(xiriVersion=xiriVersion_req).delete()
content = {"msg": "删除成功"}
return HttpResponse(json.dumps(content), content_type="application/json")
- 三级联动下拉列表
太复杂,后面补充 - 文件上传及excel解析
同上,不赘述
- 文件下载
同上,不赘述