Skip to content

Commit 4760c62

Browse files
authored
Merge pull request #5 from buserbrasil/ruff-check-and-format
style/pep: apply ruff auto-fixes and formatting
2 parents aca7c92 + 7694681 commit 4760c62

File tree

18 files changed

+601
-219
lines changed

18 files changed

+601
-219
lines changed

.github/workflows/test.yml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,22 @@ on:
99
- main
1010

1111
jobs:
12+
code-quality:
13+
runs-on: ubuntu-latest
14+
steps:
15+
- uses: actions/checkout@v4
16+
17+
- name: Install the latest version of uv and set the python version
18+
uses: astral-sh/setup-uv@v5
19+
with:
20+
python-version: ${{ matrix.python-version }}
21+
22+
- name: ruff format --check
23+
run: uv run ruff check
24+
25+
- name: ruff check
26+
run: uv run ruff check
27+
1228
test:
1329
runs-on: ubuntu-latest
1430
strategy:

pyproject.toml

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,21 @@ name = "santander-python-sdk"
33
dynamic = ["version"]
44
description = "Client não oficial da API do Santander em Python"
55
authors = [
6-
{ name = "Samuel Rodrigues Coelho", email = "[email protected]" }
6+
{ name = "Samuel Rodrigues Coelho", email = "[email protected]" },
77
]
88
readme = "README.md"
99
keywords = ["santander", "api", "client", "python"]
1010
requires-python = ">=3.11"
1111

1212
classifiers = [
13-
# 3 - Alpha
14-
# 4 - Beta
15-
# 5 - Production/Stable
16-
"Development Status :: 3 - Alpha",
17-
18-
"Intended Audience :: Developers",
19-
"Topic :: Software Development :: Libraries :: Python Modules",
20-
21-
"License :: OSI Approved :: MIT License",
22-
23-
"Programming Language :: Python :: 3.11"
24-
]
25-
dependencies = [
26-
"python-dateutil~=2.0",
27-
"requests>=2",
13+
"Development Status :: 3 - Alpha",
14+
"Intended Audience :: Developers",
15+
"Topic :: Software Development :: Libraries :: Python Modules",
16+
"License :: OSI Approved :: MIT License",
17+
"Programming Language :: Python :: 3.11",
18+
"Programming Language :: Python :: 3.12",
2819
]
20+
dependencies = ["python-dateutil~=2.0", "requests>=2"]
2921

3022
[project.urls]
3123
homepage = "https://github.com/buserbrasil/santander-python-sdk"
@@ -38,4 +30,8 @@ dev-dependencies = [
3830
"requests-mock>=1.10.0",
3931
"pytest-cov>=4.0.0",
4032
"pytest-mock>=3.14.0",
33+
"ruff>=0.9.5",
4134
]
35+
36+
[tool.ruff.lint]
37+
flake8-tidy-imports.ban-relative-imports = "all"

santander_client/api_client/__init__.py

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,46 @@
11
import logging
2-
from typing import TypedDict
3-
from .exceptions import SantanderConfigurationException, SantanderWorkspaceException
4-
from .workspaces import get_first_workspace_id_of_type
5-
from .client import SantanderApiClient
6-
from .client_configuration import SantanderClientConfiguration
7-
2+
from santander_client.api_client.exceptions import (
3+
SantanderConfigurationException,
4+
SantanderWorkspaceException,
5+
)
6+
from santander_client.api_client.workspaces import get_first_workspace_id_of_type
7+
from santander_client.api_client.client import SantanderApiClient
8+
from santander_client.api_client.client_configuration import (
9+
SantanderClientConfiguration,
10+
)
11+
812
logger = logging.getLogger("santanderLogger")
9-
13+
1014
santander_client_configuration = None
11-
15+
16+
1217
def set_configuration(configuration: SantanderClientConfiguration) -> None:
1318
if not isinstance(configuration, SantanderClientConfiguration):
1419
raise SantanderConfigurationException("Configuração inválida fornecida.")
15-
20+
1621
global santander_client_configuration
1722
santander_client_configuration = configuration
18-
23+
24+
1925
def get_client() -> SantanderApiClient:
2026
"""
2127
Creates and returns an instance of SantanderApiClient based on the provided configuration.
2228
"""
2329
if not santander_client_configuration:
24-
raise SantanderConfigurationException("Configuração do client (SantanderClientConfiguration) não foi denida.")
30+
raise SantanderConfigurationException(
31+
"Configuração do client (SantanderClientConfiguration) não foi denida."
32+
)
2533

2634
santander_client_instance = SantanderApiClient(santander_client_configuration)
2735

2836
if not santander_client_configuration.workspace_id:
29-
workspace_id = get_first_workspace_id_of_type(santander_client_instance, "PAYMENTS")
37+
workspace_id = get_first_workspace_id_of_type(
38+
santander_client_instance, "PAYMENTS"
39+
)
3040
if not workspace_id:
31-
raise SantanderWorkspaceException("Conta sem configuração de workspace na configuração e na conta.")
41+
raise SantanderWorkspaceException(
42+
"Conta sem configuração de workspace na configuração e na conta."
43+
)
3244

3345
logger.info(f"Workspace obtido e configurado com sucesso: {workspace_id}")
3446
santander_client_configuration.set_workspace_id(workspace_id)

santander_client/api_client/client.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ def patch(self, endpoint: str, data: dict) -> dict:
6262
@property
6363
def is_authenticated(self) -> bool:
6464
return bool(
65-
self.token and (self.token_expires_at - BEFORE_EXPIRE_TOKEN_SECONDS) > datetime.now()
65+
self.token
66+
and (self.token_expires_at - BEFORE_EXPIRE_TOKEN_SECONDS) > datetime.now()
6667
)
6768

6869
def _ensure_requirements(self) -> None:
@@ -75,7 +76,9 @@ def _authenticate(self) -> None:
7576
if not self.token:
7677
raise SantanderClientException("Token de autenticação não encontrado")
7778

78-
self.token_expires_at = datetime.now() + timedelta(seconds=token_data.get("expires_in", 120))
79+
self.token_expires_at = datetime.now() + timedelta(
80+
seconds=token_data.get("expires_in", 120)
81+
)
7982
self.session.headers = {
8083
"Authorization": f"Bearer {self.token}",
8184
"X-Application-Key": self.config.client_id,
@@ -93,13 +96,20 @@ def _request_token(self) -> dict:
9396
}
9497
try:
9598
response = self.session.post(
96-
url, data=data, headers=headers, verify=True, timeout=60, cert=self.config.cert
99+
url,
100+
data=data,
101+
headers=headers,
102+
verify=True,
103+
timeout=60,
104+
cert=self.config.cert,
97105
)
98106
response.raise_for_status()
99107
except requests.exceptions.RequestException as e:
100108
status_code = getattr(e.response, "status_code", None)
101109
response = try_parse_response_to_json(e.response)
102-
raise SantanderRequestException(f"Erro na obtenção do Token: {e}", status_code, response)
110+
raise SantanderRequestException(
111+
f"Erro na obtenção do Token: {e}", status_code, response
112+
)
103113
token_data = response.json()
104114
return token_data
105115

@@ -112,19 +122,25 @@ def _prepare_url(self, endpoint: str) -> str:
112122
url = url.replace(":workspaceid", self.config.workspace_id)
113123
return url
114124

115-
def _request(self, method: str, endpoint: str, data: dict = None, params: dict = None) -> dict:
125+
def _request(
126+
self, method: str, endpoint: str, data: dict = None, params: dict = None
127+
) -> dict:
116128
self._ensure_requirements()
117129
url = self._prepare_url(endpoint)
118130

119131
try:
120-
response = self.session.request(method, url, json=data, params=params, timeout=60)
132+
response = self.session.request(
133+
method, url, json=data, params=params, timeout=60
134+
)
121135
response.raise_for_status()
122136
return response.json()
123137
except requests.exceptions.RequestException as e:
124138
status_code = getattr(e.response, "status_code", None)
125139
error_content = try_parse_response_to_json(e.response)
126140
status_description = get_status_code_description(status_code)
127141

128-
raise SantanderRequestException(status_description, status_code, error_content)
142+
raise SantanderRequestException(
143+
status_description, status_code, error_content
144+
)
129145
except Exception as e:
130146
raise SantanderRequestException(f"Erro na requisição: {e}", None, None)
Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
class SantanderClientConfiguration:
2-
3-
def __init__(self, client_id: str, client_secret: str, cert: str, base_url: str, workspace_id: str = ""):
2+
def __init__(
3+
self,
4+
client_id: str,
5+
client_secret: str,
6+
cert: str,
7+
base_url: str,
8+
workspace_id: str = "",
9+
):
410
self.client_id = client_id
511
self.client_secret = client_secret
612
self.workspace_id = workspace_id
@@ -10,6 +16,7 @@ def __init__(self, client_id: str, client_secret: str, cert: str, base_url: str,
1016
def set_workspace_id(self, workspace_id: str):
1117
self.workspace_id = workspace_id
1218

13-
1419
def __repr__(self):
15-
return f'SantanderClientConfiguration<client_id={self.client_id} cert={self.cert}>'
20+
return (
21+
f"SantanderClientConfiguration<client_id={self.client_id} cert={self.cert}>"
22+
)

santander_client/api_client/helpers.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@
77
import re
88
import requests
99

10-
from santander_client.api_client.exceptions import SantanderRequestException, SantanderValueErrorException
10+
from santander_client.api_client.exceptions import (
11+
SantanderRequestException,
12+
SantanderValueErrorException,
13+
)
14+
1115
logger = logging.getLogger("santanderLogger")
1216

1317
LENGTH_CNPJ = 14
@@ -81,12 +85,16 @@ def get_status_code_description(status_code: int | str) -> str:
8185

8286

8387
def today():
84-
now = timezone.now().replace(tzinfo=tz.UTC).astimezone(tz.gettz("America/Sao_Paulo"))
88+
now = (
89+
timezone.now().replace(tzinfo=tz.UTC).astimezone(tz.gettz("America/Sao_Paulo"))
90+
)
8591
return now.date()
86-
92+
93+
8794
def only_numbers(s):
8895
return re.sub("[^0-9]", "", s) if s else s
8996

97+
9098
def is_valid_cpf(cpf):
9199
clean_cpf = only_numbers(cpf)
92100
if (
@@ -98,9 +106,7 @@ def is_valid_cpf(cpf):
98106
digit = {0: 0, 1: 0}
99107
a = 10
100108
for c in range(2):
101-
digit[c] = sum(
102-
i * int(clean_cpf[idx]) for idx, i in enumerate(range(a, 1, -1))
103-
)
109+
digit[c] = sum(i * int(clean_cpf[idx]) for idx, i in enumerate(range(a, 1, -1)))
104110

105111
digit[c] = int(11 - (digit[c] % 11))
106112
if digit[c] > 9:
@@ -129,6 +135,7 @@ def is_valid_cnpj(cnpj):
129135

130136
return True
131137

138+
132139
def retry_one_time_on_request_exception(func):
133140
def wrapper(*args, **kwargs):
134141
try:
@@ -139,6 +146,7 @@ def wrapper(*args, **kwargs):
139146

140147
return wrapper
141148

149+
142150
def convert_to_decimal(cents: int) -> Decimal:
143151
return Decimal(cents) / 100
144152

@@ -148,4 +156,4 @@ def document_type(document_number: str) -> str:
148156
return "CPF"
149157
if len(document_number) == 14:
150158
return "CNPJ"
151-
raise SantanderValueErrorException('Unknown document type "{document_number}"')
159+
raise SantanderValueErrorException('Unknown document type "{document_number}"')

santander_client/api_client/workspaces.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,21 @@ def get_workspaces(client: SantanderAbstractApiClient):
2828
return response.get("_content", None)
2929

3030

31-
def get_first_workspace_id_of_type(client: SantanderAbstractApiClient, workspace_type: WorkspaceType) -> str | None:
31+
def get_first_workspace_id_of_type(
32+
client: SantanderAbstractApiClient, workspace_type: WorkspaceType
33+
) -> str | None:
3234
_check_client_instance(client)
3335
workspaces = get_workspaces(client)
3436
if len(workspaces) == 0:
3537
return None
3638

3739
workspace_id = next(
38-
(w["id"] for w in workspaces if w.get("type") == workspace_type and w.get("status") == "ACTIVE"), None
40+
(
41+
w["id"]
42+
for w in workspaces
43+
if w.get("type") == workspace_type and w.get("status") == "ACTIVE"
44+
),
45+
None,
3946
)
4047
return workspace_id
4148

@@ -45,4 +52,6 @@ def _check_client_instance(client):
4552
raise SantanderClientException("O client é obrigatório")
4653

4754
if not issubclass(client.__class__, SantanderAbstractApiClient):
48-
raise SantanderClientException("O client deve ser uma instância de Herança de BaseSantanderApiClient")
55+
raise SantanderClientException(
56+
"O client deve ser uma instância de Herança de BaseSantanderApiClient"
57+
)

0 commit comments

Comments
 (0)