本文整理汇总了Python中networkapi.vlan.models.TipoRede类的典型用法代码示例。如果您正苦于以下问题:Python TipoRede类的具体用法?Python TipoRede怎么用?Python TipoRede使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TipoRede类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_delete
def handle_delete(self, request, user, *args, **kwargs):
"""Trata uma requisição DELETE para excluir um tipo de rede
URL: /tiporede/<id_tipo_rede>/
"""
# Verifica acesso e obtém dados do request
try:
# Verificar a permissão
if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
return self.not_authorized()
# Obtém argumentos passados na URL
id_tipo_rede = kwargs.get('id_tipo_rede')
if id_tipo_rede is None:
return self.response_error(256)
# Remove a informação de acesso a equipamento
TipoRede.remove(user, id_tipo_rede)
# Retorna response vazio em caso de sucesso
return self.response(dumps_networkapi({}))
except TipoRedeNotFoundError:
return self.response_error(111)
except TipoRedeUsedByVlanError:
return self.response_error(215, id_tipo_rede)
except (GrupoError, VlanError):
return self.response_error(1)
示例2: config_ambiente
def config_ambiente(user, hosts, ambientes):
#ip_config
ip_config = IPConfig()
ip_config.subnet = hosts.get("REDE")
ip_config.new_prefix = hosts.get("PREFIX")
if hosts.get("VERSION")=="ipv4":
ip_config.type = IP_VERSION.IPv4[0]
elif hosts.get("VERSION")=="ipv6":
ip_config.type = IP_VERSION.IPv6[0]
tiporede = TipoRede()
tipo = tiporede.get_by_name(hosts.get("TIPO"))
ip_config.network_type = tipo
ip_config.save()
#ambiente
config_environment = ConfigEnvironment()
amb_log = AmbienteLogico()
div = DivisaoDc()
amb_log = amb_log.get_by_name(ambientes.get("LOG"))
div = div.get_by_name(ambientes.get("DC"))
for j in Ambiente().search(div.id, amb_log.id):
if j.grupo_l3.nome==ambientes.get("L3"):
config_environment.environment = j
config_environment.ip_config = ip_config
config_environment.save()
示例3: 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}))
示例4: handle_post
def handle_post(self, request, user, *args, **kwargs):
"""Trata as requisições de POST para criar tipos de rede.
URL: /tiporede/
"""
# Obtém dados do request e verifica acesso
try:
# Verificar a permissão
if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
return self.not_authorized()
# Obtém os dados do xml do request
xml_map, attrs_map = loads(request.raw_post_data)
# Obtém o mapa correspondente ao root node do mapa do XML
# (networkapi)
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.')
# Verifica a existência do node "tipo_rede"
tipo_rede_map = networkapi_map.get('tipo_rede')
if tipo_rede_map is None:
return self.response_error(3, u'Não existe valor para a tag tipo_rede do XML de requisição.')
# Verifica a existência do valor "fqdn"
nome = tipo_rede_map.get('nome')
if nome is None:
return self.response_error(176)
# Cria acesso ao equipamento conforme dados recebidos no XML
tipo_rede = TipoRede(tipo_rede=nome)
tipo_rede.create(user)
# Monta dict para response
networkapi_map = dict()
tipo_rede_map = dict()
tipo_rede_map['id'] = tipo_rede.id
networkapi_map['tipo_rede'] = tipo_rede_map
return self.response(dumps_networkapi(networkapi_map))
except TipoRedeNameDuplicatedError:
return self.response_error(253, nome)
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, x)
示例5: handle_put
def handle_put(self, request, user, *args, **kwargs):
"""Trata uma requisição PUT para alterar tipos de rede.
URL: /tiporede/<id_tipo_rede>/
"""
# Obtém dados do request e verifica acesso
try:
# Verificar a permissão
if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.WRITE_OPERATION):
return self.not_authorized()
# Obtém argumentos passados na URL
id_tipo_rede = kwargs.get('id_tipo_rede')
if id_tipo_rede is None:
return self.response_error(256)
# Obtém dados do XML
xml_map, attrs_map = loads(request.raw_post_data)
# Obtém o mapa correspondente ao root node do mapa do XML
# (networkapi)
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.')
# Verifica a existência do node "tipo_rede"
tipo_rede_map = networkapi_map.get('tipo_rede')
if tipo_rede_map is None:
return self.response_error(3, u'Não existe valor para a tag tipo_rede do XML de requisição.')
# Verifica a existência do valor "fqdn"
nome = tipo_rede_map.get('nome')
if nome is None:
return self.response_error(176)
# Altera o tipo de redeconforme dados recebidos no XML
TipoRede.update(user,
id_tipo_rede,
tipo_rede=nome
)
# Retorna response vazio em caso de sucesso
return self.response(dumps_networkapi({}))
except XMLError, x:
self.log.error(u'Erro ao ler o XML da requisição.')
return self.response_error(3, x)
示例6: test_alter_valid
def test_alter_valid(self):
mock = self.mock_valid_alter()
response = self.alter(self.ID_ALTER_VALID, {self.XML_KEY: mock})
valid_response(response)
nt = TipoRede.get_by_pk(self.ID_ALTER_VALID)
self.valid_attr(mock, model_to_dict(nt))
示例7: handle_get
def handle_get(self, request, user, *args, **kwargs):
"""Trata as requisições GET para consulta de tipos de rede.
Permite a consulta de tipos de rede existentes.
URL: /tiporede/
"""
try:
if not has_perm(user, AdminPermission.NETWORK_TYPE_MANAGEMENT, AdminPermission.READ_OPERATION):
return self.not_authorized()
# Efetua a consulta de todos os tipos de rede
results = TipoRede.search()
if results.count() > 0:
# Monta lista com dados retornados
map_list = []
for item in results:
item_map = self.get_tipo_rede_map(item)
map_list.append(item_map)
# Gera response (XML) com resultados
return self.response(dumps_networkapi({'tipo_rede': map_list}))
else:
# Gera response (XML) para resultado vazio
return self.response(dumps_networkapi({}))
except (VlanError, GrupoError):
return self.response_error(1)
示例8: test_save_valid
def test_save_valid(self):
mock = self.mock_valid()
response = self.save({self.XML_KEY: mock})
valid_response(response)
content = valid_content(response, self.XML_KEY)
nt = TipoRede.get_by_pk(content["id"])
self.valid_attr(mock, model_to_dict(nt))
示例9: criar_rede
def criar_rede(user, tipo_rede, variablestochangecore1, vlan, active=1):
tiporede = TipoRede()
net_id = tiporede.get_by_name(tipo_rede)
network_type = tiporede.get_by_pk(net_id.id)
network_ip = NetworkIPv4()
network_ip.oct1, network_ip.oct2, network_ip.oct3, network_ip.oct4 = str(variablestochangecore1.get("REDE_IP")).split('.')
network_ip.block = variablestochangecore1.get("REDE_MASK")
network_ip.mask_oct1, network_ip.mask_oct2, network_ip.mask_oct3, network_ip.mask_oct4 = str(variablestochangecore1.get("NETMASK")).split('.')
network_ip.broadcast = variablestochangecore1.get("BROADCAST")
network_ip.vlan = vlan
network_ip.network_type = network_type
network_ip.ambient_vip = None
network_ip.active = active
destroy_cache_function([vlan.id])
network_ip.save()
return network_ip
示例10: criar_rede_ipv6
def criar_rede_ipv6(user, tipo_rede, variablestochangecore1, vlan, active=1):
tiporede = TipoRede()
net_id = tiporede.get_by_name(tipo_rede)
network_type = tiporede.get_by_pk(net_id.id)
network_ip = NetworkIPv6()
network_ip.vlan = vlan
network_ip.network_type = network_type
network_ip.ambient_vip = None
network_ip.active = active
network_ip.block = variablestochangecore1.get("REDE_MASK")
while str(variablestochangecore1.get("REDE_IP")).endswith(":"):
variablestochangecore1['REDE_IP'] = variablestochangecore1['REDE_IP'][:-1]
while str(variablestochangecore1.get("NETMASK")).endswith(":"):
variablestochangecore1['NETMASK'] = variablestochangecore1['NETMASK'][:-1]
len_ip_ipv6 = len(str(variablestochangecore1.get("REDE_IP")).split(':'))
len_mask = len(str(variablestochangecore1.get("NETMASK")).split(':'))
while(8-len_ip_ipv6>0):#8-6=2--8-7=1--8-8=0
len_ip_ipv6 = len_ip_ipv6 + 1
variablestochangecore1['REDE_IP'] = variablestochangecore1.get("REDE_IP")+":0"
while(8-len_mask>0):
len_mask = len_mask + 1
variablestochangecore1['NETMASK'] = variablestochangecore1.get("NETMASK")+":0"
network_ip.block1, network_ip.block2, network_ip.block3, network_ip.block4, network_ip.block5, network_ip.block6, network_ip.block7, network_ip.block8 = str(variablestochangecore1.get("REDE_IP")).split(':')
network_ip.mask1, network_ip.mask2, network_ip.mask3, network_ip.mask4, network_ip.mask5, network_ip.mask6, network_ip.mask7, network_ip.mask8 = str(variablestochangecore1.get("NETMASK")).split(':')
destroy_cache_function([vlan.id])
network_ip.save()
return network_ip
示例11: handle_delete
def handle_delete(self, request, user, *args, **kwargs):
"""Treat DELETE request to remove network type
URL: /net_type/<id_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 URL args
id_net_type = kwargs.get('id_net_type')
if not is_valid_int_greater_zero_param(id_net_type):
self.log.error(
u'Parameter %s is invalid. Value: %s.', 'id_net_type', id_net_type)
raise InvalidValueError(None, 'id_net_type', id_net_type)
net_type = TipoRede.get_by_pk(id_net_type)
with distributedlock(LOCK_TYPE_NETWORK % id_net_type):
# Check if network type is used by vlan
if net_type.networkipv4_set.count() > 0 or net_type.networkipv6_set.count() > 0:
self.log.error(u'Network type used by network.')
raise NetTypeUsedByNetworkError(
None, u'Network type used by network.')
try:
net_type.delete(user)
except Exception, e:
self.log.error(u'Failed to remove network type.')
raise VlanError(e, u'Failed to remove network type.')
# Return empty response
return self.response(dumps_networkapi({}))
示例12: handle_post
def handle_post(self, request, user, *args, **kwargs):
"""Treat POST requests to add new Environment Configuration Prefix
URL: environment/configuration/add
"""
try:
self._validate_permission(user)
xml_map, _ = loads(request.raw_post_data)
networkapi_map = xml_map.get('networkapi')
self._validate_xml_networkapi(networkapi_map)
network_map = networkapi_map.get('ambiente')
self._validate_xml_network(network_map)
# Get XML data
network = network_map.get('network')
id_environment = network_map.get('id_environment')
ip_version = network_map.get('ip_version')
network_type = network_map.get('network_type')
prefix = network_map.get('prefix')
self._validate_network(network, prefix)
self._validate_environment_id(id_environment)
self._validate_ip_version(ip_version)
self._validate_network_type(network_type)
self._validate_prefix_by_net_type(prefix, ip_version)
environment = Ambiente().get_by_pk(id_environment)
network_type = TipoRede.get_by_pk(network_type)
ip_config = IPConfig()
ip_config.subnet = network
ip_config.new_prefix = prefix
ip_config.type = ip_version
ip_config.network_type = network_type
ip_config.save()
config_environment = ConfigEnvironment()
config_environment.environment = environment
config_environment.ip_config = ip_config
config_environment.save()
return self.response(dumps_networkapi({'network': network_map}))
except PermissionError:
return self.not_authorized()
except AmbienteNotFoundError, e:
return self.response_error(112)
示例13: handle_post
def handle_post(self, request, user, *args, **kwargs):
"""Treat POST requests to add new Network
URL: network/add/
"""
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)
network_map = networkapi_map.get('network')
if network_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
network = network_map.get('network')
id_vlan = network_map.get('id_vlan')
network_type = network_map.get('id_network_type')
environment_vip = network_map.get('id_environment_vip')
# Valid Network
try:
net = IPNetwork(network)
except ValueError, e:
raise InvalidValueError(None, 'network', network)
# VLAN
# Valid vlan ID
if not is_valid_int_greater_zero_param(id_vlan):
raise InvalidValueError(None, 'id_vlan', id_vlan)
# Find vlan by ID to check if it exist
vlan = Vlan().get_by_pk(id_vlan)
# Network Type
# Valid network_type ID
if not is_valid_int_greater_zero_param(network_type):
raise InvalidValueError(None, 'id_network_type', network_type)
# Find network_type by ID to check if it exist
net_type = TipoRede.get_by_pk(network_type)
# Environment Vip
if environment_vip is not None:
# Valid environment_vip ID
if not is_valid_int_greater_zero_param(environment_vip):
raise InvalidValueError(
None, 'id_environment_vip', environment_vip)
evips = EnvironmentVip.objects.all()
evip_list = EnvironmentVip.available_evips(
EnvironmentVip(), evips, int(id_vlan))
# Check if the chose environment is in the same environment
if any(int(environment_vip) == item['id'] for item in evip_list):
# Find Environment VIP by ID to check if it exist
env_vip = EnvironmentVip.get_by_pk(environment_vip)
else:
raise InvalidValueError(
None, 'id_environment_vip', environment_vip)
else:
env_vip = None
# Check unchecked exception
blocks, network, version = break_network(network)
expl = split(
net.network.exploded, "." if version == IP_VERSION.IPv4[0] else ":")
expl.append(str(net.prefixlen))
if blocks != expl:
raise InvalidValueError(None, 'rede', network)
# Business Rules
#.........这里部分代码省略.........
示例14: handle_put
def handle_put(self, request, user, *args, **kwargs):
"""Treat PUT requests to edit network types.
URL: /net_type/<id_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 URL args
id_net_type = kwargs.get('id_net_type')
if not is_valid_int_greater_zero_param(id_net_type):
self.log.error(
u'Parameter %s is invalid. Value: %s.', 'id_net_type', id_net_type)
raise InvalidValueError(None, 'id_net_type', id_net_type)
# Get 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 net_type 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.get_by_pk(id_net_type)
with distributedlock(LOCK_TYPE_NETWORK % id_net_type):
try:
if name.lower() != net_type.tipo_rede.lower():
TipoRede.get_by_name(name)
raise NetworkTypeNameDuplicatedError(
None, u'Network type with name %s already exists' % name)
except NetworkTypeNotFoundError:
pass
net_type.tipo_rede = name
try:
net_type.save(user)
except Exception, e:
self.log.error(u'Failed to edit network type.')
raise VlanError(e, u'Failed to edit network type.')
# Return empty response
return self.response(dumps_networkapi({}))
示例15: 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
#.........这里部分代码省略.........