from poll.models import Questionnaire, Whitelist, Blacklist,Record,HistoryRecord,Condition,Choice
from django.http import JsonResponse
from http import HTTPStatus
from django.forms.models import model_to_dict
from Utils.wrappers import permitted_methods
from Utils.tools import request_body_serialize,request_body_serialize_init
from django.core.paginator import Paginator,EmptyPage
from student.models import Student
from Utils.tools import paginator2dict,paginator3dict,paginator4dict,paginator5dict,paginator6dict
from Utils.fileTool import upload_file
import xlwt
import io, csv, codecs
from django.http import HttpResponse
from openpyxl import Workbook
from openpyxl import load_workbook
import wx
import wx.grid
import matplotlib; matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
import numpy as np
@permitted_methods(["GET"])
def polls(request, type):
page_num = request.GET.get('p', 1)
length = request.GET.get('l', 15)
if type == '' or type is None:
# 获取未归档的问卷列表
questionnaires = Questionnaire.objects.exclude(status=-1)
paginator = Paginator(questionnaires, length)
try:
paginator_page = paginator.page(page_num)
except EmptyPage:
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "没有该页面"},
json_dumps_params={'ensure_ascii': False})
ret = {'message': 'ok',
'data': paginator4dict(paginator_page, ["id", "title", "creatorId", "oneoff", "status",'createTime','updateTime'])}
return JsonResponse(data=ret, json_dumps_params={'ensure_ascii': False})
elif type == 'archive':
# 获取已归档的问卷列表:
questionnaires = Questionnaire.objects.filter(status=-1)
paginator = Paginator(questionnaires, length)
try:
paginator_page = paginator.page(page_num)
except EmptyPage:
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "没有该页面"},
json_dumps_params={'ensure_ascii': False})
ret = {'message': 'ok',
'data': paginator5dict(paginator_page,["id", "title", "creatorId", "oneoff", "status", 'createTime', 'updateTime'])}
return JsonResponse(data=ret, json_dumps_params={'ensure_ascii': False})
else:
return JsonResponse(status=HTTPStatus.NOT_ACCEPTABLE, data={'error': '参数错误'},
json_dumps_params={'ensure_ascii': False})
@permitted_methods(["GET"])
def meta(request, pollId):
questionnaires = Questionnaire.objects.filter(id=pollId)
if len(questionnaires) == 0:
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={'error': '没有该问卷'},
json_dumps_params={'ensure_ascii': False})
questionnaire = questionnaires[0]
fields = ["status", "oneoff", "title", "scope", "creatorId"]
for i in range(1, 21):
if getattr(questionnaire, "k" + str(i)) is not None:
fields.append("k" + str(i))
mod = model_to_dict(questionnaire, fields=fields)
mod['createTime'] = questionnaire.createTime.strftime("%Y-%m-%d %H:%M")
mod['updateTime'] = questionnaire.updateTime.strftime("%Y-%m-%d %H:%M")
ret = {'message': 'ok',
'data': mod}
return JsonResponse(data=ret, json_dumps_params={'ensure_ascii': False})
@permitted_methods(["POST"])
def whitelist_search(request,pollId):
page_num = request.GET.get('p', 1)
length = request.GET.get('l', 15)
vars = request_body_serialize(request)
whiteList = Whitelist.objects.filter(xh__icontains=vars['xh'],questionnaireId=pollId)
if(len(whiteList)==0):
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "该学生并不在白名单内"},
json_dumps_params={'ensure_ascii': False})
paginator = Paginator(whiteList,length)
try:
paginator_page = paginator.page(page_num)
except EmptyPage:
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "没有该页面"},
json_dumps_params={'ensure_ascii': False})
ret = {'message': 'ok',
'data': paginator6dict(paginator_page,['questionnaireId','xh'])}
return JsonResponse(data=ret, json_dumps_params={'ensure_ascii': False})
@permitted_methods(["DELETE"])
def whitelist_delete(request, pollId):
vars = request_body_serialize(request)
if "xh" not in vars.keys():
return JsonResponse(status=HTTPStatus.NOT_ACCEPTABLE, data={'error': '缺少参数'},
json_dumps_params={'ensure_ascii': False})
whitelist = Whitelist.objects.filter(questionnaireId=pollId, xh=vars['xh'])
if len(whitelist) == 0:
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={'error': '白名单或名单中学号不存在'},
json_dumps_params={'ensure_ascii': False})
whitelist.delete()
return JsonResponse(data={'message': 'ok'}, json_dumps_params={'ensure_ascii': False})
@permitted_methods(["POST"])
def whitelist_import(request, pollId):
tmpFile = request.FILES.get('whitelist')
print(tmpFile,type(tmpFile)) #whitelist.xlsx <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
# if not tmpFile:
# return ...
# save_path = os.path.join("temp_data", tmpFile.name)
# destination = open(save_path, 'wb+')
# for chunk in tmpFile.chunks():
# destination.write(chunk)
# destination.close()
workbook_ = load_workbook(tmpFile)
sheetnames = workbook_.get_sheet_names()
sheet = workbook_.get_sheet_by_name(sheetnames[0])
j=2
tmp = sheet.cell(row=2,column=1).value
while tmp:
student = Student.objects.filter(xh=tmp)
if (len(student) == 0):
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "没有该学生"},
json_dumps_params={'ensure_ascii': False})
blacklist = Blacklist.objects.filter(xh=tmp)
if (len(blacklist) != 0):
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "该学生已经在黑名单里了"},
json_dumps_params={'ensure_ascii': False})
Whitelist.objects.create(questionnaireId=pollId, xh=tmp)
j = j+1
tmp = sheet.cell(row=j,column=1).value
return JsonResponse(data={'message':'ok'}, json_dumps_params={'ensure_ascii': False})
@permitted_methods(["POST"])
def blacklist_search(request,pollId):
page_num = request.GET.get('p', 1)
length = request.GET.get('l', 15)
vars = request_body_serialize(request)
blackList = Blacklist.objects.filter(xh__icontains=vars['xh'],questionnaireId=pollId)
if(len(blackList)==0):
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "该学生并不在黑名单内"},
json_dumps_params={'ensure_ascii': False})
paginator = Paginator(blackList,length)
try:
paginator_page = paginator.page(page_num)
except EmptyPage:
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={"error": "没有该页面"},
json_dumps_params={'ensure_ascii': False})
ret = {'message': 'ok',
'data': paginator6dict(paginator_page,['questionnaireId','xh'])}
return JsonResponse(data=ret, json_dumps_params={'ensure_ascii': False})
@permitted_methods(["DELETE"])
def blacklist_delete(request, pollId):
vars = request_body_serialize(request)
if "xh" not in vars.keys():
return JsonResponse(status=HTTPStatus.NOT_ACCEPTABLE, data={'error': '缺少参数'},
json_dumps_params={'ensure_ascii': False})
blacklist = Blacklist.objects.filter(questionnaireId=pollId, xh=vars['xh'])
if len(blacklist) == 0:
return JsonResponse(status=HTTPStatus.NO_CONTENT, data={'error': '�