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

Some cleaning and organization in the code #44

Merged
merged 13 commits into from
Jan 22, 2024
Merged
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
5 changes: 3 additions & 2 deletions fordev/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
fordev.consts
-------------

Este módulo contém todas as variáveis com valores constantes usadas no pacote fordev.
Este módulo contém todas as variáveis com valores constantes
usadas no pacote fordev.
"""

URL_4DEV_API = 'https://www.4devs.com.br/ferramentas_online.php'

ALL_UF_CODE = [
'AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'ES', 'GO', 'MA',
'MT', 'MS', 'MG','PA', 'PB', 'PR', 'PE', 'PI', 'RJ',
'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ',
'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO', 'DF'
]

Expand Down
14 changes: 9 additions & 5 deletions fordev/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ def _create_headers(content_length: int, referer: str) -> dict:
Parameters
----------
content_length
Indica o tamanho do entity-body, em bytes, enviados no header para o destinatário.
Indica o tamanho do entity-body, em bytes, enviados no header
para o destinatário.

referer
Referência a ação a ser executada pela API do site 4devs.
Expand All @@ -28,8 +29,9 @@ def _create_headers(content_length: int, referer: str) -> dict:

headers = {
'user-agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
'Chrome/106.0.0.0 Safari/537.36'
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
' AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/106.0.0.0 Safari/537.36'
),
'authority': 'www.4devs.com.br',
'method': 'POST',
Expand Down Expand Up @@ -59,14 +61,16 @@ def fordev_request(content_length: int, referer: str, payload: dict) -> dict:
Parameters
----------
content_length
Indica o tamanho do entity-body, em bytes, enviados no header para o destinatário.
Indica o tamanho do entity-body, em bytes, enviados no header
para o destinatário.

referer
Referência a ação a ser executada pela API do site 4devs.
Pode-se interpretar como o endpoint do serviço a ser disponibilizado.

payload
Um dicionário de dados contendo a ação e outros dados solicitados pela API.
Um dicionário de dados contendo a ação e outros dados
solicitados pela API.
"""

try:
Expand Down
16 changes: 11 additions & 5 deletions fordev/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ def filter_bank_account_info(html: str) -> dict:

labels = [div.text for div in soup.find_all('div', 'output-subtitle')]

data_of_bank_account = [div.text for div in soup.find_all('div', 'output-txt')]
data_of_bank_account = [
div.text for div in soup.find_all('div', 'output-txt')
]

data_dict = dict(
zip(labels, data_of_bank_account)
Expand All @@ -65,7 +67,8 @@ def filter_vehicle_info(html: str) -> dict:

labels = [div.text[:-1] for div in soup.find_all('strong')]

data_of_vehicle = [input_.get('value') for input_ in soup.find_all('input', 'margem_menor')]
data_of_vehicle = [input_.get('value')
for input_ in soup.find_all('input', 'margem_menor')]

data_dict = dict(
zip(labels, data_of_vehicle)
Expand All @@ -88,7 +91,8 @@ def filter_credit_card_info(html: str) -> dict:

labels = [div.text for div in soup.find_all('div', 'output-subtitle')]

data_of_credit_card = [div.text.strip() for div in soup.find_all('div', 'output-txt')]
data_of_credit_card = [div.text.strip()
for div in soup.find_all('div', 'output-txt')]

data_dict = dict(
zip(labels, data_of_credit_card)
Expand All @@ -98,7 +102,8 @@ def filter_credit_card_info(html: str) -> dict:


def filter_company_info(html: str) -> dict:
"""Filtra dados de companhia (empresa/organização) contidos na estrutura HTML.
"""Filtra dados de companhia (empresa/organização) contidos na
estrutura HTML.

Parameters
----------
Expand All @@ -111,7 +116,8 @@ def filter_company_info(html: str) -> dict:

labels = [div.text[:-1] for div in soup.find_all('strong')]

data_of_company = [input_.get('value') for input_ in soup.find_all('input', 'margem_menor')]
data_of_company = [input_.get('value')
for input_ in soup.find_all('input', 'margem_menor')]

data_dict = dict(
zip(labels, data_of_company)
Expand Down
12 changes: 7 additions & 5 deletions fordev/generators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
fordev.generators
-----------------

Este módulo coleta dados aleatórios gerados pelo site `4Devs <https://www.4devs.com.br/>`_
e disponíbiliza uma API simples para uso.
Este módulo coleta dados aleatórios gerados pelo site
`4Devs <https://www.4devs.com.br/>`_ e disponíbiliza uma API simples para uso.

Use a função ``help()`` para mais informações:

Expand All @@ -30,16 +30,18 @@
Recebe o Código da **Unidade Federativa** para geração do dado.

Caso não saiba o que é ou não conheça o do estado que necessita,
obtenha mais informações em: https://pt.wikipedia.org/wiki/Subdivis%C3%B5es_do_Brasil
obtenha mais informações em:
- https://pt.wikipedia.org/wiki/Subdivisões_do_Brasil

formatting: bool
Se receber o valor ``True``, retorna os dados formatados.
Se receber o valor ``False``, retorna os dados sem formatação.

data_only: bool
Se receber o valor ``True``, retorna somente os dados em texto puro.
Se receber o valor ``False``, retorna um dicionário contendo uma chave ``msg`` e ``data`` ou ``error``
contendo valores correspondentes à nomenclatura de suas chaves.
Se receber o valor ``False``, retorna um dicionário contendo uma
chave ``msg`` e ``data`` ou ``error`` contendo valores correspondentes
à nomenclatura de suas chaves.

Sendo assim, sempre que os encontrar, utilize conforme o descrito acima.
"""
Expand Down
10 changes: 7 additions & 3 deletions fordev/generators/bank_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
from fordev.validators.utils import raise_for_invalid_uf


def bank_account(bank: int=0, uf_code: str='', data_only: bool=True) -> dict:
def bank_account(
bank: int = 0,
uf_code: str = '',
data_only: bool = True
) -> dict:
"""Gere dados de conta bancária.

Parameters
Expand All @@ -26,8 +30,8 @@ def bank_account(bank: int=0, uf_code: str='', data_only: bool=True) -> dict:

if not (0 <= bank <= 5):
msg_error = (
f'The bank code value "{bank}" is invalid. Enter a valid bank code.'
' The range is 0 to 5.'
f'The bank code value "{bank}" is invalid.'
' Enter a valid bank code. The range is 0 to 5.'
)

raise ValueError(msg_error)
Expand Down
11 changes: 9 additions & 2 deletions fordev/generators/certificate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@
-----------------------------
"""

from typing import Union

from fordev.core import fordev_request

from fordev.filters import data_format


def certificate(type_: str='I', formatting: bool=True, data_only: bool=True) -> str:
"""Gere o código de certidões (birth, wedding, religious wedding and death) aleatórias.
def certificate(
type_: str = 'I',
formatting: bool = True,
data_only: bool = True
) -> Union[str, dict]:
"""Gere o código de certidões (birth, wedding, religious wedding and death)
aleatórias.

Parameters
----------
Expand Down
4 changes: 3 additions & 1 deletion fordev/generators/city.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
----------------------
"""

from typing import Union

from fordev.core import fordev_request

from fordev.validators.utils import raise_for_invalid_uf
Expand All @@ -11,7 +13,7 @@
from fordev.filters import data_format


def city(uf_code: str='SP', data_only: bool=True) -> list:
def city(uf_code: str = 'SP', data_only: bool = True) -> Union[list, dict]:
"""Obtenha as cidades do UF especificado."""

uf_code = uf_code.upper()
Expand Down
4 changes: 3 additions & 1 deletion fordev/generators/cnh.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
---------------------
"""

from typing import Union

from fordev.core import fordev_request

from fordev.filters import data_format


def cnh(data_only: bool=True) -> str:
def cnh(data_only: bool = True) -> Union[str, dict]:
"""Geração aleatória de CNH (Carteira Nacional de Habilitação)."""

resp = fordev_request(
Expand Down
8 changes: 6 additions & 2 deletions fordev/generators/cnpj.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
----------------------
"""

from typing import Union

from fordev.core import fordev_request

from fordev.filters import data_format


def cnpj(formatting: bool=True, data_only: bool=True) -> str:
"""Gere o código do CNPJ(Cadastro Nacional da Pessoa Jurídica) aleatório."""
def cnpj(formatting: bool = True, data_only: bool = True) -> Union[str, dict]:
"""Gere o código do CNPJ(Cadastro Nacional da Pessoa Jurídica)
aleatório.
"""

resp = fordev_request(
content_length=27,
Expand Down
11 changes: 8 additions & 3 deletions fordev/generators/company.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@
from fordev.filters import data_format


def company(uf_code: str='SP', age: int=1, formatting: bool=True, data_only: bool=True) -> dict:
def company(
uf_code: str = 'SP',
age: int = 1,
formatting: bool = True,
data_only: bool = True
) -> dict:
"""Gere dados de companhia (empresa/organização) aleatório.

Parameters
Expand All @@ -26,8 +31,8 @@ def company(uf_code: str='SP', age: int=1, formatting: bool=True, data_only: boo

if not (1 <= age <= 30):
msg_error = (
f'The company age value "{age}" is invalid. Enter a valid company age.'
' The range is 1 to 30.'
f'The company age value "{age}" is invalid.'
' Enter a valid company age. The range is 1 to 30.'
)

raise ValueError(msg_error)
Expand Down
8 changes: 7 additions & 1 deletion fordev/generators/cpf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,20 @@
---------------------
"""

from typing import Union

from fordev.core import fordev_request

from fordev.filters import data_format

from fordev.validators.utils import raise_for_invalid_uf


def cpf(uf_code: str='', formatting: bool=True, data_only: bool=True) -> str:
def cpf(
uf_code: str = '',
formatting: bool = True,
data_only: bool = True
) -> Union[str, dict]:
"""Gere o código de um CPF(Cadastro de Pessoas Físicas) aleatório."""

uf_code = uf_code.upper()
Expand Down
16 changes: 10 additions & 6 deletions fordev/generators/credit_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
from fordev.filters import data_format


def credit_card(bank: int=0, formatting: bool=True, data_only: bool=True) -> dict:
def credit_card(
bank: int = 0,
formatting: bool = True,
data_only: bool = True
) -> dict:
"""Gere dados de cartão de crédito aleatório.

Parameters
Expand All @@ -28,16 +32,16 @@ def credit_card(bank: int=0, formatting: bool=True, data_only: bool=True) -> dic

if not (0 <= bank <= 10):
msg_error = (
f'The bank code value "{bank}" is invalid. Enter a valid bank code.'
' The range is 0 to 10.'
f'The bank code value "{bank}" is invalid.'
' Enter a valid bank code. The range is 0 to 10.'
)

raise ValueError(msg_error)

if bank != 0:
bank = ALL_BANK_FLAGS[bank]
bank_flag = ALL_BANK_FLAGS[bank]
else:
bank = random_choice(
bank_flag = random_choice(
list(ALL_BANK_FLAGS.values())
)

Expand All @@ -47,7 +51,7 @@ def credit_card(bank: int=0, formatting: bool=True, data_only: bool=True) -> dic
payload={
'acao': 'gerar_cc',
'pontuacao': 'S' if formatting else 'N',
'bandeira': bank
'bandeira': bank_flag
}
)

Expand Down
19 changes: 11 additions & 8 deletions fordev/generators/people.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
------------------------
"""

from typing import Union

from json import loads as json_loads

from fordev.core import fordev_request
Expand All @@ -11,13 +13,13 @@


def people(
n: int=1,
sex: str='R',
age: int=0,
uf_code: str='',
formatting: bool=True,
data_only: bool=True
) -> str:
n: int = 1,
sex: str = 'R',
age: int = 0,
uf_code: str = '',
formatting: bool = True,
data_only: bool = True
) -> Union[str, dict]:
"""Gere dados de pessoa(s) aleatório(s)

Parameters
Expand All @@ -32,7 +34,8 @@ def people(
https://fordev.rtfd.io/pt_BR/latest/fordev/generators.html

age
A idade da pessoa para geração dos dados. A idade mínima é 18 e a máxima é 80.
A idade da pessoa para geração dos dados. A idade mínima é 18 e a
máxima é 80.
"""

sex = sex.upper()
Expand Down
7 changes: 6 additions & 1 deletion fordev/generators/pis_pasep.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@
---------------------------
"""

from typing import Union

from fordev.core import fordev_request

from fordev.filters import data_format


def pis_pasep(formatting: bool=True, data_only: bool=True) -> str:
def pis_pasep(
formatting: bool = True,
data_only: bool = True
) -> Union[str, dict]:
"""Gere o código do PIS/PASEP aleatório."""

resp = fordev_request(
Expand Down
Loading