コード例 #1
0
def delete_question(request):
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    if not get_system(session, request.user.id):
        return error_response()

    try:
        q_id = int(request.POST.get("id"))
        if q_id and q_id > 0:
            Question.objects.get(id=q_id).delete()
    except Question.DoesNotExist:
        pass
    except ValueError as e:
        log.exception(e)
        return error_response()

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #2
0
ファイル: questions.py プロジェクト: Abashinos/ExpertSystem
def delete_question(request):
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    if not get_system(session, request.user.id):
        return error_response()

    try:
        q_id = int(request.POST.get("id"))
        if q_id and q_id > 0:
            Question.objects.get(id=q_id).delete()
    except Question.DoesNotExist:
        pass
    except ValueError as e:
        log.exception(e)
        return error_response()

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #3
0
def delete_attribute(request):
    """
    Удаление атрибута
    :param request: id атрибута
    :return:
    """
    try:
        attribute_id = int(request.POST.get("id"))
        attribute = Attribute.objects.get(id=attribute_id)
        attribute_values = attribute.attributevalue_set.all()
    except (ValueError, Attribute.DoesNotExist) as e:
        log.exception(e)
        return error_response()

    for attr_val in attribute_values:
        _delete_attribute_value(attr_val.id)

    attribute.delete()

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #4
0
ファイル: attributes.py プロジェクト: Abashinos/ExpertSystem
def delete_attribute(request):
    """
    Удаление атрибута
    :param request: id атрибута
    :return:
    """
    try:
        attribute_id = int(request.POST.get("id"))
        attribute = Attribute.objects.get(id=attribute_id)
        attribute_values = attribute.attributevalue_set.all()
    except (ValueError, Attribute.DoesNotExist) as e:
        log.exception(e)
        return error_response()

    for attr_val in attribute_values:
        _delete_attribute_value(attr_val.id)

    attribute.delete()

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #5
0
ファイル: answers.py プロジェクト: Abashinos/ExpertSystem
def insert_answers(request):
    """
    Добавление/редактирование ответов
    :param request:
    {
        "form_data": [
            {
                "id": id вопроса
                "answers": [
                    {
                        "id": id ответа, либо -1
                        "body": значение,
                        "parameter_value": значение параметра, устанавлимое этим ответом
                    }
                ]
            }
        ]
    }
    :return:
    """
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    system = get_system(session, request.user.id)
    if not system:
        return error_response()

    try:
        form_data = json.loads(request.POST.get("form_data"))
    except TypeError as e:
        log.exception(e)
        return error_response()

    for question_element in form_data:
        try:
            question = Question.objects.get(id=question_element['id'], system=system)
        except Question.DoesNotExist:
            log.error("Question #" + str(question_element["id"]) + " doesn\'t exist.")
            continue

        if len(question_element['answers']) > 0:
            for answer in question_element['answers']:
                a_id = answer['id']

                if not answer.get('body'):
                    response = {
                        "code": 1,
                        "msg": u"Заполните все ответы, пожалуйста."
                    }

                    return HttpResponse(json.dumps(response), content_type="application/json")

                if a_id and int(a_id) != -1:
                    # Обновление вопроса
                    try:
                        answer_element = Answer.objects.get(id=a_id)
                    except Answer.DoesNotExist as e:
                        log.error("Answer #" + str(a_id) + " doesn\'t exist.")
                        continue
                    answer_element.body = answer['body']
                    answer_element.parameter_value = answer['parameter_value']
                    answer_element.save()
                else:
                    # Создание вопроса
                    answer_element = Answer(question=question, body=answer['body'], parameter_value=answer['parameter_value'])
                    answer_element.save()
                pass
        else:
            # удалить все ответы для этого вопроса
            Answer.objects.filter(question=question).delete()
    response = {
        "code": 0,
    }
    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #6
0
def insert_attributes(request):
    """
    Добавление/редактирование атрибутов
    :param request:
    {
        "form_data": [
            {
                "id": id атрибута либо -1, если атрибут новый и надо его создать
                "name": имя атрибута
                "values": [
                    {
                        "id": id AttributeValue, либо -1
                        "value": значение
                    }
                ]
            }
        ]
    }
    :return:
    """
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    system = get_system(session, request.user.id)
    if not system:
        return error_response()

    form_data = json.loads(request.POST.get("form_data"))
    attr_names = []
    for attr_json in form_data:
        attr_name = attr_json.get("name")
        if not attr_name:
            response = {
                "code": 1,
                "msg": u"Заполните названия всех атрибутов, пожалуйста"
            }

            return HttpResponse(json.dumps(response),
                                content_type="application/json")
        attr_name = attr_name.lower()
        if attr_name in attr_names:
            response = {
                "code": 1,
                "msg":
                u"Введите различные названия для всех атрибутов, пожалуйста"
            }

            return HttpResponse(json.dumps(response),
                                content_type="application/json")
        attr_names.append(attr_name)

    for attr_json in form_data:
        try:
            attr_id = int(attr_json.get("id"))
        except ValueError as e:
            log.exception(e)
            continue

        if attr_id != -1:
            # Редактируем атрибут
            attribute = Attribute.objects.get(id=attr_id)
            attribute.name = attr_json["name"]
            attribute.save()
            # Обновляем значения:
            # TODO: добавить проверку values
            added_values = []
            for val in attr_json["values"]:
                if val["id"] and int(val["id"]) != -1:
                    attribute_value = AttributeValue.objects.get(id=val["id"])
                    if not val["value"]:
                        attribute_value.delete()
                        continue
                else:
                    attribute_value = AttributeValue(system=system,
                                                     attr=attribute)
                    if not val["value"]:
                        continue

                if val["value"] in added_values:
                    continue

                added_values.append(val["value"])
                attribute_value.value = val["value"]
                attribute_value.save()

        else:
            # Создаем атрибут
            existing_attrs = Attribute.objects.filter(name=attr_json["name"],
                                                      system=system)
            if not existing_attrs:
                attribute = Attribute.objects.create(name=attr_json["name"],
                                                     system=system)
                for val in attr_json["values"]:
                    AttributeValue.objects.create(system=system,
                                                  attr=attribute,
                                                  value=val["value"])
            else:
                response = {
                    "code":
                    1,
                    "msg":
                    u"Введите различные названия для всех атрибутов, пожалуйста"
                }

                return HttpResponse(json.dumps(response),
                                    content_type="application/json")

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #7
0
ファイル: questions.py プロジェクト: Abashinos/ExpertSystem
def insert_questions(request):
    """
    Добавляет объекты
    :param request: {
        "form_data": [
            {
                "id": id параметра,
                "questions": [
                    {
                        "id": id вопроса, либо -1, если вопрос новый
                        "type": тип вопроса (0 или 1),
                        "body": текст вопроса
                    }, ...
                ]
            }, ...
        ]
    }
    :return:
    """
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    system = get_system(session, request.user.id)
    if not system:
        return error_response()

    try:
        formdata = json.loads(request.POST.get('form_data'))
    except TypeError as e:
        log.exception(e)
        return error_response()

    for parameterJSON in formdata:
        try:
            parameter = Parameter.objects.get(id=parameterJSON["id"])
        except Parameter.DoesNotExist:
            log.error("Parameter #" + str(parameterJSON["id"]) + " doesn\'t exist.")
            continue

        for questionJSON in parameterJSON["questions"]:
            question_id = questionJSON["id"]
            if not questionJSON.get("body"):
                response = {
                    "code": 1,
                    "msg": u"Заполните все вопросы, пожалуйста."
                }

                return HttpResponse(json.dumps(response), content_type="application/json")
            if question_id and question_id != "-1":
                try:
                    question = Question.objects.get(id=question_id)
                except Question.DoesNotExist:
                    log.error("Question #" + str(question_id) + " doesn\'t exist.")
                    continue
            else:
                question = Question(system=system, parameter=parameter)
            question.type = questionJSON["type"]
            question.body = questionJSON["body"]
            question.save()

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #8
0
def insert_questions(request):
    """
    Добавляет объекты
    :param request: {
        "form_data": [
            {
                "id": id параметра,
                "questions": [
                    {
                        "id": id вопроса, либо -1, если вопрос новый
                        "type": тип вопроса (0 или 1),
                        "body": текст вопроса
                    }, ...
                ]
            }, ...
        ]
    }
    :return:
    """
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    system = get_system(session, request.user.id)
    if not system:
        return error_response()

    try:
        formdata = json.loads(request.POST.get('form_data'))
    except TypeError as e:
        log.exception(e)
        return error_response()

    for parameterJSON in formdata:
        try:
            parameter = Parameter.objects.get(id=parameterJSON["id"])
        except Parameter.DoesNotExist:
            log.error("Parameter #" + str(parameterJSON["id"]) +
                      " doesn\'t exist.")
            continue

        for questionJSON in parameterJSON["questions"]:
            question_id = questionJSON["id"]
            if not questionJSON.get("body"):
                response = {
                    "code": 1,
                    "msg": u"Заполните все вопросы, пожалуйста."
                }

                return HttpResponse(json.dumps(response),
                                    content_type="application/json")
            if question_id and question_id != "-1":
                try:
                    question = Question.objects.get(id=question_id)
                except Question.DoesNotExist:
                    log.error("Question #" + str(question_id) +
                              " doesn\'t exist.")
                    continue
            else:
                question = Question(system=system, parameter=parameter)
            question.type = questionJSON["type"]
            question.body = questionJSON["body"]
            question.save()

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #9
0
ファイル: attributes.py プロジェクト: Abashinos/ExpertSystem
def insert_attributes(request):
    """
    Добавление/редактирование атрибутов
    :param request:
    {
        "form_data": [
            {
                "id": id атрибута либо -1, если атрибут новый и надо его создать
                "name": имя атрибута
                "values": [
                    {
                        "id": id AttributeValue, либо -1
                        "value": значение
                    }
                ]
            }
        ]
    }
    :return:
    """
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    system = get_system(session, request.user.id)
    if not system:
        return error_response()

    form_data = json.loads(request.POST.get("form_data"))
    attr_names = []
    for attr_json in form_data:
        attr_name = attr_json.get("name")
        if not attr_name:
            response = {
                "code": 1,
                "msg": u"Заполните названия всех атрибутов, пожалуйста"
            }

            return HttpResponse(json.dumps(response), content_type="application/json")
        attr_name = attr_name.lower()
        if attr_name in attr_names:
            response = {
                "code": 1,
                "msg": u"Введите различные названия для всех атрибутов, пожалуйста"
            }

            return HttpResponse(json.dumps(response), content_type="application/json")
        attr_names.append(attr_name)

    for attr_json in form_data:
        try:
            attr_id = int(attr_json.get("id"))
        except ValueError as e:
            log.exception(e)
            continue

        if attr_id != -1:
            # Редактируем атрибут
            attribute = Attribute.objects.get(id=attr_id)
            attribute.name = attr_json["name"]
            attribute.save()
            # Обновляем значения:
            # TODO: добавить проверку values
            added_values = []
            for val in attr_json["values"]:
                if val["id"] and int(val["id"]) != -1:
                    attribute_value = AttributeValue.objects.get(id=val["id"])
                    if not val["value"]:
                        attribute_value.delete()
                        continue
                else:
                    attribute_value = AttributeValue(system=system, attr=attribute)
                    if not val["value"]:
                        continue

                if val["value"] in added_values:
                    continue

                added_values.append(val["value"])
                attribute_value.value = val["value"]
                attribute_value.save()

        else:
            # Создаем атрибут
            existing_attrs = Attribute.objects.filter(name=attr_json["name"], system=system)
            if not existing_attrs:
                attribute = Attribute.objects.create(name=attr_json["name"], system=system)
                for val in attr_json["values"]:
                    AttributeValue.objects.create(system=system, attr=attribute, value=val["value"])
            else:
                response = {
                    "code": 1,
                    "msg": u"Введите различные названия для всех атрибутов, пожалуйста"
                }

                return HttpResponse(json.dumps(response), content_type="application/json")


    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #10
0
ファイル: parameters.py プロジェクト: Abashinos/ExpertSystem
def insert_parameters(request):
    """
    Добавление/редактирование параметров
    :param request:
    {
        "form_data": [
            {
                "id": id параметра либо -1, если параметр новый и надо его создать
                "name": имя атрибута
            }
        ]
    }
    :return:
    """
    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    system = get_system(session, request.user.id)
    if not system:
        return error_response()

    form_data = json.loads(request.POST.get("form_data"))
    param_names = []
    for param_json in form_data:
        param_name = param_json.get("name")
        if not param_name:
            response = {
                "code": 1,
                "msg": u"Заполните названия всех параметров, пожалуйста"
            }

            return HttpResponse(json.dumps(response), content_type="application/json")
        param_name = param_name.lower()
        if param_name in param_names:
            response = {
                "code": 1,
                "msg": u"Введите различные названия для всех параметров, пожалуйста"
            }

            return HttpResponse(json.dumps(response), content_type="application/json")
        param_names.append(param_name)

    for param_json in form_data:
        try:
            param_id = int(param_json.get("id"))
        except ValueError as e:
            log.exception(e)
            continue

        if not param_json["name"]:
            response = {
                "code": 1,
                "msg": u"Заполните названия всех параметров, пожалуйста"
            }

            return HttpResponse(json.dumps(response), content_type="application/json")

        if param_id != -1:
            # Редактируем параметр
            try:
                parameter = Parameter.objects.get(id=param_id)
            except Parameter.DoesNotExist:
                parameter = None

            if parameter:
                parameter.name = param_json["name"]
                parameter.save()
                continue

        # Создаем параметр
        existing_params = Parameter.objects.filter(name=param_json["name"], system=system)
        if not existing_params:
            Parameter.objects.create(name=param_json["name"], system=system)
        else:
            response = {
                "code": 1,
                "msg": u"Введите различные названия для всех параметров, пожалуйста"
            }

            return HttpResponse(json.dumps(response), content_type="application/json")

    response = {
        "code": 0,
    }

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #11
0
def insert_system(request):

    response = {
        "code": 0,
    }

    system_name = request.POST.get("system_name")
    system_about = request.POST.get("system_about")
    system_public = True if request.POST.get("system_public") else False
    system_open = True if request.POST.get("system_open") else False
    system_pic = request.FILES.get('system_pic')

    if not system_name:
        response = {'code': 1, 'msg': u'Введите название системы'}
        return HttpResponse(json.dumps(response),
                            content_type="application/json")

    if system_pic:
        try:
            trial_image = Image.open(system_pic)
            trial_image.verify()
        except IOError:
            response = {'code': 1, 'msg': u'Загрузите корректную картинку.'}
            return HttpResponse(json.dumps(response),
                                content_type="application/json")
        except Exception as e:
            log.exception(e)
            response = {'code': 1, 'msg': u'Загрузите корректную картинку.'}
            return HttpResponse(json.dumps(response),
                                content_type="application/json")

    session = request.session.get(sessions.SESSION_ES_CREATE_KEY)
    if session:
        try:
            system = System.objects.get(id=session["system_id"],
                                        is_deleted=False)
        except System.DoesNotExist:
            log.error("System " + session["system_id"] + " doesn\'t exist.")
            response = {
                'code': 1,
                'msg':
                u'Системы не существует. Попробуйте заново создать систему.'
            }
            return HttpResponse(json.dumps(response),
                                content_type="application/json")

        system.name = system_name
        system.about = system_about
        system.is_open_for_guests = system_open
        system.is_public = system_public
        if system_pic:
            system.photo = system_pic
        try:
            system.save()
        except Exception as e:
            log.exception(e)
            return error_response()

        response['system_id'] = system.id
        return HttpResponse(json.dumps(response),
                            content_type="application/json")

    params = {
        "name": system_name,
        "user": request.user,
        "about": system_about,
        "is_open_for_guests": system_open,
        "is_public": system_public
    }
    if system_pic:
        params.update({"photo": system_pic})
    try:
        system = System.objects.create(**params)
        response['system_id'] = system.id
    except Exception as e:
        log.exception(e)
        return error_response()

    sessions.init_es_create_session(request, system.id)
    return HttpResponse(json.dumps(response), content_type="application/json")