本文整理汇总了Python中networkapi.util.is_valid_string_minsize函数的典型用法代码示例。如果您正苦于以下问题:Python is_valid_string_minsize函数的具体用法?Python is_valid_string_minsize怎么用?Python is_valid_string_minsize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_valid_string_minsize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例2: 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({}))
示例3: 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))
示例4: 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)
示例5: 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
示例6: 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)
示例7: 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}))
示例8: 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)
示例9: 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}}))
示例10: 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)
示例11: handle_put
def handle_put(self, request, user, *args, **kwargs):
"""Trata uma requisição PUT para alterar informações de uma interface.
URL: /interface/<id_interface>/
"""
# Get request data and check permission
try:
# Valid Interface ID
id_interface = kwargs.get('id_interface')
if not is_valid_int_greater_zero_param(id_interface):
self.log.error(
u'The id_interface parameter is not a valid value: %s.', id_interface)
raise InvalidValueError(None, 'id_interface', id_interface)
# Get interface and equipment to check permission
interface = Interface.get_by_pk(id_interface)
id_equipamento = interface.equipamento_id
# Check permission
if not has_perm(user,
AdminPermission.EQUIPMENT_MANAGEMENT,
AdminPermission.WRITE_OPERATION,
None,
id_equipamento,
AdminPermission.EQUIP_WRITE_OPERATION):
return self.not_authorized()
# Get XML data
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 XML request.')
interface_map = networkapi_map.get('interface')
if interface_map is None:
return self.response_error(3, u'There is no interface tag in XML request.')
# Valid name value
nome = interface_map.get('nome')
if not is_valid_string_minsize(nome, 1) or not is_valid_string_maxsize(nome, 20):
self.log.error(u'Parameter nome is invalid. Value: %s', nome)
raise InvalidValueError(None, 'nome', nome)
# Valid protegida value
protegida = interface_map.get('protegida')
if not is_valid_boolean_param(protegida):
self.log.error(
u'Parameter protegida is invalid. Value: %s', protegida)
raise InvalidValueError(None, 'protegida', protegida)
else:
protegida = convert_string_or_int_to_boolean(protegida)
# Valid descricao value
descricao = interface_map.get('descricao')
if descricao is not None:
if not is_valid_string_minsize(descricao, 3) or not is_valid_string_maxsize(descricao, 200):
self.log.error(
u'Parameter descricao is invalid. Value: %s', descricao)
raise InvalidValueError(None, 'descricao', descricao)
# Valid "id_ligacao_front" value
id_ligacao_front = interface_map.get('id_ligacao_front')
if id_ligacao_front is not None:
if not is_valid_int_greater_zero_param(id_ligacao_front):
self.log.error(
u'The id_ligacao_front parameter is not a valid value: %s.', id_ligacao_front)
raise InvalidValueError(
None, 'id_ligacao_front', id_ligacao_front)
else:
id_ligacao_front = int(id_ligacao_front)
# Valid "id_ligacao_back" value
id_ligacao_back = interface_map.get('id_ligacao_back')
if id_ligacao_back is not None:
if not is_valid_int_greater_zero_param(id_ligacao_back):
self.log.error(
u'The id_ligacao_back parameter is not a valid value: %s.', id_ligacao_back)
raise InvalidValueError(
None, 'id_ligacao_back', id_ligacao_back)
else:
id_ligacao_back = int(id_ligacao_back)
tipo = interface_map.get('tipo')
tipo = TipoInterface.get_by_name(tipo)
vlan = interface_map.get('vlan')
with distributedlock(LOCK_INTERFACE % id_interface):
# Update interface
Interface.update(user,
id_interface,
interface=nome,
protegida=protegida,
descricao=descricao,
ligacao_front_id=id_ligacao_front,
ligacao_back_id=id_ligacao_back,
tipo=tipo,
#.........这里部分代码省略.........
示例12: handle_post
def handle_post(self, request, user, *args, **kwargs):
"""Treat requests POST to add Model.
URL: model/
"""
try:
self.log.info("Add Model")
# 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.')
model_map = networkapi_map.get('model')
if model_map is None:
return self.response_error(3, u'There is no value to the model tag of XML request.')
# Get XML data
name = model_map.get('name')
id_brand = model_map.get('id_brand')
# 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)
# Valid ID Brand
if not is_valid_int_greater_zero_param(id_brand):
self.log.error(
u'The id_brand parameter is not a valid value: %s.', id_brand)
raise InvalidValueError(None, 'id_brand', id_brand)
# Find Brand by ID to check if it exist
brand = Marca.get_by_pk(id_brand)
try:
Modelo.get_by_name_brand(name, id_brand)
raise MarcaModeloNameDuplicatedError(
None, u'Já existe um modelo com o nome %s com marca %s.' % (name, brand.nome))
except ModeloNotFoundError:
pass
model = Modelo()
# set variables
model.nome = name
model.marca = brand
try:
# save Model
model.save()
except Exception, e:
self.log.error(u'Failed to save the Model.')
raise EquipamentoError(e, u'Failed to save the Model.')
model_map = dict()
model_map['model'] = model_to_dict(
model, exclude=["nome", "marca"])
return self.response(dumps_networkapi(model_map))
示例13: handle_post
def handle_post(self, request, user, *args, **kwargs):
"""
Handles POST requests to allocate a new VLAN.
URL: vlan/
"""
self.log.info('Allocate new VLAN')
try:
# Commons Validations
# User permission
if not has_perm(user, AdminPermission.VLAN_MANAGEMENT, AdminPermission.WRITE_OPERATION):
self.log.error(
u'User does not have permission to perform the 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)
vlan_map = networkapi_map.get('vlan')
if vlan_map is None:
msg = u'There is no value to the vlan tag of XML request.'
self.log.error(msg)
return self.response_error(3, msg)
# Get XML data
environment = vlan_map.get('id_ambiente')
network_type = vlan_map.get('id_tipo_rede')
name = vlan_map.get('nome')
description = vlan_map.get('descricao')
environment_vip = vlan_map.get('id_ambiente_vip')
vrf = vlan_map.get('vrf')
# Name must NOT be none and 50 is the maxsize
if not is_valid_string_minsize(name, 3) or not is_valid_string_maxsize(name, 50):
self.log.error(u'Parameter nome is invalid. Value: %s.', name)
raise InvalidValueError(None, 'nome', 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):
self.log.error(
u'Parameter descricao is invalid. Value: %s.', description)
raise InvalidValueError(None, 'descricao', description)
# vrf can NOT be greater than 100
if not is_valid_string_maxsize(vrf, 100, False):
self.log.error(
u'Parameter vrf is invalid. Value: %s.', vrf)
raise InvalidValueError(None, 'vrf', vrf)
# Environment
# Valid environment ID
if not is_valid_int_greater_zero_param(environment):
self.log.error(
u'Parameter id_ambiente is invalid. Value: %s.', environment)
raise InvalidValueError(None, 'id_ambiente', environment)
# Find environment by ID to check if it exist
env = Ambiente.get_by_pk(environment)
# Environment Vip
if environment_vip is not None:
# Valid environment_vip ID
if not is_valid_int_greater_zero_param(environment_vip):
self.log.error(
u'Parameter id_ambiente_vip is invalid. Value: %s.', environment_vip)
raise InvalidValueError(
None, 'id_ambiente_vip', environment_vip)
# Find Environment VIP by ID to check if it exist
evip = EnvironmentVip.get_by_pk(environment_vip)
else:
evip = None
# Network Type
# Valid network_type ID
if not is_valid_int_greater_zero_param(network_type):
self.log.error(
u'Parameter id_tipo_rede is invalid. Value: %s.', network_type)
raise InvalidValueError(None, 'id_tipo_rede', network_type)
# Find network_type by ID to check if it exist
net = TipoRede.get_by_pk(network_type)
# Business Rules
# New Vlan
#.........这里部分代码省略.........
示例14: 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)
示例15: 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)