Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mudanças nas funções de CEP #477

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions brutils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
# CEP Imports
from brutils.cep import (
format_cep,
get_address_from_cep,
get_cep_information_from_address,
)
from brutils.cep import generate as generate_cep
from brutils.cep import is_valid as is_valid_cep
from brutils.cep import remove_symbols as remove_symbols_cep

# CNPJ Imports
from brutils.cnpj import format_cnpj
Expand Down Expand Up @@ -82,8 +78,6 @@
"get_address_from_cep",
"get_cep_information_from_address",
"generate_cep",
"is_valid_cep",
"remove_symbols_cep",
# CNPJ
"format_cnpj",
"generate_cnpj",
Expand Down
168 changes: 23 additions & 145 deletions brutils/cep.py
Original file line number Diff line number Diff line change
@@ -1,119 +1,13 @@
from json import loads
from random import randint
from unicodedata import normalize
from urllib.request import urlopen

from brutils.data.enums import UF
from brutils.exceptions import CEPNotFound, InvalidCEP
from brutils.types import Address

# FORMATTING
############


def remove_symbols(dirty): # type: (str) -> str
"""
Removes specific symbols from a given CEP (Postal Code).

This function takes a CEP (Postal Code) as input and removes all occurrences
of the '.' and '-' characters from it.

Args:
cep (str): The input CEP (Postal Code) containing symbols to be removed.

Returns:
str: A new string with the specified symbols removed.

Example:
>>> remove_symbols("123-45.678.9")
"123456789"
>>> remove_symbols("abc.xyz")
"abcxyz"
"""

return "".join(filter(lambda char: char not in ".-", dirty))


def format_cep(cep): # type: (str) -> str | None
"""
Formats a Brazilian CEP (Postal Code) into a standard format.

This function takes a CEP (Postal Code) as input and, if it is a valid
8-digit CEP, formats it into the standard "12345-678" format.

Args:
cep (str): The input CEP (Postal Code) to be formatted.

Returns:
str: The formatted CEP in the "12345-678" format if it's valid,
None if it's not valid.

Example:
>>> format_cep("12345678")
"12345-678"
>>> format_cep("12345")
None
"""

return f"{cep[:5]}-{cep[5:8]}" if is_valid(cep) else None


# OPERATIONS
############


def is_valid(cep): # type: (str) -> bool
"""
Checks if a CEP (Postal Code) is valid.

To be considered valid, the input must be a string containing exactly 8
digits.
This function does not verify if the CEP is a real postal code; it only
validates the format of the string.

Args:
cep (str): The string containing the CEP to be checked.

Returns:
bool: True if the CEP is valid (8 digits), False otherwise.

Example:
>>> is_valid("12345678")
True
>>> is_valid("12345")
False
>>> is_valid("abcdefgh")
False

Source:
https://en.wikipedia.org/wiki/Código_de_Endereçamento_Postal
"""

return isinstance(cep, str) and len(cep) == 8 and cep.isdigit()


def generate(): # type: () -> str
"""
Generates a random 8-digit CEP (Postal Code) number as a string.

Returns:
str: A randomly generated 8-digit number.

Example:
>>> generate()
"12345678"
"""

generated_number = ""

for _ in range(8):
generated_number = generated_number + str(randint(0, 9))

return generated_number


# Reference: https://viacep.com.br/
def get_address_from_cep(cep, raise_exceptions=False): # type: (str, bool) -> Address | None
def get_address_from_cep(cep: str) -> Address | None:
"""
Fetches address information from a given CEP (Postal Code) using the ViaCEP API.

Expand All @@ -122,8 +16,7 @@ def get_address_from_cep(cep, raise_exceptions=False): # type: (str, bool) -> A
raise_exceptions (bool, optional): Whether to raise exceptions when the CEP is invalid or not found. Defaults to False.

Raises:
InvalidCEP: When the input CEP is invalid.
CEPNotFound: When the input CEP is not found.
ValueError: raised by urlopen.

Returns:
Address | None: An Address object (TypedDict) containing the address information if the CEP is found, None otherwise.
Expand All @@ -146,43 +39,35 @@ def get_address_from_cep(cep, raise_exceptions=False): # type: (str, bool) -> A
>>> get_address_from_cep("abcdefg")
None

>>> get_address_from_cep("abcdefg", True)
InvalidCEP: CEP 'abcdefg' is invalid.
>>> get_address_from_cep("abcdefg")
None

>>> get_address_from_cep("00000000", True)
CEPNotFound: 00000000
>>> get_address_from_cep("00000000")
None
"""
base_api_url = "https://viacep.com.br/ws/{}/json/"

clean_cep = remove_symbols(cep)
cep_is_valid = is_valid(clean_cep)
# Removing some symbols from cep.
clean_cep = "".join(filter(lambda char: char not in ".-", cep))
# Cheking if a cep is value.
cep_is_valid = isinstance(cep, str) and len(cep) == 8 and cep.isdigit()

if not cep_is_valid:
if raise_exceptions:
raise InvalidCEP(cep)

return None

try:
with urlopen(base_api_url.format(clean_cep)) as f:
response = f.read()
data = loads(response)
return None if data.get("erro") else Address(**loads(response))

if data.get("erro", False):
raise CEPNotFound(cep)

return Address(**loads(response))

except Exception as e:
if raise_exceptions:
raise CEPNotFound(cep) from e

except ValueError:
return None


def get_cep_information_from_address(
federal_unit, city, street, raise_exceptions=False
): # type: (str, str, str, bool) -> list[Address] | None
federal_unit: str, city: str, street: str
) -> list[Address] | None:
"""
Fetches CEP (Postal Code) options from a given address using the ViaCEP API.

Expand All @@ -193,8 +78,7 @@ def get_cep_information_from_address(
raise_exceptions (bool, optional): Whether to raise exceptions when the address is invalid or not found. Defaults to False.

Raises:
ValueError: When the input UF is invalid.
CEPNotFound: When the input address is not found.
ValueError: raised by urlopen.

Returns:
list[Address] | None: A list of Address objects (TypedDict) containing the address information if the address is found, None otherwise.
Expand All @@ -220,18 +104,15 @@ def get_cep_information_from_address(
None

>>> get_cep_information_from_address("XX", "Example", "Example", True)
ValueError: Invalid UF: XX
None

>>> get_cep_information_from_address("SP", "Example", "Example", True)
CEPNotFound: SP - Example - Example
None
"""
if federal_unit in UF.values:
federal_unit = UF(federal_unit).name

if federal_unit not in UF.names:
if raise_exceptions:
raise ValueError(f"Invalid UF: {federal_unit}")

return None

base_api_url = "https://viacep.com.br/ws/{}/{}/{}/json/"
Expand All @@ -255,14 +136,11 @@ def get_cep_information_from_address(
) as f:
response = f.read()
response = loads(response)
return (
None
if len(response) == 0
else [Address(**address) for address in response]
)

if len(response) == 0:
raise CEPNotFound(f"{federal_unit} - {city} - {street}")

return [Address(**address) for address in response]

except Exception as e:
if raise_exceptions:
raise CEPNotFound(f"{federal_unit} - {city} - {street}") from e

except ValueError:
return None
2 changes: 1 addition & 1 deletion brutils/exceptions/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .cep import CEPNotFound, InvalidCEP

8 changes: 0 additions & 8 deletions brutils/exceptions/cep.py

This file was deleted.

Loading
Loading