datamais-api 0.5.0__tar.gz → 0.6.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {datamais_api-0.5.0/src/datamais_api.egg-info → datamais_api-0.6.0}/PKG-INFO +63 -4
- {datamais_api-0.5.0 → datamais_api-0.6.0}/README.md +62 -3
- {datamais_api-0.5.0 → datamais_api-0.6.0}/pyproject.toml +1 -1
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api/__init__.py +1 -1
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api/cliente.py +26 -15
- {datamais_api-0.5.0 → datamais_api-0.6.0/src/datamais_api.egg-info}/PKG-INFO +63 -4
- {datamais_api-0.5.0 → datamais_api-0.6.0}/tests/test_cliente.py +135 -7
- {datamais_api-0.5.0 → datamais_api-0.6.0}/tests/test_pandas.py +27 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/LICENSE +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/setup.cfg +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api/config.py +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api/erros.py +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api/eventos.py +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api/modelos.py +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api/py.typed +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api.egg-info/SOURCES.txt +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api.egg-info/dependency_links.txt +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api.egg-info/requires.txt +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/src/datamais_api.egg-info/top_level.txt +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/tests/test_acompanhar.py +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/tests/test_config.py +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/tests/test_eventos.py +0 -0
- {datamais_api-0.5.0 → datamais_api-0.6.0}/tests/test_layout.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datamais-api
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.0
|
|
4
4
|
Summary: Cliente Python da API DataMais, feito para bots de carga de dados.
|
|
5
5
|
Author: SECONV-RR
|
|
6
6
|
License-Expression: LicenseRef-Proprietary
|
|
@@ -107,6 +107,65 @@ existir e ter dono — uma chave não é um usuário, então ela nunca pode cria
|
|
|
107
107
|
grupo. Uma fonte que já existe volta como `ErroConflito`; um grupo inexistente
|
|
108
108
|
ou sem dono, como `ErroValidacao` (`422`).
|
|
109
109
|
|
|
110
|
+
## Fontes independentes
|
|
111
|
+
|
|
112
|
+
Uma fonte independente não pertence a um grupo. Ela tem um slug global e pode
|
|
113
|
+
ser anexada a vários grupos, que a leem pelo caminho do grupo. Quem escreve
|
|
114
|
+
nela usa as rotas `/fontes/independentes/{slug}/...`, com uma chave de API que
|
|
115
|
+
tenha `independent:<slug>:manage` ou com uma sessão que tenha
|
|
116
|
+
`datasets:independent`, `dev` ou `admin`.
|
|
117
|
+
|
|
118
|
+
| Método | Rota | Credenciais |
|
|
119
|
+
| --- | --- | --- |
|
|
120
|
+
| `substituir_dados_fonte_independente(slug, colunas, linhas)` | `PUT /fontes/independentes/{slug}/dados` | chave de API ou sessão |
|
|
121
|
+
| `substituir_dados_fonte_independente_de_dataframe(slug, frame, colunas=None)` | `PUT /fontes/independentes/{slug}/dados` | chave de API ou sessão |
|
|
122
|
+
| `obter_relacoes_fonte_independente(slug)` | `GET /fontes/independentes/{slug}/relacoes` | chave de API ou sessão |
|
|
123
|
+
| `definir_relacoes_fonte_independente(slug, relacoes)` | `PUT /fontes/independentes/{slug}/relacoes` | chave de API ou sessão |
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from datamais_api import (
|
|
127
|
+
ClienteDatamais,
|
|
128
|
+
Coluna,
|
|
129
|
+
ColunaRelacao,
|
|
130
|
+
DestinoRelacao,
|
|
131
|
+
RelacaoFonte,
|
|
132
|
+
TipoColuna,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
colunas = [
|
|
136
|
+
Coluna("ibge", "IBGE", escondida=True),
|
|
137
|
+
Coluna("municipio", "Município", filtravel=True),
|
|
138
|
+
Coluna("populacao", "População", TipoColuna.INTEIRO),
|
|
139
|
+
]
|
|
140
|
+
linhas = [{"ibge": "1400100", "municipio": "Boa Vista", "populacao": 413486}]
|
|
141
|
+
relacoes = [
|
|
142
|
+
RelacaoFonte(
|
|
143
|
+
destino=DestinoRelacao(fonte="municipios", independente=True),
|
|
144
|
+
colunas=[ColunaRelacao(origem="ibge", destino="ibge")],
|
|
145
|
+
),
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
with ClienteDatamais() as cliente:
|
|
149
|
+
cliente.substituir_dados_fonte_independente("municipios", colunas, linhas)
|
|
150
|
+
cliente.definir_relacoes_fonte_independente("convenios-estaduais", relacoes)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`substituir_dados_fonte_independente` troca de uma vez o catálogo de colunas e
|
|
154
|
+
as linhas da fonte, com o mesmo corpo de `substituir_dados_fonte`, e a versão
|
|
155
|
+
nova vale para todos os grupos em que a fonte está anexada. A variante
|
|
156
|
+
`_de_dataframe` recebe um DataFrame e infere o catálogo como
|
|
157
|
+
`substituir_dados_fonte_de_dataframe` (veja [pandas](#pandas)).
|
|
158
|
+
|
|
159
|
+
`definir_relacoes_fonte_independente` troca o conjunto inteiro de relações da
|
|
160
|
+
fonte e devolve o que a API gravou; uma lista vazia remove todas. Como a fonte
|
|
161
|
+
não tem grupo, o destino precisa vir com `grupo` explícito ou com
|
|
162
|
+
`independente=True`. As colunas citadas precisam existir nas duas fontes, então
|
|
163
|
+
carregue os dados delas antes de declarar a relação. Os corpos e as respostas
|
|
164
|
+
são os mesmos de `obter_relacoes_fonte` e `definir_relacoes_fonte`.
|
|
165
|
+
|
|
166
|
+
Uma chave sem a permissão da fonte recebe `ErroProibido` (403), e um slug que
|
|
167
|
+
não existe, `ErroNaoEncontrado` (404).
|
|
168
|
+
|
|
110
169
|
## Consultas no servidor
|
|
111
170
|
|
|
112
171
|
`consultar_fonte` filtra, agrupa, agrega, ordena e junta as linhas de uma fonte
|
|
@@ -304,9 +363,9 @@ with ClienteDatamais(token=token_da_sessao) as cliente:
|
|
|
304
363
|
```
|
|
305
364
|
|
|
306
365
|
A autenticação é resolvida a cada requisição: o `token` vai como
|
|
307
|
-
`Authorization: Bearer` e, sem ele, vai o `X-API-Chave`.
|
|
308
|
-
|
|
309
|
-
sem token, antes de fazer a requisição.
|
|
366
|
+
`Authorization: Bearer` e, sem ele, vai o `X-API-Chave`. A única rota que só
|
|
367
|
+
aceita sessão, `acompanhar_dados_fonte_independente`, levanta
|
|
368
|
+
`ErroSessaoObrigatoria` sem token, antes de fazer a requisição.
|
|
310
369
|
|
|
311
370
|
`eu` devolve o `Usuario` da sessão, ou `None` quando ela não vale mais.
|
|
312
371
|
`eu(token)` usa outro token só naquela chamada. `sair` revoga a sessão na API
|
|
@@ -88,6 +88,65 @@ existir e ter dono — uma chave não é um usuário, então ela nunca pode cria
|
|
|
88
88
|
grupo. Uma fonte que já existe volta como `ErroConflito`; um grupo inexistente
|
|
89
89
|
ou sem dono, como `ErroValidacao` (`422`).
|
|
90
90
|
|
|
91
|
+
## Fontes independentes
|
|
92
|
+
|
|
93
|
+
Uma fonte independente não pertence a um grupo. Ela tem um slug global e pode
|
|
94
|
+
ser anexada a vários grupos, que a leem pelo caminho do grupo. Quem escreve
|
|
95
|
+
nela usa as rotas `/fontes/independentes/{slug}/...`, com uma chave de API que
|
|
96
|
+
tenha `independent:<slug>:manage` ou com uma sessão que tenha
|
|
97
|
+
`datasets:independent`, `dev` ou `admin`.
|
|
98
|
+
|
|
99
|
+
| Método | Rota | Credenciais |
|
|
100
|
+
| --- | --- | --- |
|
|
101
|
+
| `substituir_dados_fonte_independente(slug, colunas, linhas)` | `PUT /fontes/independentes/{slug}/dados` | chave de API ou sessão |
|
|
102
|
+
| `substituir_dados_fonte_independente_de_dataframe(slug, frame, colunas=None)` | `PUT /fontes/independentes/{slug}/dados` | chave de API ou sessão |
|
|
103
|
+
| `obter_relacoes_fonte_independente(slug)` | `GET /fontes/independentes/{slug}/relacoes` | chave de API ou sessão |
|
|
104
|
+
| `definir_relacoes_fonte_independente(slug, relacoes)` | `PUT /fontes/independentes/{slug}/relacoes` | chave de API ou sessão |
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from datamais_api import (
|
|
108
|
+
ClienteDatamais,
|
|
109
|
+
Coluna,
|
|
110
|
+
ColunaRelacao,
|
|
111
|
+
DestinoRelacao,
|
|
112
|
+
RelacaoFonte,
|
|
113
|
+
TipoColuna,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
colunas = [
|
|
117
|
+
Coluna("ibge", "IBGE", escondida=True),
|
|
118
|
+
Coluna("municipio", "Município", filtravel=True),
|
|
119
|
+
Coluna("populacao", "População", TipoColuna.INTEIRO),
|
|
120
|
+
]
|
|
121
|
+
linhas = [{"ibge": "1400100", "municipio": "Boa Vista", "populacao": 413486}]
|
|
122
|
+
relacoes = [
|
|
123
|
+
RelacaoFonte(
|
|
124
|
+
destino=DestinoRelacao(fonte="municipios", independente=True),
|
|
125
|
+
colunas=[ColunaRelacao(origem="ibge", destino="ibge")],
|
|
126
|
+
),
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
with ClienteDatamais() as cliente:
|
|
130
|
+
cliente.substituir_dados_fonte_independente("municipios", colunas, linhas)
|
|
131
|
+
cliente.definir_relacoes_fonte_independente("convenios-estaduais", relacoes)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`substituir_dados_fonte_independente` troca de uma vez o catálogo de colunas e
|
|
135
|
+
as linhas da fonte, com o mesmo corpo de `substituir_dados_fonte`, e a versão
|
|
136
|
+
nova vale para todos os grupos em que a fonte está anexada. A variante
|
|
137
|
+
`_de_dataframe` recebe um DataFrame e infere o catálogo como
|
|
138
|
+
`substituir_dados_fonte_de_dataframe` (veja [pandas](#pandas)).
|
|
139
|
+
|
|
140
|
+
`definir_relacoes_fonte_independente` troca o conjunto inteiro de relações da
|
|
141
|
+
fonte e devolve o que a API gravou; uma lista vazia remove todas. Como a fonte
|
|
142
|
+
não tem grupo, o destino precisa vir com `grupo` explícito ou com
|
|
143
|
+
`independente=True`. As colunas citadas precisam existir nas duas fontes, então
|
|
144
|
+
carregue os dados delas antes de declarar a relação. Os corpos e as respostas
|
|
145
|
+
são os mesmos de `obter_relacoes_fonte` e `definir_relacoes_fonte`.
|
|
146
|
+
|
|
147
|
+
Uma chave sem a permissão da fonte recebe `ErroProibido` (403), e um slug que
|
|
148
|
+
não existe, `ErroNaoEncontrado` (404).
|
|
149
|
+
|
|
91
150
|
## Consultas no servidor
|
|
92
151
|
|
|
93
152
|
`consultar_fonte` filtra, agrupa, agrega, ordena e junta as linhas de uma fonte
|
|
@@ -285,9 +344,9 @@ with ClienteDatamais(token=token_da_sessao) as cliente:
|
|
|
285
344
|
```
|
|
286
345
|
|
|
287
346
|
A autenticação é resolvida a cada requisição: o `token` vai como
|
|
288
|
-
`Authorization: Bearer` e, sem ele, vai o `X-API-Chave`.
|
|
289
|
-
|
|
290
|
-
sem token, antes de fazer a requisição.
|
|
347
|
+
`Authorization: Bearer` e, sem ele, vai o `X-API-Chave`. A única rota que só
|
|
348
|
+
aceita sessão, `acompanhar_dados_fonte_independente`, levanta
|
|
349
|
+
`ErroSessaoObrigatoria` sem token, antes de fazer a requisição.
|
|
291
350
|
|
|
292
351
|
`eu` devolve o `Usuario` da sessão, ou `None` quando ela não vale mais.
|
|
293
352
|
`eu(token)` usa outro token só naquela chamada. `sair` revoga a sessão na API
|
|
@@ -119,11 +119,7 @@ class ClienteDatamais:
|
|
|
119
119
|
def substituir_dados_fonte(
|
|
120
120
|
self, grupo: str, slug: str, colunas: list[Coluna], linhas: list[Linha]
|
|
121
121
|
) -> None:
|
|
122
|
-
|
|
123
|
-
"colunas": [coluna.para_payload() for coluna in colunas],
|
|
124
|
-
"linhas": linhas,
|
|
125
|
-
}
|
|
126
|
-
self._requisitar("PUT", _rota("/grupos/{}/fontes/{}/dados", grupo, slug), json=payload)
|
|
122
|
+
self._substituir_dados(_rota("/grupos/{}/fontes/{}/dados", grupo, slug), colunas, linhas)
|
|
127
123
|
|
|
128
124
|
def substituir_dados_fonte_de_dataframe(
|
|
129
125
|
self,
|
|
@@ -132,12 +128,24 @@ class ClienteDatamais:
|
|
|
132
128
|
frame: pd.DataFrame,
|
|
133
129
|
colunas: list[Coluna] | None = None,
|
|
134
130
|
) -> None:
|
|
135
|
-
self.substituir_dados_fonte(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
)
|
|
131
|
+
self.substituir_dados_fonte(grupo, slug, *_conteudo_de_dataframe(frame, colunas))
|
|
132
|
+
|
|
133
|
+
def substituir_dados_fonte_independente(
|
|
134
|
+
self, slug: str, colunas: list[Coluna], linhas: list[Linha]
|
|
135
|
+
) -> None:
|
|
136
|
+
self._substituir_dados(_rota("/fontes/independentes/{}/dados", slug), colunas, linhas)
|
|
137
|
+
|
|
138
|
+
def substituir_dados_fonte_independente_de_dataframe(
|
|
139
|
+
self, slug: str, frame: pd.DataFrame, colunas: list[Coluna] | None = None
|
|
140
|
+
) -> None:
|
|
141
|
+
self.substituir_dados_fonte_independente(slug, *_conteudo_de_dataframe(frame, colunas))
|
|
142
|
+
|
|
143
|
+
def _substituir_dados(self, caminho: str, colunas: list[Coluna], linhas: list[Linha]) -> None:
|
|
144
|
+
payload: dict[str, Any] = {
|
|
145
|
+
"colunas": [coluna.para_payload() for coluna in colunas],
|
|
146
|
+
"linhas": linhas,
|
|
147
|
+
}
|
|
148
|
+
self._requisitar("PUT", caminho, json=payload)
|
|
141
149
|
|
|
142
150
|
def criar_fonte(
|
|
143
151
|
self,
|
|
@@ -168,15 +176,11 @@ class ClienteDatamais:
|
|
|
168
176
|
)
|
|
169
177
|
|
|
170
178
|
def obter_relacoes_fonte_independente(self, slug: str) -> list[RelacaoFonte]:
|
|
171
|
-
if not self._token:
|
|
172
|
-
raise ErroSessaoObrigatoria("Obter as relações de uma fonte independente")
|
|
173
179
|
return self._obter_relacoes(_rota("/fontes/independentes/{}/relacoes", slug))
|
|
174
180
|
|
|
175
181
|
def definir_relacoes_fonte_independente(
|
|
176
182
|
self, slug: str, relacoes: list[RelacaoFonte]
|
|
177
183
|
) -> list[RelacaoFonte]:
|
|
178
|
-
if not self._token:
|
|
179
|
-
raise ErroSessaoObrigatoria("Definir as relações de uma fonte independente")
|
|
180
184
|
return self._definir_relacoes(_rota("/fontes/independentes/{}/relacoes", slug), relacoes)
|
|
181
185
|
|
|
182
186
|
def _obter_relacoes(self, caminho: str) -> list[RelacaoFonte]:
|
|
@@ -340,5 +344,12 @@ def _rota(modelo: str, *segmentos: str) -> str:
|
|
|
340
344
|
return modelo.format(*(quote(segmento, safe="") for segmento in segmentos))
|
|
341
345
|
|
|
342
346
|
|
|
347
|
+
def _conteudo_de_dataframe(
|
|
348
|
+
frame: pd.DataFrame, colunas: list[Coluna] | None
|
|
349
|
+
) -> tuple[list[Coluna], list[Linha]]:
|
|
350
|
+
catalogo = colunas if colunas is not None else colunas_de_dataframe(frame)
|
|
351
|
+
return catalogo, linhas_de_dataframe(frame)
|
|
352
|
+
|
|
353
|
+
|
|
343
354
|
def _relacoes_de(body: dict[str, Any]) -> list[RelacaoFonte]:
|
|
344
355
|
return [RelacaoFonte.de_payload(relacao) for relacao in body.get("relacoes") or []]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datamais-api
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.0
|
|
4
4
|
Summary: Cliente Python da API DataMais, feito para bots de carga de dados.
|
|
5
5
|
Author: SECONV-RR
|
|
6
6
|
License-Expression: LicenseRef-Proprietary
|
|
@@ -107,6 +107,65 @@ existir e ter dono — uma chave não é um usuário, então ela nunca pode cria
|
|
|
107
107
|
grupo. Uma fonte que já existe volta como `ErroConflito`; um grupo inexistente
|
|
108
108
|
ou sem dono, como `ErroValidacao` (`422`).
|
|
109
109
|
|
|
110
|
+
## Fontes independentes
|
|
111
|
+
|
|
112
|
+
Uma fonte independente não pertence a um grupo. Ela tem um slug global e pode
|
|
113
|
+
ser anexada a vários grupos, que a leem pelo caminho do grupo. Quem escreve
|
|
114
|
+
nela usa as rotas `/fontes/independentes/{slug}/...`, com uma chave de API que
|
|
115
|
+
tenha `independent:<slug>:manage` ou com uma sessão que tenha
|
|
116
|
+
`datasets:independent`, `dev` ou `admin`.
|
|
117
|
+
|
|
118
|
+
| Método | Rota | Credenciais |
|
|
119
|
+
| --- | --- | --- |
|
|
120
|
+
| `substituir_dados_fonte_independente(slug, colunas, linhas)` | `PUT /fontes/independentes/{slug}/dados` | chave de API ou sessão |
|
|
121
|
+
| `substituir_dados_fonte_independente_de_dataframe(slug, frame, colunas=None)` | `PUT /fontes/independentes/{slug}/dados` | chave de API ou sessão |
|
|
122
|
+
| `obter_relacoes_fonte_independente(slug)` | `GET /fontes/independentes/{slug}/relacoes` | chave de API ou sessão |
|
|
123
|
+
| `definir_relacoes_fonte_independente(slug, relacoes)` | `PUT /fontes/independentes/{slug}/relacoes` | chave de API ou sessão |
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from datamais_api import (
|
|
127
|
+
ClienteDatamais,
|
|
128
|
+
Coluna,
|
|
129
|
+
ColunaRelacao,
|
|
130
|
+
DestinoRelacao,
|
|
131
|
+
RelacaoFonte,
|
|
132
|
+
TipoColuna,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
colunas = [
|
|
136
|
+
Coluna("ibge", "IBGE", escondida=True),
|
|
137
|
+
Coluna("municipio", "Município", filtravel=True),
|
|
138
|
+
Coluna("populacao", "População", TipoColuna.INTEIRO),
|
|
139
|
+
]
|
|
140
|
+
linhas = [{"ibge": "1400100", "municipio": "Boa Vista", "populacao": 413486}]
|
|
141
|
+
relacoes = [
|
|
142
|
+
RelacaoFonte(
|
|
143
|
+
destino=DestinoRelacao(fonte="municipios", independente=True),
|
|
144
|
+
colunas=[ColunaRelacao(origem="ibge", destino="ibge")],
|
|
145
|
+
),
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
with ClienteDatamais() as cliente:
|
|
149
|
+
cliente.substituir_dados_fonte_independente("municipios", colunas, linhas)
|
|
150
|
+
cliente.definir_relacoes_fonte_independente("convenios-estaduais", relacoes)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`substituir_dados_fonte_independente` troca de uma vez o catálogo de colunas e
|
|
154
|
+
as linhas da fonte, com o mesmo corpo de `substituir_dados_fonte`, e a versão
|
|
155
|
+
nova vale para todos os grupos em que a fonte está anexada. A variante
|
|
156
|
+
`_de_dataframe` recebe um DataFrame e infere o catálogo como
|
|
157
|
+
`substituir_dados_fonte_de_dataframe` (veja [pandas](#pandas)).
|
|
158
|
+
|
|
159
|
+
`definir_relacoes_fonte_independente` troca o conjunto inteiro de relações da
|
|
160
|
+
fonte e devolve o que a API gravou; uma lista vazia remove todas. Como a fonte
|
|
161
|
+
não tem grupo, o destino precisa vir com `grupo` explícito ou com
|
|
162
|
+
`independente=True`. As colunas citadas precisam existir nas duas fontes, então
|
|
163
|
+
carregue os dados delas antes de declarar a relação. Os corpos e as respostas
|
|
164
|
+
são os mesmos de `obter_relacoes_fonte` e `definir_relacoes_fonte`.
|
|
165
|
+
|
|
166
|
+
Uma chave sem a permissão da fonte recebe `ErroProibido` (403), e um slug que
|
|
167
|
+
não existe, `ErroNaoEncontrado` (404).
|
|
168
|
+
|
|
110
169
|
## Consultas no servidor
|
|
111
170
|
|
|
112
171
|
`consultar_fonte` filtra, agrupa, agrega, ordena e junta as linhas de uma fonte
|
|
@@ -304,9 +363,9 @@ with ClienteDatamais(token=token_da_sessao) as cliente:
|
|
|
304
363
|
```
|
|
305
364
|
|
|
306
365
|
A autenticação é resolvida a cada requisição: o `token` vai como
|
|
307
|
-
`Authorization: Bearer` e, sem ele, vai o `X-API-Chave`.
|
|
308
|
-
|
|
309
|
-
sem token, antes de fazer a requisição.
|
|
366
|
+
`Authorization: Bearer` e, sem ele, vai o `X-API-Chave`. A única rota que só
|
|
367
|
+
aceita sessão, `acompanhar_dados_fonte_independente`, levanta
|
|
368
|
+
`ErroSessaoObrigatoria` sem token, antes de fazer a requisição.
|
|
310
369
|
|
|
311
370
|
`eu` devolve o `Usuario` da sessão, ou `None` quando ela não vale mais.
|
|
312
371
|
`eu(token)` usa outro token só naquela chamada. `sair` revoga a sessão na API
|
|
@@ -22,7 +22,6 @@ from datamais_api import (
|
|
|
22
22
|
ErroRedirecionamento,
|
|
23
23
|
ErroSegmentoInvalido,
|
|
24
24
|
ErroServicoIndisponivel,
|
|
25
|
-
ErroSessaoObrigatoria,
|
|
26
25
|
ErroValidacao,
|
|
27
26
|
FiltroConsulta,
|
|
28
27
|
GranularidadeConsulta,
|
|
@@ -376,6 +375,38 @@ def test_substituir_dados_fonte_faz_put_do_conteudo_completo() -> None:
|
|
|
376
375
|
}
|
|
377
376
|
|
|
378
377
|
|
|
378
|
+
def test_substituir_dados_fonte_independente_faz_put_com_a_chave() -> None:
|
|
379
|
+
capturadas: list[httpx.Request] = []
|
|
380
|
+
|
|
381
|
+
def manipulador(requisicao: httpx.Request) -> httpx.Response:
|
|
382
|
+
capturadas.append(requisicao)
|
|
383
|
+
return httpx.Response(204)
|
|
384
|
+
|
|
385
|
+
colunas = [
|
|
386
|
+
Coluna("ibge", "IBGE", escondida=True),
|
|
387
|
+
Coluna("municipio", "Município", filtravel=True),
|
|
388
|
+
Coluna("populacao", "População", TipoColuna.INTEIRO),
|
|
389
|
+
]
|
|
390
|
+
linhas = [{"ibge": "1400100", "municipio": "Boa Vista", "populacao": 413486}]
|
|
391
|
+
|
|
392
|
+
with cliente_com(manipulador) as cliente:
|
|
393
|
+
cliente.substituir_dados_fonte_independente("municipios", colunas, linhas)
|
|
394
|
+
|
|
395
|
+
[requisicao] = capturadas
|
|
396
|
+
assert requisicao.method == "PUT"
|
|
397
|
+
assert str(requisicao.url) == f"{URL_BASE}/fontes/independentes/municipios/dados"
|
|
398
|
+
assert requisicao.headers["X-API-Chave"] == CHAVE_API
|
|
399
|
+
assert "Authorization" not in requisicao.headers
|
|
400
|
+
assert json.loads(requisicao.content) == {
|
|
401
|
+
"colunas": [
|
|
402
|
+
{"chave": "ibge", "cabecalho": "IBGE", "tipo": "text", "escondida": True},
|
|
403
|
+
{"chave": "municipio", "cabecalho": "Município", "tipo": "text", "filtravel": True},
|
|
404
|
+
{"chave": "populacao", "cabecalho": "População", "tipo": "int"},
|
|
405
|
+
],
|
|
406
|
+
"linhas": [{"ibge": "1400100", "municipio": "Boa Vista", "populacao": 413486}],
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
|
|
379
410
|
def test_criar_fonte_faz_post_da_entrada_de_catalogo() -> None:
|
|
380
411
|
capturado: dict[str, object] = {}
|
|
381
412
|
|
|
@@ -549,15 +580,68 @@ def test_definir_relacoes_fonte_aceita_lista_vazia() -> None:
|
|
|
549
580
|
assert devolvidas == []
|
|
550
581
|
|
|
551
582
|
|
|
552
|
-
def
|
|
583
|
+
def test_obter_relacoes_fonte_independente_envia_a_chave_e_analisa_o_payload() -> None:
|
|
584
|
+
capturadas: list[httpx.Request] = []
|
|
585
|
+
|
|
553
586
|
def manipulador(requisicao: httpx.Request) -> httpx.Response:
|
|
554
|
-
|
|
587
|
+
capturadas.append(requisicao)
|
|
588
|
+
return httpx.Response(
|
|
589
|
+
200,
|
|
590
|
+
json={
|
|
591
|
+
"relacoes": [
|
|
592
|
+
{
|
|
593
|
+
"destino": {"fonte": "municipios", "independente": True},
|
|
594
|
+
"colunas": [{"origem": "ibge", "destino": "ibge"}],
|
|
595
|
+
"criado_em": "2026-11-04T10:00:00Z",
|
|
596
|
+
},
|
|
597
|
+
],
|
|
598
|
+
},
|
|
599
|
+
)
|
|
555
600
|
|
|
556
601
|
with cliente_com(manipulador) as cliente:
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
602
|
+
relacoes = cliente.obter_relacoes_fonte_independente("tabela-global")
|
|
603
|
+
|
|
604
|
+
[requisicao] = capturadas
|
|
605
|
+
assert requisicao.method == "GET"
|
|
606
|
+
assert str(requisicao.url) == f"{URL_BASE}/fontes/independentes/tabela-global/relacoes"
|
|
607
|
+
assert requisicao.headers["X-API-Chave"] == CHAVE_API
|
|
608
|
+
assert "Authorization" not in requisicao.headers
|
|
609
|
+
assert len(relacoes) == 1
|
|
610
|
+
assert relacoes[0].destino.fonte == "municipios"
|
|
611
|
+
assert relacoes[0].destino.independente is True
|
|
612
|
+
assert [(par.origem, par.destino) for par in relacoes[0].colunas] == [("ibge", "ibge")]
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def test_definir_relacoes_fonte_independente_envia_a_chave_e_o_conjunto_completo() -> None:
|
|
616
|
+
capturadas: list[httpx.Request] = []
|
|
617
|
+
|
|
618
|
+
def manipulador(requisicao: httpx.Request) -> httpx.Response:
|
|
619
|
+
capturadas.append(requisicao)
|
|
620
|
+
return httpx.Response(200, json=json.loads(requisicao.content))
|
|
621
|
+
|
|
622
|
+
relacoes = [
|
|
623
|
+
RelacaoFonte(
|
|
624
|
+
destino=DestinoRelacao(fonte="municipios", independente=True),
|
|
625
|
+
colunas=[ColunaRelacao(origem="ibge", destino="ibge")],
|
|
626
|
+
),
|
|
627
|
+
]
|
|
628
|
+
|
|
629
|
+
with cliente_com(manipulador) as cliente:
|
|
630
|
+
devolvidas = cliente.definir_relacoes_fonte_independente("tabela-global", relacoes)
|
|
631
|
+
|
|
632
|
+
[requisicao] = capturadas
|
|
633
|
+
assert requisicao.method == "PUT"
|
|
634
|
+
assert str(requisicao.url) == f"{URL_BASE}/fontes/independentes/tabela-global/relacoes"
|
|
635
|
+
assert requisicao.headers["X-API-Chave"] == CHAVE_API
|
|
636
|
+
assert json.loads(requisicao.content) == {
|
|
637
|
+
"relacoes": [
|
|
638
|
+
{
|
|
639
|
+
"destino": {"fonte": "municipios", "independente": True},
|
|
640
|
+
"colunas": [{"origem": "ibge", "destino": "ibge"}],
|
|
641
|
+
},
|
|
642
|
+
],
|
|
643
|
+
}
|
|
644
|
+
assert [relacao.destino.fonte for relacao in devolvidas] == ["municipios"]
|
|
561
645
|
|
|
562
646
|
|
|
563
647
|
def test_definir_relacoes_fonte_independente_usa_o_token_da_sessao() -> None:
|
|
@@ -576,6 +660,42 @@ def test_definir_relacoes_fonte_independente_usa_o_token_da_sessao() -> None:
|
|
|
576
660
|
assert capturado["autorizacao"] == "Bearer tok-1"
|
|
577
661
|
|
|
578
662
|
|
|
663
|
+
@pytest.mark.parametrize(
|
|
664
|
+
("status", "tipo_erro"),
|
|
665
|
+
[(403, ErroProibido), (404, ErroNaoEncontrado)],
|
|
666
|
+
)
|
|
667
|
+
@pytest.mark.parametrize(
|
|
668
|
+
"chamada",
|
|
669
|
+
[
|
|
670
|
+
pytest.param(
|
|
671
|
+
lambda c: c.substituir_dados_fonte_independente(
|
|
672
|
+
"tabela-global", [Coluna("uf", "UF")], [{"uf": "RR"}]
|
|
673
|
+
),
|
|
674
|
+
id="substituir_dados_fonte_independente",
|
|
675
|
+
),
|
|
676
|
+
pytest.param(
|
|
677
|
+
lambda c: c.obter_relacoes_fonte_independente("tabela-global"),
|
|
678
|
+
id="obter_relacoes_fonte_independente",
|
|
679
|
+
),
|
|
680
|
+
pytest.param(
|
|
681
|
+
lambda c: c.definir_relacoes_fonte_independente("tabela-global", []),
|
|
682
|
+
id="definir_relacoes_fonte_independente",
|
|
683
|
+
),
|
|
684
|
+
],
|
|
685
|
+
)
|
|
686
|
+
def test_escrita_de_fonte_independente_por_chave_mapeia_recusa_e_ausencia(
|
|
687
|
+
chamada: Callable[[ClienteDatamais], object], status: int, tipo_erro: type[ErroAPI]
|
|
688
|
+
) -> None:
|
|
689
|
+
def manipulador(requisicao: httpx.Request) -> httpx.Response:
|
|
690
|
+
return httpx.Response(status, json={"status": status, "detail": "sem acesso à fonte"})
|
|
691
|
+
|
|
692
|
+
with cliente_com(manipulador) as cliente, pytest.raises(tipo_erro) as exc:
|
|
693
|
+
chamada(cliente)
|
|
694
|
+
|
|
695
|
+
assert exc.value.status == status
|
|
696
|
+
assert exc.value.detalhe == "sem acesso à fonte"
|
|
697
|
+
|
|
698
|
+
|
|
579
699
|
@pytest.mark.parametrize(
|
|
580
700
|
("status", "tipo_erro"),
|
|
581
701
|
[
|
|
@@ -753,6 +873,11 @@ def test_slug_vai_na_rota_como_um_unico_segmento_codificado(slug: str, segmento:
|
|
|
753
873
|
"/grupos/..%2Fg/fontes/a%2Fb/dados",
|
|
754
874
|
id="substituir_dados_fonte",
|
|
755
875
|
),
|
|
876
|
+
pytest.param(
|
|
877
|
+
lambda c: c.substituir_dados_fonte_independente("a/b", [], []),
|
|
878
|
+
"/fontes/independentes/a%2Fb/dados",
|
|
879
|
+
id="substituir_dados_fonte_independente",
|
|
880
|
+
),
|
|
756
881
|
pytest.param(
|
|
757
882
|
lambda c: c.criar_fonte("../g", "a/b", "Programas"),
|
|
758
883
|
"/grupos/..%2Fg/fontes",
|
|
@@ -844,11 +969,14 @@ def test_segmento_vazio_ou_de_ponto_levanta_erro_antes_de_qualquer_requisicao(
|
|
|
844
969
|
cliente.substituir_dados_fonte("geral", segmento, [], [])
|
|
845
970
|
with pytest.raises(ErroSegmentoInvalido) as no_fluxo:
|
|
846
971
|
cliente.acompanhar_dados_painel("geral", segmento)
|
|
972
|
+
with pytest.raises(ErroSegmentoInvalido) as no_independente:
|
|
973
|
+
cliente.substituir_dados_fonte_independente(segmento, [], [])
|
|
847
974
|
|
|
848
975
|
assert capturadas == []
|
|
849
976
|
assert no_grupo.value.segmento == segmento
|
|
850
977
|
assert no_slug.value.segmento == segmento
|
|
851
978
|
assert no_fluxo.value.segmento == segmento
|
|
979
|
+
assert no_independente.value.segmento == segmento
|
|
852
980
|
assert str(no_grupo.value) == (
|
|
853
981
|
f"segmento de rota inválido: {segmento!r}; "
|
|
854
982
|
"grupo e slug não podem ser vazios nem iguais a '.' ou '..'"
|
|
@@ -128,3 +128,30 @@ def test_substituir_dados_fonte_de_dataframe_respeita_colunas_explicitas() -> No
|
|
|
128
128
|
],
|
|
129
129
|
"linhas": [{"valor": 10.0}],
|
|
130
130
|
}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_substituir_dados_fonte_independente_de_dataframe_envia_para_o_slug_global() -> None:
|
|
134
|
+
capturadas: list[httpx.Request] = []
|
|
135
|
+
|
|
136
|
+
def manipulador(requisicao: httpx.Request) -> httpx.Response:
|
|
137
|
+
capturadas.append(requisicao)
|
|
138
|
+
return httpx.Response(204)
|
|
139
|
+
|
|
140
|
+
frame = pd.DataFrame({"ibge": ["1400100"], "populacao": [413486]})
|
|
141
|
+
cliente = ClienteDatamais(
|
|
142
|
+
"https://api.example.com", "dmk_secret", transport=httpx.MockTransport(manipulador)
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
with cliente:
|
|
146
|
+
cliente.substituir_dados_fonte_independente_de_dataframe("municipios", frame)
|
|
147
|
+
|
|
148
|
+
[requisicao] = capturadas
|
|
149
|
+
assert requisicao.method == "PUT"
|
|
150
|
+
assert str(requisicao.url) == "https://api.example.com/fontes/independentes/municipios/dados"
|
|
151
|
+
assert json.loads(requisicao.content) == {
|
|
152
|
+
"colunas": [
|
|
153
|
+
{"chave": "ibge", "cabecalho": "ibge", "tipo": "text"},
|
|
154
|
+
{"chave": "populacao", "cabecalho": "populacao", "tipo": "int"},
|
|
155
|
+
],
|
|
156
|
+
"linhas": [{"ibge": "1400100", "populacao": 413486}],
|
|
157
|
+
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|