Example #1
0
def del_module(request):
    response = {"success": False, "error": ""}
    try:
        # 校验参数
        module_id = request.POST.get("moduleId", None)

        if module_id is None or str(module_id).strip() == "":
            response["error"] = "必要参数为空!"
            return HttpResponse(json.dumps(response),
                                mimetype="application/json")

        path = request.path
        is_sys = None
        if path == '/customer/system/list/':
            is_sys = True
        elif path == '/customer/list/':
            is_sys = False
        else:
            is_sys = False
        customers = Customer.objects(is_sys=is_sys).order_by('+tag')
        error = request.GET.get("error", None)

        # 执行删除操作
        module = Module.objects(pk=module_id)
        if len(module) == 0:
            response["error"] = "未找到该模块!"
            return HttpResponse(json.dumps(response),
                                mimetype="application/json")

        module = module[0]
        for item in module.files:
            if not isinstance(item, DBRef):
                item.delete()
        for item in module.runInfos:
            if not isinstance(item, DBRef):
                item.delete()
        for customer in customers:
            cus_modules = customer.modules
            for cus_module in cus_modules:
                if module.name == cus_module.name:
                    response["error"] = "此模块被客户[%s]使用,不能删除!" % str(
                        customer.name)
                    return HttpResponse(json.dumps(response),
                                        mimetype="application/json")

        module.delete()
        response["success"] = True
        response["error"] = "执行成功!"
        return HttpResponse(json.dumps(response), mimetype="application/json")
    except Exception, e:
        response["error"] = "系统异常![%s]" % str(e)
        logger.error(response["error"] + getTraceBack())
        return HttpResponse(json.dumps(response), mimetype="application/json")
Example #2
0
def view_modules(request):
    if request.user.is_authenticated:
        if request.method == 'POST' and checkRole(request, 'admin'):
            moduleObj = Module(moduleCode=request.POST['moduleCode'],
                               moduleName=request.POST['moduleName'])
            moduleObj.save()

        modules = Module.objects.all()

        # getting all modules enrolled by "request.user"
        # from module model
        enrolledModules = request.user.student.all()

        context_variable = {
            'modules': modules,
            'enrolledModules': enrolledModules,
            'staff_roles': STAFF_ROLES
        }
        return render(request, 'modules.html', context_variable)
    messages.error(request, "Login to view modules")
    return redirect('/')
Example #3
0
def removeInvalidModule(request):
    machines = Machine.objects()
    for machine in machines:
        invalidModules = []
        for module in machine.modules:
            if type(module) != type(Module()):
                invalidModules.append(module)
        if len(invalidModules) > 0:
            for module in invalidModules:
                machine.modules.remove(module)
            print machine.name, "saved"
            machine.save()
    return HttpResponse("成功")
Example #4
0
def handle_del_module(request, fn, log):
    """
    处理删除模块
    :param request:
    :param fn:
    """
    resp = None
    is_success = False
    try:
        module_id = request.POST.get("moduleId", None)

        log = log % '删除模块[id=%s]' % str(module_id)

        old_obj = Module.objects(pk=module_id)[0]
        old_version = old_obj.version
        old_json = convert_module_to_json(old_obj)

        # 执行方法
        resp = fn(request)

        # 解析响应
        resp_json = json.loads(resp.content)
        is_success = resp_json["success"]

        core_log = CoreLogger()
        core_log.collection = 'module'
        core_log.operate_type = OPERATE_DELETE
        core_log.result_type = RESULT_TYPE_SUCCESS if is_success else RESULT_TYPE_FAILURE
        core_log.old_version = old_version
        core_log.old_data = json.dumps(old_json, ensure_ascii=False).encode(ENCODE)
        core_log.new_version = None
        core_log.new_data = None
        core_log.response = json.dumps(resp_json, ensure_ascii=False).encode(ENCODE)
        core_log.create_time = datetime.datetime.now()
        core_log.create_user = User.objects(username=request.user.username)[0]
        core_log.save()

        log += ' --> 执行成功!'
    except Exception as e:
        log += ' --> 记录过程异常![%s]' % str(e)
    finally:
        logger.info(log) if is_success else logger.error(log)
        return resp
Example #5
0
def view(request):
    if request.method == 'GET':
        try:
            is_view = True
            module_id = request.GET.get("module_id", None)

            if module_id is None or module_id == '':
                error = "模块ID为空!"
                logger.error(error)
                return render_to_response(
                    "item/temp.html",
                    locals(),
                    context_instance=RequestContext(request))
            module = Module.objects(pk=module_id)

            if len(module) == 0:
                error = "模块[ID=%s]并不存在!" % module_id
                logger.error(error)
                return render_to_response(
                    "item/temp.html",
                    locals(),
                    context_instance=RequestContext(request))

            groups = Group.objects()
            module = module[0]
            return render_to_response("module/module_create.html",
                                      locals(),
                                      context_instance=RequestContext(request))
        except Exception as e:
            error = '查看模块信息异常[%s]' % str(e)
            logger.error(error + getTraceBack())
            return render_to_response('item/temp.html',
                                      locals(),
                                      context_instance=RequestContext(request))
    elif request.method == 'POST':
        error = "非法请求方式!"
        logger.error(error)
        return render_to_response('item/temp.html',
                                  locals(),
                                  context_instance=RequestContext(request))
Example #6
0
def save(request):
    username = request.user.username

    # create module
    module_name = request.POST.get("name")
    module_description = request.POST.get('description')
    module_wiki_link = request.POST.get('wiki_link')
    module = Module.create(module_name, module_description, module_wiki_link,
                           username)

    # create module
    # version_comment = request.POST.get('comment')
    version_type = request.POST.get("type")
    version_file = request.POST.get("file")
    version_file_identifier = request.POST.get("file_identifier")
    version_options = request.POST.get("options")
    version_git_options = request.POST.get("git_options")

    try:
        logger.info("save new module, file %s, identifier %s", version_file,
                    version_file_identifier)
        module_version = ModuleVersions.create(module.id, '', version_type,
                                               version_file,
                                               version_git_options, False,
                                               version_options, username)
        if not version_file_identifier:
            resumable_wrapper.remove(version_file_identifier)
        logger.debug("module saved")
    except ObjectDoesNotExist as e:
        context = {'status': -1, 'error': 'please upload file first'}
        return HttpResponse(json.dumps(context), mimetype="application/json")

    context = {
        'status': 1,
        'module_id': module.id,
        'version_id': module_version.id
    }
    return HttpResponse(json.dumps(context), mimetype="application/json")
Example #7
0
def handle_modify_module(request, fn, log):
    """
    处理创建或编辑模块
    :param request:
    :param fn:
    """
    resp = None
    is_success = False
    try:
        # 获取参数
        request_json = json.loads(request.POST.get("json"))
        # 模块ID
        module_id = request_json["moduleId"]
        log = log % ('创建模块[id=%s]' % None) if module_id is None else ('编辑模块[id=%s]' % str(module_id))

        # 记录参数
        old_obj = None
        if module_id is not None:
            old_obj = Module.objects(pk=module_id)[0]

        old_json = None
        old_version = None
        if old_obj is not None:
            old_version = old_obj.version
            old_json = convert_module_to_json(old_obj)

        log += '旧数据版本 : [%s] ; ' % None if old_version is None else old_version.encode(ENCODE)
        log += '旧数据备份 : [%s] ; ' % None if old_json is None else json.dumps(old_json, ensure_ascii=False).encode(ENCODE)

        # 执行方法
        resp = fn(request)
        # 执行方法end
        # 方法响应参数
        resp_json = json.loads(resp.content)

        new_json = None
        new_version = None

        if module_id is not None:
            new_module = Module.objects(pk=module_id)[0]
            new_version = new_module.version
            new_json = convert_module_to_json(new_module)
        elif resp_json['id'] is not None:
            new_module = Module.objects(pk=resp_json['id'])[0]
            new_version = new_module.version
            new_json = convert_module_to_json(new_module)

        log += '新数据版本 : [%s] ; ' % new_version.encode(ENCODE)
        log += '新数据备份 : [%s] ; ' % json.dumps(new_json, ensure_ascii=False).encode(ENCODE)

        is_success = resp_json['success']

        core_log = CoreLogger()
        core_log.collection = 'module'
        core_log.operate_type = OPERATE_CREATE if module_id is None else OPERATE_UPDATE
        core_log.result_type = RESULT_TYPE_SUCCESS if is_success else RESULT_TYPE_FAILURE
        core_log.old_version = old_version
        core_log.old_data = None if old_json is None else json.dumps(old_json, ensure_ascii=False).encode(ENCODE)
        core_log.new_version = new_version
        core_log.new_data = json.dumps(new_json, ensure_ascii=False).encode(ENCODE)
        core_log.response = json.dumps(resp_json, ensure_ascii=False).encode(ENCODE)
        core_log.create_time = datetime.datetime.now()
        core_log.create_user = User.objects(username=request.user.username)[0]
        core_log.save()

        log += ' --> 执行成功!'
    except Exception as e:
        log += ' --> 记录过程异常![%s]\n[%s]' % (str(e), getTraceBack())
    finally:
        logger.info(log) if is_success else logger.error(log)
        return resp
Example #8
0
def create(request):
    if request.method == "GET":
        p_id = request.GET.get('p_id', None)
        is_extends = False
        module = None

        if p_id:
            is_extends = True
            module = Module.objects.get(pk=p_id)
        groups = Group.objects()
        return render_to_response("module/module_create.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    elif request.method == 'POST':
        response = {"success": False, "error": "", "id": None}
        try:
            # 获取参数
            request_json = json.loads(request.POST.get("json"))
            now = datetime.datetime.now()
            # 校验参数
            module_id = request_json["moduleId"]
            module_name = request_json["moduleName"]
            module_remark = request_json["module_remark"]
            module_group = request_json["module_group"]
            module = None
            if module_id is not None:
                module = Module.objects.get(pk=module_id)
                module_by_name = Module.objects(name=module_name)
                if len(module_by_name) > 0:
                    if len(module_by_name) > 1:
                        response["error"] = "模块名称重复!"
                        logger.error(response["error"])
                        return HttpResponse(json.dumps(response),
                                            mimetype="application/json")

                    module_by_name = module_by_name[0]
                    if module_by_name.id != module.id:
                        response["error"] = "模块名称重复!"
                        logger.error(response["error"])
                        return HttpResponse(json.dumps(response),
                                            mimetype="application/json")
            else:
                module_by_name = Module.objects(name=module_name)
                if len(module_by_name) > 0:
                    response["error"] = "模块名称重复!"
                    logger.error(response["error"])
                    return HttpResponse(json.dumps(response),
                                        mimetype="application/json")
                module = Module()

            # 保存
            # 先保存文件信息
            runInfoList = request_json["runInfoList"]
            run_info_list = []
            for item in runInfoList:
                run_info = None
                run_info_id = item["runInfoId"]
                if run_info_id is not None:
                    run_info = RunInfo.objects(pk=run_info_id)[0]
                else:
                    run_info = RunInfo()
                run_info.run_info_name = item["run_info_name"]
                run_info.workingDir = item["workingDir"]
                run_info.runParam = item["runParam"]
                run_info.runType = item["runType"]
                run_info.timerParam = item["timerParam"]
                run_info.save()
                run_info_list.append(run_info)

            # 保存文件信息
            fileInfoList = request_json["fileInfoList"]
            file_info_list = []
            for item in fileInfoList:
                file_info_id = item["fileInfoId"]
                if file_info_id is not None:
                    file_info = FileInfo.objects(pk=file_info_id)[0]
                else:
                    file_info = FileInfo()
                file_info.filePath = item["filePath"]
                file_info.mod = item["mod"]
                file_info.descript = item["descript"]
                file_info.fileType = item["file_type"]
                file_info.rawPath = item["rawPath"]
                file_info.remark = item["remark"]
                if file_info_id is None:
                    file_info.createTime = now
                file_info.updateTime = now
                file_info.save()
                file_info_list.append(file_info)

            # 保存模块信息
            module.name = module_name
            module.head = request_json["moduleHead"]
            module.remark = module_remark
            module.version = VERSION_PREFIX_MODULE + str(
                int(time.time() * 1000))
            module.group = module_group
            # 删除已删除的file和run信息
            for item in set(module.files) - set(file_info_list):
                if type(item) is not DBRef:
                    item.delete()
            for item in set(module.runInfos) - set(run_info_list):
                if type(item) is not DBRef:
                    item.delete()

            module.files = file_info_list
            module.runInfos = run_info_list
            if module_id is None:
                module.createTime = now
            module.save()

            response["success"] = True
            response["id"] = str(module.id)
            response["error"] = "执行成功!"
            return HttpResponse(json.dumps(response),
                                mimetype="application/json")
        except Exception, e:
            response["error"] = "系统异常![%s]" % str(e)
            logger.error(response["error"] + getTraceBack())
            return HttpResponse(json.dumps(response),
                                mimetype="application/json")
Example #9
0
def groupList(request):
    groups = Group.objects().order_by("name")
    modules = Module.objects().order_by("name")
    return render_to_response("module/module_group.html",
                              locals(),
                              context_instance=RequestContext(request))