text
stringlengths
81
112k
Remove newlines, tabs and multiple spaces with single spaces. def collapse_spaces(text): """Remove newlines, tabs and multiple spaces with single spaces.""" if not isinstance(text, six.string_types): return text return COLLAPSE_RE.sub(WS, text).strip(WS)
The main normalization function for text. This will take a string and apply a set of transformations to it so that it can be processed more easily afterwards. Arguments: * ``lowercase``: not very mysterious. * ``collapse``: replace multiple whitespace-like characters with a single whitespace. Th...
A simple slug generator. def slugify(text, sep='-'): """A simple slug generator.""" text = stringify(text) if text is None: return None text = text.replace(sep, WS) text = normalize(text, ascii=True) if text is None: return None return text.replace(WS, sep)
Transliterate the given text to the latin script. This attempts to convert a given text to latin script using the closest match of characters vis a vis the original script. def latinize_text(text, ascii=False): """Transliterate the given text to the latin script. This attempts to convert a given text...
Transliterate the given text and make sure it ends up as ASCII. def ascii_text(text): """Transliterate the given text and make sure it ends up as ASCII.""" text = latinize_text(text, ascii=True) if isinstance(text, six.text_type): text = text.encode('ascii', 'ignore').decode('ascii') return tex...
Return default message for this element def message(self): """Return default message for this element """ if self.code != 200: for code in self.response_codes: if code.code == self.code: return code.message raise ValueError("Unknown r...
Return default value for the element def get_default_sample(self): """Return default value for the element """ if self.type not in Object.Types or self.type is Object.Types.type: return self.type_object.get_sample() else: return self.get_object().get_sample()
Return a proper object def factory(cls, str_type, version): """Return a proper object """ type = Object.Types(str_type) if type is Object.Types.object: object = ObjectObject() elif type is Object.Types.array: object = ObjectArray() elif type is O...
Main function to run command def main(): """Main function to run command """ configParser = FileParser() logging.config.dictConfig( configParser.load_from_file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings', 'logging.yml')) ) ApiDoc().main()
return command's configuration from call's arguments def _init_config(self): """return command's configuration from call's arguments """ options = self.parser.parse_args() if options.config is None and options.input is None: self.parser.print_help() sys.exit(2) ...
Run the command def main(self): """Run the command """ self._init_config() if self.dry_run: return self.run_dry_run() elif self.watch: return self.run_watch() else: return self.run_render()
Refresh sources then templates def _watch_refresh_source(self, event): """Refresh sources then templates """ self.logger.info("Sources changed...") try: self.sources = self._get_sources() self._render_template(self.sources) except: pass
Refresh template's contents def _watch_refresh_template(self, event): """Refresh template's contents """ self.logger.info("Template changed...") try: self._render_template(self.sources) except: pass
Add a property to a class def add_property(attribute, type): """Add a property to a class """ def decorator(cls): """Decorator """ private = "_" + attribute def getAttr(self): """Property getter """ if getattr(self, private) is None: ...
Combine the input files to a big output file def _merge_files(self, input_files, output_file): """Combine the input files to a big output file""" # we assume that all the input files have the same charset with open(output_file, mode='wb') as out: for input_file in input_files: ...
Return a populated object Object from dictionary datas def create_from_name_and_dictionary(self, name, datas): """Return a populated object Object from dictionary datas """ if "type" not in datas: str_type = "any" else: str_type = str(datas["type"]).lower() ...
Merge extended dicts def merge_extends(self, target, extends, inherit_key="inherit", inherit=False): """Merge extended dicts """ if isinstance(target, dict): if inherit and inherit_key in target and not to_boolean(target[inherit_key]): return if not isins...
Merge sources files def merge_sources(self, datas): """Merge sources files """ datas = [data for data in datas if data is not None] if len(datas) == 0: raise ValueError("Data missing") if len(datas) == 1: return datas[0] if isinstance(datas[0],...
Merge configs files def merge_configs(self, config, datas): """Merge configs files """ if not isinstance(config, dict) or len([x for x in datas if not isinstance(x, dict)]) > 0: raise TypeError("Unable to merge: Dictionnary expected") for key, value in config.items(): ...
Return a proper object def factory(cls, object_raw): """Return a proper object """ if object_raw is None: return None if object_raw.type is ObjectRaw.Types.object: return ObjectObject(object_raw) elif object_raw.type is ObjectRaw.Types.type: r...
Render the documentation as defined in config Object def render(self, sources, config, out=sys.stdout): """Render the documentation as defined in config Object """ logger = logging.getLogger() template = self.env.get_template(self.input) output = template.render(sources=sources,...
Return a populated object Configuration from dictionnary datas def create_from_dictionary(self, datas): """Return a populated object Configuration from dictionnary datas """ configuration = ObjectConfiguration() if "uri" in datas: configuration.uri = str(datas["uri"]) ...
Return a populated object Parameter from dictionary datas def create_from_name_and_dictionary(self, name, datas): """Return a populated object Parameter from dictionary datas """ parameter = ObjectParameter() self.set_common_datas(parameter, name, datas) if "optional" in datas:...
Validate the format of sources def validate(self, sources): """Validate the format of sources """ if not isinstance(sources, Root): raise Exception("Source object expected") parameters = self.get_uri_with_missing_parameters(sources) for parameter in parameters: ...
Validate that the source file is ok def validate(self, config): """Validate that the source file is ok """ if not isinstance(config, ConfigObject): raise Exception("Config object expected") if config["output"]["componants"] not in ("local", "remote", "embedded", "without"):...
Retrieve a template path from the config object def get_template_from_config(self, config): """Retrieve a template path from the config object """ if config["output"]["template"] == "default": return os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__fil...
Return a populated object ResponseCode from dictionary datas def create_from_dictionary(self, datas): """Return a populated object ResponseCode from dictionary datas """ if "code" not in datas: raise ValueError("A response code must contain a code in \"%s\"." % repr(datas)) ...
Add a path in watch queue def add_handler(self, path, handler): """Add a path in watch queue """ self.signatures[path] = self.get_path_signature(path) self.handlers[path] = handler
generate a unique signature for file contained in path def get_path_signature(self, path): """generate a unique signature for file contained in path """ if not os.path.exists(path): return None if os.path.isdir(path): merge = {} for root, dirs, files ...
Check if a file is changed def check(self): """Check if a file is changed """ for (path, handler) in self.handlers.items(): current_signature = self.signatures[path] new_signature = self.get_path_signature(path) if new_signature != current_signature: ...
Return a tupple of values representing the unicity of the object def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (int(self.major), int(self.minor), str(self.label), str(self.name))
Return a tupple of values representing the unicity of the object def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (int(self.order), str(self.label), str(self.name))
Return a tupple of values representing the unicity of the object def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (not self.generic, str(self.name), str(self.description))
Return a tupple of values representing the unicity of the object def get_comparable_values_for_ordering(self): """Return a tupple of values representing the unicity of the object """ return (0 if self.position >= 0 else 1, int(self.position), str(self.name), str(self.description))
Return a tupple of values representing the unicity of the object def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (not self.generic, int(self.code), str(self.message), str(self.description))
Return a proper object def factory(cls, object_source): """Return a proper object """ if object_source.type is ObjectRaw.Types.object: return ObjectObject(object_source) elif object_source.type not in ObjectRaw.Types or object_source.type is ObjectRaw.Types.type: ...
Return a tupple of values representing the unicity of the object def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (str(self.name), str(self.description), str(self.type), bool(self.optional), str(self.constraints) if isinstance(self,...
Return a tupple of values representing the unicity of the object def get_comparable_values(self): """Return a tupple of values representing the unicity of the object """ return (str(self.name), str(self.description), str(self.constraints))
Return a populated object Category from dictionary datas def create_from_name_and_dictionary(self, name, datas): """Return a populated object Category from dictionary datas """ category = ObjectCategory(name) self.set_common_datas(category, name, datas) if "order" in datas: ...
Return dict from a file config def load_from_file(self, file_path, format=None): """Return dict from a file config """ if format is None: base_name, file_extension = os.path.splitext(file_path) if file_extension in (".yaml", ".yml"): format = "yaml" ...
Return a list of dict from a directory containing files def load_all_from_directory(self, directory_path): """Return a list of dict from a directory containing files """ datas = [] for root, folders, files in os.walk(directory_path): for f in files: datas.app...
Represent instance of a class as JSON. def json_repr(obj): """Represent instance of a class as JSON. """ def serialize(obj): """Recursively walk object's hierarchy. """ if obj is None: return None if isinstance(obj, Enum): return str(obj) if ...
Return a populated Object Root from dictionnary datas def create_from_root(self, root_source): """Return a populated Object Root from dictionnary datas """ root_dto = ObjectRoot() root_dto.configuration = root_source.configuration root_dto.versions = [Version(x) for x in root_...
Populated common data for an element from dictionnary datas def set_common_datas(self, element, name, datas): """Populated common data for an element from dictionnary datas """ element.name = str(name) if "description" in datas: element.description = str(datas["description"]...
Populate a dictionary of elements def create_dictionary_of_element_from_dictionary(self, property_name, datas): """Populate a dictionary of elements """ response = {} if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], collections.Iterable...
Populate a list of elements def create_list_of_element_from_dictionary(self, property_name, datas): """Populate a list of elements """ response = [] if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], list): for value in datas[...
Factory enum type def get_enum(self, property, enum, datas): """Factory enum type """ str_property = str(datas[property]).lower() if str_property not in enum: raise ValueError("Unknow enum \"%s\" for \"%s\"." % (str_property, property)) return enum(str_property)
Create a template object file defined in the config object def create_from_config(self, config): """Create a template object file defined in the config object """ configService = ConfigService() template = TemplateService() template.output = config["output"]["location"] ...
Deploy network in equipments and set column 'active = 1' in tables redeipv4 :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output def deploy(self, id_networkv4): """Deploy network in equipments and set column 'active = 1' in tables redeipv4 :param id_networ...
Get IPv4 network :param id_networkv4: ID for NetworkIPv4 :return: IPv4 Network def get_by_id(self, id_networkv4): """Get IPv4 network :param id_networkv4: ID for NetworkIPv4 :return: IPv4 Network """ uri = 'api/networkv4/%s/' % id_networkv4 return s...
List IPv4 networks :param environment_vip: environment vip to filter :return: IPv4 Networks def list(self, environment_vip=None): """List IPv4 networks :param environment_vip: environment vip to filter :return: IPv4 Networks """ uri = 'api/networkv4/?' ...
Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ] :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output def undeploy(self, id_networkv4): """Remove deployment of network in equipments and set column 'active = 0' in tables re...
Check available ip in environment vip def check_vip_ip(self, ip, environment_vip): """ Check available ip in environment vip """ uri = 'api/ipv4/ip/%s/environment-vip/%s/' % (ip, environment_vip) return super(ApiNetworkIPv4, self).get(uri)
Delete ipv4 def delete_ipv4(self, ipv4_id): """ Delete ipv4 """ uri = 'api/ipv4/%s/' % (ipv4_id) return super(ApiNetworkIPv4, self).delete(uri)
Method to search ipv4's based on extends search. :param search: Dict containing QuerySets to find ipv4's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override d...
Method to delete network-ipv4's by their ids :param ids: Identifiers of network-ipv4's :return: None def delete(self, ids): """ Method to delete network-ipv4's by their ids :param ids: Identifiers of network-ipv4's :return: None """ url = build_uri_with...
Method to update network-ipv4's :param networkipv4s: List containing network-ipv4's desired to updated :return: None def update(self, networkipv4s): """ Method to update network-ipv4's :param networkipv4s: List containing network-ipv4's desired to updated :return: None...
Method to create network-ipv4's :param networkipv4s: List containing networkipv4's desired to be created on database :return: None def create(self, networkipv4s): """ Method to create network-ipv4's :param networkipv4s: List containing networkipv4's desired to be created on da...
Inserts a new Division Dc and returns its identifier. :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters :return: Dictionary with the following structure: :: {'division_dc': {'id': < id_division_dc >}} :raise InvalidParameterError: Name i...
Change Division Dc from by the identifier. :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero. :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters :return: None :raise InvalidParameterError: The identifier of Divisi...
Remove Division Dc from by the identifier. :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Division Dc is null and invalid. :raise DivisaoDcNaoExisteError: Division Dc not registere...
Method to search object types based on extends search. :param search: Dict containing QuerySets to find object types. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields t...
Find vlans by all search parameters :param number: Filter by vlan number column :param name: Filter by vlan name column :param iexact: Filter by name will be exact? :param environment: Filter by environment ID related :param net_type: Filter by network_type ID related :p...
List all VLANs from an environment. ** The itens returning from network is there to be compatible with other system ** :param id_ambiente: Environment identifier. :return: Following dictionary: :: {'vlan': [{'id': < id_vlan >, 'nome': < nome_vlan >, 'num_...
Inserts a new VLAN. :param nome: Name of Vlan. String with a maximum of 50 characters. :param id_tipo_rede: Identifier of the Network Type. Integer value and greater than zero. :param id_ambiente: Identifier of the Environment. Integer value and greater than zero. :param descricao: Desc...
Create new VLAN :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :param number: Number of Vlan :param acl_file: Acl IPv4 File name to VLAN. :param acl_file_v6: Acl IPv6 File name to VLAN. :par...
Edit a VLAN :param id_vlan: ID for Vlan :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :param number: Number of Vlan :param acl_file: Acl IPv4 File name to VLAN. :param acl_file_v6: Acl IPv6...
Set column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None def create_vlan(self, id_vlan): """ Set column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None """ vlan_map = dict() vlan_map['vlan_id'] = id_vlan code, ...
Create new VLAN without add NetworkIPv4. :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, ...
Check if there is communication permission for VLAN to trunk. Run script 'configurador'. The "stdout" key value of response dictionary is 1(one) if VLAN has permission, or 0(zero), otherwise. :param id_vlan: VLAN identifier. :param nome_equipamento: Equipment name. :pa...
Get VLAN by its identifier. :param id_vlan: VLAN identifier. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'id_tipo_rede': < id_tipo_rede >, ...
Get a VLAN by your primary key. Network IPv4/IPv6 related will also be fetched. :param id_vlan: ID for VLAN. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_amb...
List all VLANS having communication permission to trunk from a port in switch. Run script 'configurador'. :: The value of 'stdout' key of return dictionary can have a list of numbers or number intervals of VLAN´s, comma separated. Examples of possible returns of 'stdout' below: ...
Create VLAN in layer 2 using script 'navlan'. :param id_network_ipv4: NetworkIPv4 ID. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise NetworkIPv4NaoExisteError: NetworkIPv4 not ...
Create VLAN in layer 2 using script 'navlan'. :param id_network_ipv6: NetworkIPv6 ID. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise NetworkIPv6NaoExisteError: NetworkIPv6 not ...
Apply the file acl in equipments :param equipments: list of equipments :param vlan: Vvlan :param environment: Environment :param network: v4 or v6 :raise Exception: Failed to apply acl :return: True case Apply and sysout of script def apply_acl(self, equipments, vlan,...
Checking if the vlan insert need to be confirmed :param number_net: Filter by vlan number column :param id_environment_vlan: Filter by environment ID related :param ip_version: Ip version for checking :return: True is need confirmation, False if no need :raise AmbienteNaoExist...
Checking if environment has a number vlan available :param id_environment: Identifier of environment :param num_vlan: Vlan number :param id_vlan: Vlan indentifier (False if inserting a vlan) :return: True is has number available, False if hasn't :raise AmbienteNaoExisteError: ...
Validates ACL - IPv4 of VLAN from its identifier. Assigns 1 to 'acl_valida'. :param id_vlan: Identifier of the Vlan. Integer value and greater than zero. :return: None :raise InvalidParameterError: Vlan identifier is null and invalid. :raise VlanNaoExisteError: Vlan not regis...
Validates ACL - IPv6 of VLAN from its identifier. Assigns 1 to 'acl_valida_v6'. :param id_vlan: Identifier of the Vlan. Integer value and greater than zero. :return: None :raise InvalidParameterError: Vlan identifier is null and invalid. :raise VlanNaoExisteError: Vlan not re...
Remove a VLAN by your primary key. Execute script to remove VLAN :param id_vlan: ID for VLAN. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise InvalidParameterError: Iden...
Deallocate all relationships between Vlan. :param id_vlan: Identifier of the VLAN. Integer value and greater than zero. :return: None :raise InvalidParameterError: VLAN identifier is null and invalid. :raise VlanError: VLAN is active. :raise VlanNaoExisteError: VLAN not found....
Inserts a new VLAN. :param name: Name of Vlan. String with a maximum of 50 characters. :param id_network_type: Identifier of the Netwok Type. Integer value and greater than zero. :param id_environment: Identifier of the Environment. Integer value and greater than zero. :param descriptio...
Generate the script acl :param id_vlan: Vlan Id :param network_type: v4 or v6 :raise InvalidValueError: Attrs invalids. :raise XMLError: Networkapi failed to generate the XML response. :raise VlanACLDuplicatedError: ACL name duplicate. :raise VlanNotFoundError: Vlan not...
Create a relationship between User and Group. :param id_user: Identifier of the User. Integer value and greater than zero. :param id_group: Identifier of the Group. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'user_group': {'i...
Cria um string no formato XML a partir dos elementos do map. Os elementos do mapa serão nós filhos do root_name. Cada chave do map será um Nó no XML. E o valor da chave será o conteúdo do Nó. Exemplos: :: - Mapa: {'networkapi':1} XML: &lt;?xml version="1.0" encoding="UTF-8"?&gt;&l...
Cria um dicionário com os dados do XML. O dicionário terá como chave o nome do nó root e como valor o conteúdo do nó root. Quando o conteúdo de um nó é uma lista de nós então o valor do nó será um dicionário com uma chave para cada nó. Entretanto, se existir nós, de um mesmo pai, com o mesmo nome, entã...
List option vip. param environment_vip_id: Id of Environment Vip Param type_option: type option vip def option_vip_by_environment_vip_type(self, environment_vip_id, type_option): """ List option vip. param environment_vip_id: Id of Environment Vip Param type_option: type...
Method to search neighbors based on extends search. :param search: Dict containing QuerySets to find neighbors. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to over...
Method to delete neighbors by their id's :param ids: Identifiers of neighbors :return: None def delete(self, ids): """ Method to delete neighbors by their id's :param ids: Identifiers of neighbors :return: None """ url = build_uri_with_ids('api/v4/neigh...
Method to update neighbors :param neighbors: List containing neighbors desired to updated :return: None def update(self, neighbors): """ Method to update neighbors :param neighbors: List containing neighbors desired to updated :return: None """ data = ...
Method to create neighbors :param neighbors: List containing neighbors desired to be created on database :return: None def create(self, neighbors): """ Method to create neighbors :param neighbors: List containing neighbors desired to be created on database :return: Non...
Adiciona um equipamento na lista de equipamentos para operação de inserir/alterar um grupo virtual. :param id_tipo_equipamento: Identificador do tipo de equipamento. :param id_modelo: Identificador do modelo do equipamento. :param prefixo: Prefixo do nome do equipamento. :param id_grupo...
Adiciona um equipamento na lista de equipamentos para operação de remover um grupo virtual. :param id: Identificador do equipamento. :param id_ip: Identificador do IP do equipamento. :param ids_ips_vips: Lista com os identificadores de IPs criados para cada VIP e associados ao equip...
Adiciona um VIP na lista de VIPs para operação de inserir/alterar um grupo virtual. Os parâmetros abaixo somente são necessários para a operação de alteração: - 'real_maps': Deverá conter os reals atualmente criados para a requisição de VIP. - 'id_requisicao_vip': O identificador da re...
Adiciona um VIP na lista de VIPs para operação de remover um grupo virtual. :param id_ip: Identificador do IP criado para o VIP. :param id_equipamentos: Lista com os identificadores dos balanceadores associados ao IP do VIP. :return: None def add_vip_remove(self, id_ip, id_equipamentos): ...
Adiciona um vip à especificação do grupo virtual. :param id: Identificador de referencia do VIP. def add_vip_incremento(self, id): """Adiciona um vip à especificação do grupo virtual. :param id: Identificador de referencia do VIP. """ vip_map = dict() vip_map['id'] = ...
Get Equipment Access by id. :return: Dictionary with following: :: {'equipamento_acesso': {'id_equipamento': < id_equipamento >, 'fqdn': < fqdn >, 'user': < user >, 'pass': < pass >, 'id_tipo_acesso': < id_tipo_acesso >, ...
List all equipment access by equipment name :return: Dictionary with the following structure: :: {‘equipamento_acesso’:[ {'id': <id_equiptos_access>, 'equipamento': <id_equip>, 'fqdn': <fqdn>, 'user': <user>, 'password': <pass> '...
Add new relationship between equipment and access type and returns its id. :param id_equipamento: Equipment identifier. :param fqdn: Equipment FQDN. :param user: User. :param password: Password. :param id_tipo_acesso: Access Type identifier. :param enable_pass: Enable ac...