• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python util.is_valid_string_maxsize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkapi.util.is_valid_string_maxsize函数的典型用法代码示例。如果您正苦于以下问题:Python is_valid_string_maxsize函数的具体用法?Python is_valid_string_maxsize怎么用?Python is_valid_string_maxsize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了is_valid_string_maxsize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: validate_filter

    def validate_filter(self, filter_map):
        '''Validates filter fields before add

        @param filter_map: Map with the data of the request.

        @raise InvalidValueError: Represents an error occurred validating a value.
        '''

        # Get XML data
        name = filter_map['name']
        description = filter_map['description']

        # name can NOT be greater than 100
        if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100) or not is_valid_text(name):
            self.log.error(u'Parameter name is invalid. Value: %s.', name)
            raise InvalidValueError(None, 'name', name)

        # description can NOT be greater than 200
        if not is_valid_string_minsize(description, 3, False) or not is_valid_string_maxsize(description, 200, False) or not is_valid_text(description, True):
            self.log.error(
                u'Parameter description is invalid. Value: %s.', description)
            raise InvalidValueError(None, 'description', description)

        # Verify existence
        if len(Filter.objects.filter(name=name).exclude(id=self.id)) > 0:
            raise FilterDuplicateError(
                None, u'Já existe um filtro com o nome %s no banco de dados.' % name)

        # set variables
        self.name = name
        self.description = description
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:31,代码来源:models.py


示例2: valid_option_pool

    def valid_option_pool(self, optionpool_map):
        """Validate the values ​​of option pool

        @param optionpool_map: Map with the data of the request.

        @raise InvalidValueError: Represents an error occurred validating a value.
        """

        # Get XML data
        type = optionpool_map.get('type')
        name = optionpool_map.get('name')

        # type can NOT be greater than 50
        if not is_valid_string_maxsize(type, 50, True) or not is_valid_option(type):
            self.log.error(
                u'Parameter type is invalid. Value: %s.', type)
            raise InvalidValueError(None, 'type', type)

        # name_txt can NOT be greater than 50
        if not is_valid_string_maxsize(name, 50, True) or not is_valid_option(name):
            self.log.error(
                u'Parameter name_txt is invalid. Value: %s.', name)
            raise InvalidValueError(None, 'name', name)

        # set variables
        self.type = type
        self.name = name
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:27,代码来源:models.py


示例3: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para inserir um grupo de equipamento.

        URL: egrupo/
        """
        try:
            if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            xml_map, attrs_map = loads(request.raw_post_data)
            self.log.debug('XML_MAP: %s', xml_map)

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')

            egroup_map = networkapi_map.get('grupo')
            if egroup_map is None:
                return self.response_error(3, u'Não existe valor para a tag grupo do XML de requisição.')

            name = egroup_map.get('nome')
            if not is_valid_string_maxsize(name, 100):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            egroup = EGrupo()
            egroup.nome = name
            egroup.create(user)

            return self.response(dumps_networkapi({'grupo': {'id': egroup.id}}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:33,代码来源:GrupoResource.py


示例4: handle_put

    def handle_put(self, request, user, *args, **kwargs):
        """Treat PUT requests to edit Access Type.

        URL: /tipoacesso/<id_tipo_acesso>/

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(u"User does not have permission to perform the operation.")
                raise UserNotAuthorizedError(None)

            # Valid Access Type ID
            tipo_acesso_id = kwargs.get("id_tipo_acesso")
            if not is_valid_int_greater_zero_param(tipo_acesso_id):
                self.log.error(u"The tipo_acesso_id parameter is not a valid value: %s.", tipo_acesso_id)
                raise InvalidValueError(None, "tipo_acesso_id", tipo_acesso_id)

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get("networkapi")
            if networkapi_map is None:
                return self.response_error(3, u"There is no networkapi tag in request XML.")

            tipo_acesso_map = networkapi_map.get("tipo_acesso")
            if tipo_acesso_map is None:
                return self.response_error(3, u"There is no tipo_acesso tag in request XML.")

            # Valid protocol
            protocol = tipo_acesso_map.get("protocolo")
            if (
                not is_valid_string_minsize(protocol, 3)
                or not is_valid_string_maxsize(protocol, 45)
                or not is_valid_regex(protocol, r"^[- a-zA-Z0-9]+$")
            ):
                self.log.error(u"Parameter protocol is invalid. Value: %s", protocol)
                raise InvalidValueError(None, "protocol", protocol)

            # Verify existence
            tpa = TipoAcesso.get_by_pk(tipo_acesso_id)

            tpa.protocolo = protocol

            try:
                if len(TipoAcesso.objects.filter(protocolo__iexact=protocol).exclude(id=tpa.id)) > 0:
                    raise DuplicateProtocolError(None, u"Access Type with protocol %s already exists" % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            with distributedlock(LOCK_TYPE_ACCESS % tipo_acesso_id):

                try:
                    # save access type
                    tpa.save(user)
                except Exception, e:
                    self.log.error(u"Failed to update TipoAcesso.")
                    raise TipoAcessoError(e, u"Failed to update TipoAcesso.")

            return self.response(dumps_networkapi({}))
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:59,代码来源:TipoAcessoResource.py


示例5: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add Brand.

        URL: brand/
        """

        try:

            self.log.info("Add Brand")

            # User permission
            if not has_perm(user, AdminPermission.BRAND_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            brand_map = networkapi_map.get('brand')
            if brand_map is None:
                return self.response_error(3, u'There is no value to the brand tag  of XML request.')

            # Get XML data
            name = brand_map.get('name')

            # Valid name
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            try:
                Marca.get_by_name(name)
                raise MarcaNameDuplicatedError(
                    None, u'Marca com o nome %s já cadastrada.' % name)
            except MarcaNotFoundError:
                pass

            brand = Marca()

            # set variables
            brand.nome = name

            try:
                # save Brand
                brand.save(user)
            except Exception, e:
                self.log.error(u'Failed to save the Brand.')
                raise EquipamentoError(e, u'Failed to save the Brand.')

            brand_map = dict()
            brand_map['brand'] = model_to_dict(brand, exclude=["nome"])

            return self.response(dumps_networkapi(brand_map))
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:59,代码来源:BrandAddResource.py


示例6: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Trata as requisições de POST para alterar a senha de um Usuario.

        URL: user-change-pass/
        """

        try:
            xml_map, attrs_map = loads(request.raw_post_data)
            self.log.info('Change user password')

            # User permission
            if not has_perm(user, AdminPermission.AUTHENTICATE, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(3, u'Não existe valor para a tag usuario do XML de requisição.')

            # Get XML data
            id_user = user_map.get('user_id')
            password = user_map.get('password')

            # Valid ID User
            if not is_valid_int_greater_zero_param(id_user):
                self.log.error(
                    u'The id_user parameter is not a valid value: %s.', id_user)
                raise InvalidValueError(None, 'id_user', id_user)

            # Valid pwd
            if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45):
                self.log.error(u'Parameter password is invalid. Value: ****')
                raise InvalidValueError(None, 'password', '****')

            # Find User by ID to check if it exist
            usr = Usuario.get_by_pk(id_user)

            with distributedlock(LOCK_USER % id_user):

                # set variable
                usr.pwd = hashlib.md5(password).hexdigest()

                try:
                    # update User
                    usr.save(user)
                except Exception, e:
                    self.log.error(u'Failed to update the user.')
                    raise UsuarioError(e, u'Failed to update the user.')

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:58,代码来源:UsuarioChangePassResource.py


示例7: valid_environment_vip

    def valid_environment_vip(self, environmentvip_map):
        '''Validate the values ​​of environment vip

        @param environmentvip_map: Map with the data of the request.

        @raise InvalidValueError: Represents an error occurred validating a value.
        '''

        # Get XML data
        finalidade_txt = environmentvip_map.get('finalidade_txt')
        cliente_txt = environmentvip_map.get('cliente_txt')
        ambiente_p44_txt = environmentvip_map.get('ambiente_p44_txt')
        description = environmentvip_map.get('description')

        # finalidade_txt can NOT be greater than 50 or lesser than 3
        if not is_valid_string_maxsize(finalidade_txt, 50, True) or not is_valid_string_minsize(finalidade_txt, 3, True) or not is_valid_text(finalidade_txt):
            self.log.error(
                u'Parameter finalidade_txt is invalid. Value: %s.', finalidade_txt)
            raise InvalidValueError(None, 'finalidade_txt', finalidade_txt)

        # cliente_txt can NOT be greater than 50 or lesser than 3
        if not is_valid_string_maxsize(cliente_txt, 50, True) or not is_valid_string_minsize(cliente_txt, 3, True) or not is_valid_text(cliente_txt):
            self.log.error(
                u'Parameter cliente_txt is invalid. Value: %s.', cliente_txt)
            raise InvalidValueError(None, 'cliente_txt', cliente_txt)

        # ambiente_p44_txt can NOT be greater than 50 or lesser than 3
        if not is_valid_string_maxsize(ambiente_p44_txt, 50, True) or not is_valid_string_minsize(ambiente_p44_txt, 3, True) or not is_valid_text(ambiente_p44_txt):
            self.log.error(
                u'Parameter ambiente_p44_txt is invalid. Value: %s.', ambiente_p44_txt)
            raise InvalidValueError(None, 'ambiente_p44_txt', ambiente_p44_txt)

        if not is_valid_string_maxsize(description, 50, True) or not is_valid_string_minsize(description, 3, True) or not is_valid_text(description):
            self.log.error(
                u'Parameter description is invalid. Value: %s.', description)
            raise InvalidValueError(None, 'description', description)

        # set variables
        self.finalidade_txt = finalidade_txt
        self.cliente_txt = cliente_txt
        self.ambiente_p44_txt = ambiente_p44_txt
        self.description = description
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:42,代码来源:models.py


示例8: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests Post to search cliente_txt of  Environment VIP by finalidade_txt

        URL: environmentvip/search/
        """

        try:

            self.log.info(
                'Search cliente_txt Environment VIP by finalidade_txt')

            # User permission
            if not has_perm(user, AdminPermission.ENVIRONMENT_VIP, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag of XML request.')

            environmentvip_map = networkapi_map.get('vip')
            if environmentvip_map is None:
                return self.response_error(3, u'There is no value to the vip tag of XML request.')

            # Get XML data
            finalidade = environmentvip_map.get('finalidade_txt')
            if not is_valid_string_maxsize(finalidade, 50) or not is_valid_string_minsize(finalidade, 3) or not is_valid_text(finalidade):
                self.log.error(
                    u'The finalidade_txt parameter is not a valid value: %s.', finalidade)
                raise InvalidValueError(None, 'finalidade_txt', finalidade)

            environmentVip = EnvironmentVip()

            evip_values = environmentVip.list_all_clientes_by_finalitys(
                finalidade)

            evips = dict()
            evips_list = []

            for evip in evip_values:
                evips['finalidade_txt'] = finalidade
                evips['cliente_txt'] = evip.get('cliente_txt')
                evips_list.append(evips)
                evips = dict()

            return self.response(dumps_networkapi({'cliente_txt': evips_list}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:54,代码来源:EnvironmentVipGetClienteTxtResource.py


示例9: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to insert a Equipment Type.

        URL: equipmenttype/
        """

        try:

            self.log.info("Add Equipment Script")

            # User permission
            if not has_perm(user, AdminPermission.EQUIPMENT_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            equipment_type_map = networkapi_map.get('equipment_type')
            if equipment_type_map is None:
                msg = u'There is no value to the equipment_type tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            name = equipment_type_map.get('name')

            # Valid Name
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100) or not is_valid_regex(name, "^[A-Za-z0-9 -]+$"):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            # Business Rules
            equipment_type = TipoEquipamento()

            # save Equipment Type
            equipment_type.insert_new(user, name)

            etype_dict = dict()
            etype_dict['id'] = equipment_type.id

            return self.response(dumps_networkapi({'equipment_type': etype_dict}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:53,代码来源:EquipmentTypeAddResource.py


示例10: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new network types.

        URL: /net_type/ 

        """

        try:
            # Check permission
            if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Get request XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # Get networkapi tag map
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no networkapi tag from request XML.')

            # Get net_type tag map
            net_type_map = networkapi_map.get('net_type')
            if net_type_map is None:
                return self.response_error(3, u'There is no tipo_rede tag from request XML.')

            # Valid name attribute
            name = net_type_map.get('name')
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 100):
                self.log.error(
                    u'Parameter %s is invalid. Value: %s.', 'name', name)
                raise InvalidValueError(None, 'name', name)

            net_type = TipoRede(tipo_rede=name)

            try:
                TipoRede.get_by_name(net_type.tipo_rede)
                raise NetworkTypeNameDuplicatedError(
                    None, u'Network type with name %s already exist' % net_type.tipo_rede)
            except NetworkTypeNotFoundError:
                pass

            try:
                net_type.save(user)
            except Exception, e:
                self.log.error(u'Failed to insert network type.')
                raise VlanError(e, u'Failed to insert network type.')

            net_type_map = dict()
            net_type_map['id'] = net_type.id

            return self.response(dumps_networkapi({'net_type': net_type_map}))
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:53,代码来源:NetworkTypeResource.py


示例11: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat POST requests to add new Access Type.

        URL: /tipoacesso/

        """

        try:
            if not has_perm(user, AdminPermission.ACCESS_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                self.log.error(u"User does not have permission to perform the operation.")
                raise UserNotAuthorizedError(None)

            xml_map, attrs_map = loads(request.raw_post_data)

            networkapi_map = xml_map.get("networkapi")
            if networkapi_map is None:
                return self.response_error(3, u"There is no networkapi tag in request XML.")

            tipo_acesso_map = networkapi_map.get("tipo_acesso")
            if tipo_acesso_map is None:
                return self.response_error(3, u"There is no tipo_acesso tag in request XML.")

            # Valid protocol
            protocol = tipo_acesso_map.get("protocolo")
            if (
                not is_valid_string_minsize(protocol, 3)
                or not is_valid_string_maxsize(protocol, 45)
                or not is_valid_regex(protocol, r"^[- a-zA-Z0-9]+$")
            ):
                self.log.error(u"Parameter protocol is invalid. Value: %s", protocol)
                raise InvalidValueError(None, "protocol", protocol)

            access_type = TipoAcesso()
            access_type.protocolo = protocol

            try:
                TipoAcesso.objects.get(protocolo__iexact=access_type.protocolo)
                raise DuplicateProtocolError(None, u"Access Type with protocol %s already exists" % protocol)
            except TipoAcesso.DoesNotExist:
                pass

            try:
                # save access type
                access_type.save(user)
            except Exception, e:
                self.log.error(u"Failed to save TipoAcesso.")
                raise TipoAcessoError(e, u"Failed to save TipoAcesso.")

            return self.response(dumps_networkapi({"tipo_acesso": {"id": access_type.id}}))
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:49,代码来源:TipoAcessoResource.py


示例12: handle_get

    def handle_get(self, request, user, *args, **kwargs):
        """Método responsável por tratar as requisições GET para consultar as interfaces.

        URL: /interface/<nome_interface>/equipamento/<id_equipamento>
        URL: /interface/equipamento/<id_equipamento>
        """

        # Get url parameters
        equipment_id = kwargs.get("id_equipamento")
        interface_name = kwargs.get("nome_interface")

        # Temporário, remover. Fazer de outra forma.
        if isinstance(interface_name, basestring):
            interface_name = interface_name.replace("s2it_replace", "/")

        is_new = kwargs.get("new")

        try:
            # Valid id_equipamento value
            if not is_valid_int_greater_zero_param(equipment_id):
                self.log.error(u"Parameter equipment_id is invalid. Value: %s", equipment_id)
                raise InvalidValueError(None, "equipment_id", equipment_id)

            # Valid interface_name value
            if not is_valid_string_minsize(interface_name, 1, required=False) or not is_valid_string_maxsize(
                interface_name, 20, required=False
            ):
                self.log.error(u"Parameter interface_name is invalid. Value: %s", interface_name)
                raise InvalidValueError(None, "interface_name", interface_name)

            # Check permission
            if not has_perm(
                user,
                AdminPermission.EQUIPMENT_MANAGEMENT,
                AdminPermission.READ_OPERATION,
                None,
                equipment_id,
                AdminPermission.EQUIP_READ_OPERATION,
            ):
                return self.not_authorized()

            # Check interface and call search method
            if interface_name is None:
                return self.search_interface_of_equipment(equipment_id, is_new)
            else:
                return self.search_interface_by_name_and_equipment(equipment_id, interface_name, is_new)

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:marcelometal,项目名称:GloboNetworkAPI,代码行数:49,代码来源:InterfaceResource.py


示例13: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add a HeltcheckExpect only expect_string field.

        URL: healthcheckexpect/add/expectstring/
        """

        try:
            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            healthcheck_map = networkapi_map.get('healthcheck')
            if healthcheck_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data

            expect_string = healthcheck_map.get('expect_string')
            if not is_valid_string_maxsize(expect_string, 50):
                self.log.error(
                    u'Parameter expect_string is invalid. Value: %s.', expect_string)
                raise InvalidValueError(None, 'expect_string', expect_string)

            # User permission
            if not has_perm(user,
                            AdminPermission.HEALTH_CHECK_EXPECT,
                            AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            healthcheck = HealthcheckExpect()

            healthcheck.insert_expect_string(user, expect_string)

            healtchcheck_dict = dict()
            healtchcheck_dict['id'] = healthcheck.id

            return self.response(dumps_networkapi({'healthcheck_expect': healtchcheck_dict}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:49,代码来源:HealthcheckAddExpectStringResource.py


示例14: handle_put

    def handle_put(self, request, user, *args, **kwargs):
        """Trata as requisições de PUT para alterar um grupo de equipamento.

        URL: egrupo/<id_grupo>/
        """
        try:
            egroup_id = kwargs.get('id_grupo')
            if not is_valid_int_greater_zero_param(egroup_id):
                self.log.error(
                    u'The egroup_id parameter is not a valid value: %s.', egroup_id)
                raise InvalidValueError(None, 'egroup_id', egroup_id)

            egrp = EGrupo.get_by_pk(egroup_id)

            if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.WRITE_OPERATION):
                return self.not_authorized()

            xml_map, attrs_map = loads(request.raw_post_data)
            self.log.debug('XML_MAP: %s', xml_map)

            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.')

            egroup_map = networkapi_map.get('grupo')
            if egroup_map is None:
                return self.response_error(3, u'Não existe valor para a tag grupo do XML de requisição.')

            name = egroup_map.get('nome')
            if not is_valid_string_maxsize(name, 100):
                self.log.error(u'Parameter name is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name', name)

            with distributedlock(LOCK_GROUP_EQUIPMENT % egroup_id):

                # Destroy equipment's cache
                equip_id_list = []
                for equipament in egrp.equipamento_set.all():
                    equip_id_list.append(equipament.id)
                destroy_cache_function(equip_id_list, True)

                EGrupo.update(user, egroup_id, nome=name)

                return self.response(dumps_networkapi({}))

        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:47,代码来源:GrupoResource.py


示例15: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to authenticate to user.

        URL: authenticate/
        """

        try:

            self.log.info("Authenticate user")

            # User permission
            if not has_perm(user, AdminPermission.AUTHENTICATE, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            user_map = networkapi_map.get('user')
            if user_map is None:
                return self.response_error(3, u'There is no value to the user tag  of XML request.')

            # Get XML data
            username = user_map.get('username')
            password = user_map.get('password')
            is_ldap_user = user_map.get('is_ldap_user')

            # Username can NOT be less 3 and greater than 45
            if not is_valid_string_minsize(username, 3) or not is_valid_string_maxsize(username, 45):
                self.log.error(
                    u'Parameter username is invalid. Value: %s.', username)
                raise InvalidValueError(None, 'username', username)

            if not is_valid_boolean_param(is_ldap_user):
                self.log.error(
                    u'Parameter is_ldap_user is invalid. Value: %s.', is_ldap_user)
                raise InvalidValueError(None, 'is_ldap_user', is_ldap_user)
            else:
                is_ldap_user = convert_string_or_int_to_boolean(is_ldap_user)

            if is_ldap_user:
                user = Usuario().get_by_ldap_user(username, True)
                password = user.pwd
            else:
                # Password can NOT be less 3 and greater than 45
                if not is_valid_string_minsize(password, 3) or not is_valid_string_maxsize(password, 45):
                    self.log.error(
                        u'Parameter password is invalid. Value: %s.', '****')
                    raise InvalidValueError(None, 'password', '****')

                # Find user by username, password to check if it exist
                user = Usuario().get_enabled_user(username.upper(), password)

            # Valid user
            if user is None:
                return self.response(dumps_networkapi({}))

            perms = {}
            for ugroup in user.grupos.all():

                for perm in ugroup.permissaoadministrativa_set.all():

                    function = perm.permission.function

                    if perms.has_key(function):

                        write = False
                        read = False

                        if perms.get(function).get('write') == True or perm.escrita == True:
                            write = True

                        if perms.get(function).get('read') == True or perm.leitura == True:
                            read = True

                        perms[function] = {'write': write, 'read': read}

                    else:
                        perms[function] = {
                            'write': perm.escrita, 'read': perm.leitura}

            user_map = {}
            user_dict = model_to_dict(
                user, fields=['id', 'user', 'nome', 'email', 'ativo', 'user_ldap'])
            user_dict['pwd'] = password
            user_dict['permission'] = perms
            user_map['user'] = user_dict

            return self.response(dumps_networkapi(user_map))

        except UsuarioNotFoundError:
            return self.response(dumps_networkapi({}))
        except InvalidValueError, e:
            return self.response_error(269, e.param, e.value)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:100,代码来源:AuthenticateResource.py


示例16: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to valid Real server.

        URL: vip/real/valid/
        """
        self.log.info('Valid Real Server')

        try:

            # Business Validations

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                return self.response_error(3, u'There is no value to the networkapi tag  of XML request.')

            real_map = networkapi_map.get('real')
            if real_map is None:
                return self.response_error(3, u'There is no value to the vip tag  of XML request.')

            # Get XML data
            ip = real_map.get('ip')
            name = real_map.get('name_equipment')
            id_evip = real_map.get('id_environment_vip')
            valid = real_map.get('valid')

            # User permission
            if not has_perm(user, AdminPermission.VIPS_REQUEST, AdminPermission.READ_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                return self.not_authorized()

            # Valid IP
            if not is_valid_ip_ipaddr(ip):
                self.log.error(u'Parameter ip is invalid. Value: %s.', ip)
                raise InvalidValueError(None, 'ip', ip)

            # Valid Name Equipment
            if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 80) or not is_valid_regex(name, '^[A-Z0-9-_]+$'):
                self.log.error(
                    u'Parameter name_equipment is invalid. Value: %s', name)
                raise InvalidValueError(None, 'name_equipment', name)

            # Valid Environment Vip
            if not is_valid_int_greater_zero_param(id_evip):
                self.log.error(
                    u'Parameter id_environment_vip is invalid. Value: %s.', id_evip)
                raise InvalidValueError(None, 'id_environment_vip', id_evip)

            # Valid Equipment
            equip = Equipamento.get_by_name(name)

            # Valid EnvironmentVip
            evip = EnvironmentVip.get_by_pk(id_evip)

            version = ''
            if is_valid_ipv4(ip):
                version = IP_VERSION.IPv4[1]

            elif is_valid_ipv6(ip):
                version = IP_VERSION.IPv6[1]

            ip, equip, evip = RequisicaoVips.valid_real_server(
                ip, equip, evip, valid)

            real_dict = {}
            ip_dict = model_to_dict(ip)
            ip_dict['version'] = version

            real_dict['ip'] = ip_dict
            real_dict['equipment'] = model_to_dict(equip)
            real_dict['environmentvip'] = model_to_dict(evip)

            return self.response(dumps_networkapi({'real': real_dict}))

        except XMLError, x:
            self.log.error(u'Error reading the XML request.')
            return self.response_error(3, x)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:81,代码来源:RequestVipRealValidResource.py


示例17: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Handles POST requests to edit an IP.

        URL: ipv4/edit/
        """

        self.log.info('Edit an IP')

        try:
            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is None:
                msg = u'There is no value to the networkapi tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)
            ip_map = networkapi_map.get('ip_map')
            if ip_map is None:
                msg = u'There is no value to the ip tag of XML request.'
                self.log.error(msg)
                return self.response_error(3, msg)

            # Get XML data
            id_ip = ip_map.get('id_ip')
            description = ip_map.get('descricao')
            ip4 = ip_map.get('ip4')

            # Valid id_ip
            if not is_valid_int_greater_zero_param(id_ip):
                self.log.error(
                    u'Parameter id_ip is invalid. Value: %s.', id_ip)
                raise InvalidValueError(None, 'id_ip', id_ip)

            if not is_valid_string_maxsize(ip4, 15):
                self.log.error(u'Parameter ip4 is invalid. Value: %s.', ip4)
                raise InvalidValueError(None, 'ip4', description)

            # Valid description
            if description is not None:
                if not is_valid_string_maxsize(description, 100) or not is_valid_string_minsize(description, 3):
                    self.log.error(
                        u'Parameter description is invalid. Value: %s.', description)
                    raise InvalidValueError(None, 'description', description)

            # User permission
            if not has_perm(user, AdminPermission.IPS, AdminPermission.WRITE_OPERATION):
                raise UserNotAuthorizedError(
                    None, u'User does not have permission to perform the operation.')

            # Business Rules

            # New IP

            ip = Ip()

            ip = ip.get_by_pk(id_ip)

            with distributedlock(LOCK_IPV4 % id_ip):

                # se Houver erro no ip informado para retorna-lo na mensagem
                ip_error = ip4

                # verificação se foi passado algo errado no ip
                ip4 = ip4.split('.')
                for oct in ip4:
                    if not is_valid_int_param(oct):
                        raise InvalidValueError(None, 'ip4', ip_error)

                # Ip passado de forma invalida
                if len(ip4) is not 4:
                    raise IndexError

                ip.descricao = description
                ip.oct1 = ip4[0]
                ip.oct2 = ip4[1]
                ip.oct3 = ip4[2]
                ip.oct4 = ip4[3]

                # Persist
                ip.edit_ipv4(user)

                return self.response(dumps_networkapi({}))

        except UserNotAuthorizedError:
            return self.not_authorized()
        except IndexError:
            msg = 'Invalid IP %s' % ip_error
            return self.response_error(150, msg)
        except IpNotFoundError, e:
            return self.response_error(150, e.message)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:92,代码来源:IPv4EditResource.py


示例18: handle_post

    def handle_post(self, request, user, *args, **kwargs):
        """Treat requests POST to add user.

        URL: user/
        """

        try:

            self.log.info('Add User')

            # User permission
            if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION):
                self.log.error(
                    u'User does not have permission to perform the operation.')
                raise UserNotAuthorizedError(None)

            # Load XML data
            xml_map, attrs_map = loads(request.raw_post_data)

            # XML data format
            networkapi_map = xml_map.get('networkapi')
            if networkapi_map is 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.is_valid_string_minsize函数代码示例发布时间:2022-05-27
下一篇:
Python util.is_valid_int_greater_zero_param函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap