def get(user): k = 'group-%s' % user.uuid v = cache.get(k) if v: data = cPickle.loads(v) data['cache'] = 'hit' return data data = {'group': [], 'grade': [], 'cache': 'miss'} server_type = models.Setting.getvalue('server_type') q = models.Group.objects.all() if server_type != 'school': if not is_admin(user): q = q.filter(uuid__in=user.permitted_groups.all()) else: school = models.Group.objects.filter(group_type='school') terms = models.Term.get_current_term_list(school) grades = models.Grade.objects.filter(term__in=terms) grades = grades.values('uuid', 'name', 'term__school__uuid') data['grade'] = model_list_to_dict(grades) q = q.values('uuid', 'name', 'group_type', 'parent__uuid') data['group'] = model_list_to_dict(q) for d in data['group']: py = pypinyin.pinyin(d['name'], pypinyin.FIRST_LETTER) d['first_letter'] = ''.join([i[0] for i in py]) py = ' '.join(pypinyin.lazy_pinyin(d['name'], pypinyin.TONE2)) d['pinyin'] = py cache.set(k, cPickle.dumps(data, cPickle.HIGHEST_PROTOCOL), get_timeout(k, None)) return data
def restore(request, *args, **kwargs): if request.method == 'POST': if not is_admin(request.current_user): return create_failure_dict(msg='只有系统管理员admin才能执行此操作!') try: f = request.FILES.get('excel') data = '' for chunk in f.chunks(): data += chunk data = bz2.decompress(data) lines = data.split('\n') # 清空数据库 _truncate_tables() meta = {} for line in lines: if len(line) == 0: continue if line.startswith('meta:'): # print line meta = json.loads(line[5:]) else: models.SyncLogPack.unpack_log('add', line) # 清空SyncLog models.SyncLog.objects.all().delete() # 设置SyncLog AUTO_INCREMENT cursor = connection.cursor() n = meta['last_upload_id'] + 1 cursor.execute('ALTER TABLE SyncLog AUTO_INCREMENT=%d' % n) return create_success_dict(msg='数据恢复成功!') except: traceback.print_exc()
def _get_classes_teachers(node_uuid, node_type, request): timelog = [] if node_type == 'grade': # 该年级的所有班级和教师 g = models.Grade.is_computerclass(node_uuid) if g: node_uuid = g.term.school.uuid classes = models.Class.objects.filter(grade__term__school=node_uuid) else: classes = models.Class.objects.filter(grade__uuid=node_uuid) timelog.append({'4-11': str(datetime.datetime.now())}) if not is_admin(request.current_user): groups = request.current_user.permitted_groups.all() timelog.append({'4-12': str(datetime.datetime.now())}) classes = classes.filter(grade__term__school__in=groups) timelog.append({'4-13': str(datetime.datetime.now())}) else: # 该级别的所有班级和教师 schools = _get_schools(node_uuid, node_type, request) timelog.append({'4-21': str(datetime.datetime.now())}) terms = simplecache.Term.get_current_term_list(node_uuid, schools) timelog.append({'4-22': str(datetime.datetime.now())}) classes = models.Class.objects.filter(grade__term__in=terms) timelog.append({'4-23': str(datetime.datetime.now())}) teachers = _get_teacher_uuids(node_uuid, node_type, classes) if node_type == 'grade' and g: # TODO 数据筛选真坑啊... 这些处理果断得重写. classes = classes.filter(grade__number=13) timelog.append({'4-4': str(datetime.datetime.now())}) return classes, teachers, timelog
def delete(request, *args, **kwargs): if request.method == 'POST': uu = request.POST.get('uuid') record = models.User.objects.get(uuid=uu) if not is_admin(record): if request.current_user.username == record.username: return create_failure_dict(msg='当前登录用户无法删除!') models.UserPermittedGroup.objects.filter(user=record).delete() record.delete() return create_success_dict(msg='删除用户成功!') else: return create_failure_dict(msg='超级管理员不允许删除!')
def details(request, *args, **kwargs): timelog = [] timelog.append({'start': str(datetime.datetime.now())}) curruser = model_to_dict(request.current_user) timelog.append({'1': str(datetime.datetime.now())}) k = 'permitted-groups-%s' % curruser['uuid'] v = cache.get(k) if v: curruser['permitted_groups'] = cPickle.loads(v) else: q = models.Group.objects.filter( userpermittedgroup__user=curruser['uuid']) curruser['permitted_groups'] = model_list_to_dict(q) v = cPickle.dumps(curruser['permitted_groups'], cPickle.HIGHEST_PROTOCOL) cache.set(k, v, get_timeout(k, None)) timelog.append({'3': str(datetime.datetime.now())}) curruser['role_name'] = '' curruser['privileges'] = [] curruser['superuser'] = False timelog.append({'4': str(datetime.datetime.now())}) if is_admin(request.current_user): curruser['role_name'] = '超级管理员' curruser['superuser'] = True timelog.append({'5-11': str(datetime.datetime.now())}) server_type = models.Setting.getvalue('server_type') timelog.append({'5-12': str(datetime.datetime.now())}) if server_type not in settings_privileges.PRIVILEGES: privileges = copy.deepcopy( settings_privileges.PRIVILEGES['school']) else: privileges = copy.deepcopy( settings_privileges.PRIVILEGES[server_type]) timelog.append({'5-13': str(datetime.datetime.now())}) curruser['privileges'] = get_all_privilege_keys(privileges) timelog.append({'5-14': str(datetime.datetime.now())}) else: if request.current_user.role: curruser['role_name'] = request.current_user.role.name timelog.append({'5-21': str(datetime.datetime.now())}) rp = request.current_user.role.roleprivilege_set.all() timelog.append({'5-22': str(datetime.datetime.now())}) curruser['privileges'] = [i.privilege for i in rp] timelog.append({'5-23': str(datetime.datetime.now())}) timelog.append({'end': str(datetime.datetime.now())}) return create_success_dict(data=curruser, timelog=timelog)
def _inner(request, *args, **kwargs): if not is_admin(request.current_user): privilege_keys = privilege_key.split(',') for i in privilege_keys: ret = create_failure_dict(status='permission_denied', msg='您没有权限访问当前功能!') if not request.current_user.role: # 当前用户没有配置角色 return ret else: r = request.current_user.role count = r.roleprivilege_set.filter(privilege=i).count() if count == 0: # 当前用户的角色没有该权限 return ret return func(request, *args, **kwargs)
def list_current(request, *args, **kwargs): page_info = get_page_info(request) school_year = request.GET.get('school_year') term_type = request.GET.get('term_type') # terms = models.Term.get_current_term_list() terms = models.Term.objects.filter(deleted=False) q = models.LessonPeriod.objects.filter(term__in=terms) if models.Setting.getvalue('server_type') != 'school': q = q.order_by().values('sequence').distinct() return create_success_dict(data={'records': model_list_to_dict(q)}) else: if not is_admin(request.current_user): if not request.current_user.role: return create_failure_dict(status='permission_denied', msg='您没有权限访问当前功能!') count = request.current_user.role.roleprivilege_set count = count.filter(privilege='system_lesson_period').count() if count == 0: return create_failure_dict(status='permission_denied', msg='您没有权限访问当前功能!') if school_year: q = q.filter(school_year=school_year) if term_type: q = q.filter(term_type=term_type) q = q.values('uuid', 'term__school_year', 'term__term_type', 'sequence', 'start_time', 'end_time') page_data = db_utils.pagination(q, **page_info) data = { 'records': model_list_to_dict(page_data['records']), 'page': page_data['page_num'], 'page_size': page_data['page_size'], 'record_count': page_data['record_count'], 'page_count': page_data['page_count'], } try: term = models.Term.get_current_term_list()[0] max_sequence = models.LessonPeriod.objects.filter(term=term) max_sequence = max_sequence.aggregate(Max('sequence')) # print max_sequence data['max_sequence'] = max_sequence['sequence__max'] except: pass return create_success_dict(data=data)
def edit(request, *args, **kwargs): if request.method == 'POST': try: uu = request.POST.get('uuid') user = models.User.objects.get(uuid=uu) if is_admin(user): role = request.POST.get('role', None) status = request.POST.get('status', None) if role: return create_failure_dict(msg='不允许修改超级管理员用户的角色') if status == 'suspended': return create_failure_dict(msg='超级管理员用户不可停用') user_form = UserForm(request.POST, instance=user) groups = request.POST.get('permitted_groups').split(',') if user_form.is_valid(): u = user_form.save() u.userpermittedgroup_set.all().delete() for i in groups: try: g = models.Group.objects.get(uuid=i) user = models.UserPermittedGroup(user=u, group=g) user.save() except: pass k = 'permitted-groups-%s' % uu cache.delete(k) k = 'group-%s' % uu cache.delete(k) data = model_to_dict(u) if data['role']: data['role__name'] = u.role.name return create_success_dict(msg='编辑用户成功!', data=data) return create_failure_dict(msg='编辑用户失败!', errors=user_form.errors) except: traceback.print_exc() return create_failure_dict(msg='错误的uuid!')
def privileges(request, *args, **kwargs): server_type = models.Setting.getvalue('server_type') if server_type not in settings_privileges.PRIVILEGES: privileges = settings_privileges.PRIVILEGES['school'] else: privileges = settings_privileges.PRIVILEGES[server_type] ret = [] if is_admin(request.current_user): ret = privileges else: try: ps = request.current_user.role.roleprivilege_set.all() u = [i.privilege for i in ps] except: return create_failure_dict(msg='该用户未设置角色!') for i in privileges: d = {} d = {'key': i['key'], 'name': i['name'], 'privileges': []} d['privileges'] = [j for j in i['privileges'] if j['key'] in u] if len(d['privileges']) > 0: ret.append(d) return create_success_dict(data=ret)
def _get_schools(node_uuid, node_type, request): if node_type == 'province': schools = models.Group.objects.filter(group_type='school', parent__parent__parent__parent__uuid=node_uuid) elif node_type == 'city': schools = models.Group.objects.filter(group_type='school', parent__parent__parent__uuid=node_uuid) elif node_type == 'country': schools = models.Group.objects.filter(group_type='school', parent__parent__uuid=node_uuid) elif node_type == 'town': schools = models.Group.objects.filter(group_type='school', parent__uuid=node_uuid) elif node_type == 'school': schools = models.Group.objects.filter(group_type='school', uuid=node_uuid) else: return [] if not is_admin(request.current_user): permitted_groups = request.current_user.permitted_groups.all() schools = schools.filter(uuid__in=permitted_groups) return schools
def grid_data(request, *args, **kwargs): '''使用记录->班班通登录日志''' page_info = get_page_info(request) start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') lesson_period = request.GET.get('lesson_period') country_name = request.GET.get('country_name') town_name = request.GET.get('town_name') school_name = request.GET.get('school_name') grade_name = request.GET.get('grade_name') class_name = request.GET.get('class_name') lesson_name = request.GET.get('lesson_name') teacher_name = request.GET.get('teacher_name') only_computerclass = kwargs.get('cc', False) if not end_date and not lesson_period \ and not grade_name and not class_name and not lesson_name \ and not teacher_name and not town_name and not school_name \ and not country_name: e = parse_date(end_date) if e == datetime.date.today(): data = force_index_query(page_info) return create_success_dict(data=data) t = models.TeacherLoginLog.objects.all() if only_computerclass: logs_base = models.TeacherLoginLogTag.objects.all() cc_name = request.GET.get('class_name', request.GET.get('name', request.GET.get('grade_name'))) if cc_name: logs_base = logs_base.filter(created_at__name=cc_name) t = t.filter(teacherloginlogtag__in=logs_base) if start_date and end_date: s = parse_date(start_date) e = parse_date(end_date) + datetime.timedelta(days=1) s = datetime.datetime.combine(s, datetime.time()) e = datetime.datetime.combine(e, datetime.time()) t = t.filter(created_at__range=(s, e)) if lesson_period: t = t.filter(lesson_period_sequence=lesson_period) if grade_name and not only_computerclass: t = t.filter(grade_name=grade_name) if class_name and not only_computerclass: t = t.filter(class_name=class_name) if lesson_name: t = t.filter(lesson_name__contains=lesson_name) if teacher_name: t = t.filter(teacher_name__contains=teacher_name) if country_name: t = t.filter(country_name=country_name) if town_name: t = t.filter(town_name=town_name) if school_name: t = t.filter(school_name=school_name) if not is_admin(request.current_user): permitted_groups = request.current_user.permitted_groups.all() uuids = [g.uuid for g in permitted_groups] t = t.filter(school__uuid__in=uuids) t = t.order_by('-created_at') # 这是老的方法 ''' values = t.values('province_name', 'city_name', 'country_name', 'town_name', 'school_name', 'grade_name', 'class_name', 'teacher_name', 'lesson_period_sequence', 'lesson_name', 'created_at', 'teacherlogintime__login_time', 'teacherlogintimetemp') ''' ''' 这个方法有几个严重的性能问题: 1. teacherlogintime__login_time和teacherlogintimetemp在其他表里, 获取values会导致两次LEFT OUTER JOIN 2. 获取record_count时,SQL语句是SELECT COUNT(*) FROM (SELECT ...) subquery, MySQL对subquery的优化很差(MariaDB可以解决此问题) 3. 上述两点相加导致查询时获取了大量无用数据 程序上的解决办法是: 1. QuerySet.values()只获取TeacherLoginLog的字段,其他字段通过format_record取得, 每个页面只需要取25条相关数据 2. record_count只使用TeacherLoginLog计算 ''' if only_computerclass: values = t.values('uuid', 'town_name', 'school_name', 'grade_name', 'class_name', 'teacher_name', 'lesson_period_sequence', 'lesson_name', 'created_at', 'teacherloginlogtag__created_at__grade__name', 'teacherloginlogtag__created_at__name') else: values = t.values('uuid', 'town_name', 'school_name', 'grade_name', 'class_name', 'teacher_name', 'lesson_period_sequence', 'lesson_name', 'created_at') # changed at 2015-01-23 add 'total' records, data = page_object(request, values) records = format_record.activity_logged_in_new(records) data['total'] = t.count() data['records'] = list(records) return create_success_dict(data=data)
def grid_data(request, *args, **kwargs): '''使用记录->班班通未登录日志''' page_info = get_page_info(request) start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') lesson_period = request.GET.get('lesson_period') country_name = request.GET.get('country_name') town_name = request.GET.get('town_name') school_name = request.GET.get('school_name') grade_name = request.GET.get('grade_name') class_name = request.GET.get('class_name') lesson_name = request.GET.get('lesson_name') teacher_name = request.GET.get('teacher_name') if not end_date and not lesson_period \ and not grade_name and not class_name and not lesson_name \ and not teacher_name and not town_name and not school_name \ and not country_name: e = parse_date(end_date) if e == datetime.date.today(): data = force_index_query(page_info) return create_success_dict(data=data) t = models.TeacherAbsentLog.objects.all() if start_date and end_date: s = parse_date(start_date) e = parse_date(end_date) + datetime.timedelta(days=1) s = datetime.datetime.combine(s, datetime.time()) e = datetime.datetime.combine(e, datetime.time()) t = t.filter(created_at__range=(s, e)) if lesson_period: t = t.filter(lesson_period_sequence=lesson_period) if grade_name: t = t.filter(grade_name=grade_name) if class_name: t = t.filter(class_name=class_name) if lesson_name: t = t.filter(lesson_name__contains=lesson_name) if teacher_name: t = t.filter(teacher_name__contains=teacher_name) if country_name: t = t.filter(country_name=country_name) if town_name: t = t.filter(town_name=town_name) if school_name: t = t.filter(school_name=school_name) if not is_admin(request.current_user): permitted_groups = request.current_user.permitted_groups.all() uuids = [g.uuid for g in permitted_groups] t = t.filter(school__uuid__in=uuids) values = t.values('province_name', 'city_name', 'country_name', 'town_name', 'school_name', 'grade_name', 'class_name', 'teacher_name', 'lesson_period_sequence', 'lesson_name', 'created_at') paginator = Paginator(values, page_info['page_size']) records = list(paginator.page(page_info['page_num']).object_list) page = page_info['page_num'] page_size = page_info['page_size'] record_count = paginator.count page_count = paginator.num_pages return create_success_dict(data={ 'records': records, 'page': page, 'page_size': page_size, 'record_count': record_count, 'page_count': page_count, })