lbxtoolkit 2.2.5__tar.gz → 2.2.7__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.
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/PKG-INFO +4 -2
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/README.md +3 -1
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/api_rest.py +21 -6
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/lbx_logger.py +13 -13
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/postgresql.py +9 -3
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/service.py +2 -1
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/pyproject.toml +1 -1
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/__init__.py +0 -0
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/auth_entra_id.py +0 -0
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/config_manager.py +0 -0
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/misc.py +0 -0
- {lbxtoolkit-2.2.5 → lbxtoolkit-2.2.7}/lbxtoolkit/service_windows.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: lbxtoolkit
|
|
3
|
-
Version: 2.2.
|
|
3
|
+
Version: 2.2.7
|
|
4
4
|
Summary:
|
|
5
5
|
Author: Cristiano P. Ferrari
|
|
6
6
|
Author-email: cristiano.ferrari@lbx.com.br
|
|
@@ -508,7 +508,9 @@ Recursos de interação com o banco de dados relacional PostgreSQL
|
|
|
508
508
|
dados = postgreSQL.csv_df(arquivo_csv, CsvDelim=',') # usando vírgula como separador. se omisso, assume ";'
|
|
509
509
|
```
|
|
510
510
|
|
|
511
|
-
|
|
511
|
+
Qualquer argumento da função `read_csv()` pode ser repassado na chamada do método.
|
|
512
|
+
|
|
513
|
+
3. O método `postgreSQl.db_insert_df()` insere dados a partir de um Dataframe (pandas) em uma tabela do banco com estrutura de colunas equivalente.
|
|
512
514
|
|
|
513
515
|
A assinatura da função é `postgreSQL.db_insert_df([conexao], [dataframe_origem], [tabela_destino], Schema=None, Colunas=None, OnConflict=None)`
|
|
514
516
|
|
|
@@ -486,7 +486,9 @@ Recursos de interação com o banco de dados relacional PostgreSQL
|
|
|
486
486
|
dados = postgreSQL.csv_df(arquivo_csv, CsvDelim=',') # usando vírgula como separador. se omisso, assume ";'
|
|
487
487
|
```
|
|
488
488
|
|
|
489
|
-
|
|
489
|
+
Qualquer argumento da função `read_csv()` pode ser repassado na chamada do método.
|
|
490
|
+
|
|
491
|
+
3. O método `postgreSQl.db_insert_df()` insere dados a partir de um Dataframe (pandas) em uma tabela do banco com estrutura de colunas equivalente.
|
|
490
492
|
|
|
491
493
|
A assinatura da função é `postgreSQL.db_insert_df([conexao], [dataframe_origem], [tabela_destino], Schema=None, Colunas=None, OnConflict=None)`
|
|
492
494
|
|
|
@@ -84,6 +84,15 @@ Quando se usa o verbo `get` e se espera o retorno de algum dado, use o método `
|
|
|
84
84
|
Para uso em APIs com autenticação JWT (JSON Web Token), OAuth, Bearer Token Authentication, a construção é a mesma indicada acima, bastando-se usar `.auth_bearer()` ao invés de _.auth_basic()_, e ajustar o dicionário `credenciais` informado no instanciamento da classe, que deve ser estruturado conforme o padrão fornecido peo mantendor da API e será enviado como payload ao endpoint (`json=credenciais`).
|
|
85
85
|
|
|
86
86
|
"""
|
|
87
|
+
class CustomError(Exception):
|
|
88
|
+
"""
|
|
89
|
+
Sob uma mensagem de erro customizada, exibindo a mensagem recebida como parametro.
|
|
90
|
+
"""
|
|
91
|
+
def __init__(self, mensagem):
|
|
92
|
+
self.message = mensagem
|
|
93
|
+
super().__init__(self.message)
|
|
94
|
+
|
|
95
|
+
|
|
87
96
|
def __init__(self, url, credenciais, cadencia=3, timeout=6, logger=None, headers={"Content-Type": "application/json"}, verify=True):
|
|
88
97
|
self.logger = logger if not logger is None else lbx_logger(None, logging.DEBUG, '%(levelname)s: %(message)s') # se não fornecer o logger, vai tudo para o console
|
|
89
98
|
|
|
@@ -135,7 +144,8 @@ Para uso em APIs com autenticação JWT (JSON Web Token), OAuth, Bearer Token Au
|
|
|
135
144
|
#print(f'Retorno: {Auth.text}')
|
|
136
145
|
return self.Sessao
|
|
137
146
|
except Exception as Err:
|
|
138
|
-
self.logger.critico(f"Falha ao autenticar API: {Err}. URL: {self.Url}"
|
|
147
|
+
self.logger.critico(f"Falha ao autenticar API: {Err}. URL: {self.Url}")
|
|
148
|
+
return Err
|
|
139
149
|
#
|
|
140
150
|
#
|
|
141
151
|
def auth_bearer(self): # Autentica e abre sessão na API
|
|
@@ -149,9 +159,11 @@ Para uso em APIs com autenticação JWT (JSON Web Token), OAuth, Bearer Token Au
|
|
|
149
159
|
self.Sessao.token = Token.text
|
|
150
160
|
return self.Sessao
|
|
151
161
|
else:
|
|
152
|
-
self.logger.critico(f"Erro ao autenticar API: {Token.status_code} - {Token.text}"
|
|
162
|
+
self.logger.critico(f"Erro ao autenticar API: {Token.status_code} - {Token.text}")
|
|
163
|
+
raise Exception
|
|
153
164
|
except Exception as Err:
|
|
154
|
-
self.logger.critico(f"Falha ao autenticar API: {Err}. URL: {self.Url}"
|
|
165
|
+
self.logger.critico(f"Falha ao autenticar API: {Err}. URL: {self.Url}")
|
|
166
|
+
return Err
|
|
155
167
|
#
|
|
156
168
|
#
|
|
157
169
|
def endpoint_json(self, endpoint, metodo, payload=None): # Interage com End Point
|
|
@@ -170,14 +182,17 @@ Para uso em APIs com autenticação JWT (JSON Web Token), OAuth, Bearer Token Au
|
|
|
170
182
|
try:
|
|
171
183
|
self.RetEndPoint = eval(ChamadaApi)
|
|
172
184
|
if self.RetEndPoint.status_code >= 500:
|
|
173
|
-
self.logger.critico(f'Erro {self.RetEndPoint.status_code} na chamada do endpoint: {Err}\nEndpoint: {self.EndPoint}\nResposta: {self.RetEndPoint.text}'
|
|
185
|
+
self.logger.critico(f'Erro {self.RetEndPoint.status_code} na chamada do endpoint: {Err}\nEndpoint: {self.EndPoint}\nResposta: {self.RetEndPoint.text}')
|
|
186
|
+
raise Exception
|
|
174
187
|
self.RetEndPoint.Espera = self.Espera ## adiona o tempo de espera ao retorno da API
|
|
175
188
|
self.RetEndPoint.Intervalo = self.Intervalo ## adiciona o intervalo entre chamada ao retorno da API
|
|
176
189
|
return self.RetEndPoint
|
|
177
190
|
except requests.exceptions.ReadTimeout as Err:
|
|
178
|
-
self.logger.critico(f'Excedido tempo limite {self.Timeout} para retorno do endpoint: {Err}\nEndpoint: {self.EndPoint}'
|
|
191
|
+
self.logger.critico(f'Excedido tempo limite {self.Timeout} para retorno do endpoint: {Err}\nEndpoint: {self.EndPoint}')
|
|
192
|
+
return Err
|
|
179
193
|
except Exception as Err:
|
|
180
|
-
self.logger.critico(f'Falha na chamada do endpoint: {Err}\nEndpoint: {self.EndPoint}\nCodigo retorno: {self.RetEndPoint.status_code}\nResposta:{self.RetEndPoint.text}'
|
|
194
|
+
self.logger.critico(f'Falha na chamada do endpoint: {Err}\nEndpoint: {self.EndPoint}\nCodigo retorno: {self.RetEndPoint.status_code}\nResposta:{self.RetEndPoint.text}')
|
|
195
|
+
return Err
|
|
181
196
|
#
|
|
182
197
|
#
|
|
183
198
|
def trata_erro_sienge(CodRet, Retorno):
|
|
@@ -408,20 +408,20 @@ class SafeLogger: ## intercepta as entradas de log para parar o daemon/watcher q
|
|
|
408
408
|
if callable(original_attr):
|
|
409
409
|
def wrapper(*args, **kwargs):
|
|
410
410
|
#if 'exit' in kwargs and (Args.d or not (Args.d or Args.f)): #não tentar para o daemon se execucção interativa
|
|
411
|
-
if 'exit' in kwargs and self.daemon: #não tentar para o daemon se execucção interativa
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
411
|
+
if 'exit' in kwargs and isinstance(kwargs['exit'], int) and self.daemon: #não tentar para o daemon se execucção interativa
|
|
412
|
+
if not self.daemon.exit: # Verifica se o daemon já foi interrompido
|
|
413
|
+
evento = 'CRASH' if kwargs['exit'] != 0 else 'STOP'
|
|
414
|
+
msg1 = 'um erro ocorreu. Interceptando log para interromper daemon/watcher...' if kwargs['exit'] != 0 else \
|
|
415
|
+
'Interrompendo daemon/watcher...'
|
|
416
|
+
msg2 = 'daemon/watcher interrompido... exibindo o erro interceptado: ' if kwargs['exit'] != 0 else \
|
|
417
|
+
'daemon/watcher interrompido!'
|
|
418
|
+
|
|
419
|
+
self.log.aviso(msg1)
|
|
420
|
+
self.daemon.stop(evento)
|
|
421
|
+
self.log.aviso(msg2)
|
|
422
|
+
|
|
420
423
|
result = original_attr(*args, **kwargs)
|
|
421
|
-
|
|
422
|
-
# log.aviso('Saindo...')
|
|
423
|
-
# os._exit(kwargs['exit'])
|
|
424
|
-
return result
|
|
424
|
+
return result
|
|
425
425
|
return wrapper
|
|
426
426
|
else:
|
|
427
427
|
return original_attr
|
|
@@ -37,7 +37,10 @@ arquivo_csv = Path('./diretorio/arquivo_exemplo.csv')
|
|
|
37
37
|
dados = postgreSQL.csv_df(arquivo_csv, CsvDelim=',') # usando vírgula como separador. se omisso, assume ";'
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
Qualquer argumento da função read_csv do Pandas é aceito na chamada do método.
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
3. O método `postgreSQl.db_insert_df()` insere dados a partir de um Dataframe (pandas) em uma tabela do banco com estrutura de colunas equivalente.
|
|
41
44
|
|
|
42
45
|
A assinatura da função é `postgreSQL.db_insert_df([conexao], [dataframe_origem], [tabela_destino], Schema=None, Colunas=None, OnConflict=None)`
|
|
43
46
|
|
|
@@ -150,9 +153,12 @@ conexao.close()
|
|
|
150
153
|
raise
|
|
151
154
|
#
|
|
152
155
|
#
|
|
153
|
-
def csv_df(self, CsvPath, CsvDelim=';'): # Le arquivo CSV e gera Dataframe do Pandas
|
|
156
|
+
def csv_df(self, CsvPath, CsvDelim=';', **kwargs): # Le arquivo CSV e gera Dataframe do Pandas
|
|
157
|
+
"""
|
|
158
|
+
Os parametros de read_csv() do Pandas podem ser passados opcionalmente para a função para ajustar a importação
|
|
159
|
+
"""
|
|
154
160
|
try:
|
|
155
|
-
DataFrame = pd.read_csv(CsvPath, delimiter=CsvDelim) # Verifique se o delimitador é ';'
|
|
161
|
+
DataFrame = pd.read_csv(CsvPath, delimiter=CsvDelim, **kwargs) # Verifique se o delimitador é ';'
|
|
156
162
|
DataFrame.replace({np.nan: None}, inplace=True) ## troca 'NaN' por None (null no postgresql)
|
|
157
163
|
return DataFrame
|
|
158
164
|
except Exception as Err:
|
|
@@ -171,7 +171,8 @@ class ServicerConfig(Servicer):
|
|
|
171
171
|
self.IP = socket.gethostbyname(socket.gethostname())
|
|
172
172
|
self.Host = socket.gethostname()
|
|
173
173
|
self.Usuario = os.getlogin() if self.OS == 'Windows' else os.path.expanduser('~').split(r'/')[1]
|
|
174
|
-
self.Me = os.path.abspath(__file__)
|
|
174
|
+
#self.Me = os.path.abspath(__file__) ## estava retornando o service.py do lbxtoolkit ao invés de retornar o script que está em execução.
|
|
175
|
+
self.Me = os.path.abspath(sys.argv[0])
|
|
175
176
|
self.PIDDir = Path('.') if not piddir else piddir
|
|
176
177
|
self.PIDFile = Path(self.PIDDir,str(self.PID))
|
|
177
178
|
self.exit = False
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|