csc-cia-stne 0.0.43__py3-none-any.whl
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.
- csc_cia_stne/__init__.py +89 -0
- csc_cia_stne/bc_correios.py +529 -0
- csc_cia_stne/bc_sta.py +416 -0
- csc_cia_stne/email.py +239 -0
- csc_cia_stne/gcp_bigquery.py +224 -0
- csc_cia_stne/google_drive.py +268 -0
- csc_cia_stne/karavela.py +135 -0
- csc_cia_stne/logger_json.py +92 -0
- csc_cia_stne/logger_rich.py +249 -0
- csc_cia_stne/provio.py +103 -0
- csc_cia_stne/servicenow.py +689 -0
- csc_cia_stne/slack.py +227 -0
- csc_cia_stne/stne_admin.py +597 -0
- csc_cia_stne/utilitarios/__init__.py +9 -0
- csc_cia_stne/utilitarios/functions/__init__.py +14 -0
- csc_cia_stne/utilitarios/functions/func_b64.py +50 -0
- csc_cia_stne/utilitarios/functions/func_converters.py +18 -0
- csc_cia_stne/utilitarios/functions/func_recriar_pastas.py +29 -0
- csc_cia_stne/utilitarios/functions/func_settings.py +66 -0
- csc_cia_stne/utilitarios/functions/func_titulo.py +141 -0
- csc_cia_stne/utilitarios/validations/GcpBigQueryValidator.py +133 -0
- csc_cia_stne/utilitarios/validations/GoogleDriveValidator.py +144 -0
- csc_cia_stne/utilitarios/validations/ServiceNowValidator.py +403 -0
- csc_cia_stne/utilitarios/validations/__init__.py +3 -0
- csc_cia_stne-0.0.43.dist-info/LICENCE +21 -0
- csc_cia_stne-0.0.43.dist-info/METADATA +33 -0
- csc_cia_stne-0.0.43.dist-info/RECORD +29 -0
- csc_cia_stne-0.0.43.dist-info/WHEEL +5 -0
- csc_cia_stne-0.0.43.dist-info/top_level.txt +1 -0
@@ -0,0 +1,224 @@
|
|
1
|
+
from google.cloud import bigquery
|
2
|
+
from google.oauth2 import service_account
|
3
|
+
from pydantic import ValidationError
|
4
|
+
from .utilitarios.validations.GcpBigQueryValidator import tryQueryValidator, InitParamsValidator, tryInsertListValidator
|
5
|
+
|
6
|
+
class BigQuery():
|
7
|
+
|
8
|
+
|
9
|
+
def __init__(self, id_project: str, creds_dict: dict = None, creds_file: str = "", limit: int = 3):
|
10
|
+
|
11
|
+
"""
|
12
|
+
Inicializa a classe BigQuery.
|
13
|
+
Parâmetros:
|
14
|
+
limit (int): O limite de resultados a serem retornados. O valor padrão é 3.
|
15
|
+
client (bigquery.Client): O cliente BigQuery a ser utilizado.
|
16
|
+
"""
|
17
|
+
|
18
|
+
self.limit = limit
|
19
|
+
self.id_project = id_project
|
20
|
+
self.creds_dict = creds_dict
|
21
|
+
self.creds_file = creds_file
|
22
|
+
self.client = self.create_client()
|
23
|
+
|
24
|
+
try:
|
25
|
+
|
26
|
+
InitParamsValidator(limit=limit, id_project=id_project, creds_dict=creds_dict, creds_file=creds_file)
|
27
|
+
|
28
|
+
except ValidationError as e:
|
29
|
+
|
30
|
+
raise ValueError("Erro na validação dos dados de input da inicialização da instância:", e.errors())
|
31
|
+
|
32
|
+
|
33
|
+
def create_client(self) -> bigquery.Client:
|
34
|
+
"""
|
35
|
+
Cria um cliente BigQuery com base nas credenciais fornecidas.
|
36
|
+
Parâmetros:
|
37
|
+
- creds_dict (dict): Dicionário contendo as informações das credenciais. Opcional se creds_file for fornecido.
|
38
|
+
- creds_file (str): Caminho do arquivo de credenciais. Opcional se creds_dict for fornecido.
|
39
|
+
- id_project (str): ID do projeto BigQuery.
|
40
|
+
Retorna:
|
41
|
+
- client (bigquery.Client): Cliente BigQuery criado com base nas credenciais fornecidas.
|
42
|
+
Exceções:
|
43
|
+
- Retorna um dicionário com as seguintes chaves em caso de erro:
|
44
|
+
- 'status' (bool): False
|
45
|
+
- 'error' (str): Mensagem de erro
|
46
|
+
- 'details' (str): Detalhes do erro
|
47
|
+
"""
|
48
|
+
|
49
|
+
try:
|
50
|
+
|
51
|
+
if(self.creds_dict is not None):
|
52
|
+
|
53
|
+
credentials = service_account.Credentials.from_service_account_info(
|
54
|
+
self.creds_dict,
|
55
|
+
scopes=["https://www.googleapis.com/auth/cloud-platform"],
|
56
|
+
)
|
57
|
+
|
58
|
+
client = bigquery.Client(credentials=credentials, project=self.id_project)
|
59
|
+
|
60
|
+
elif(str(self.creds_file) > 0):
|
61
|
+
|
62
|
+
credentials = service_account.Credentials.from_service_account_file(
|
63
|
+
self.creds_file,
|
64
|
+
scopes=["https://www.googleapis.com/auth/cloud-platform"],
|
65
|
+
)
|
66
|
+
|
67
|
+
else:
|
68
|
+
|
69
|
+
return {
|
70
|
+
'status':False,
|
71
|
+
'error':"Credenciais não fornecidas"
|
72
|
+
}
|
73
|
+
|
74
|
+
return client
|
75
|
+
|
76
|
+
except Exception as e:
|
77
|
+
|
78
|
+
return {
|
79
|
+
'status':False,
|
80
|
+
'error':'Problema ao tentar gerar o client do big query',
|
81
|
+
'details':str(e)
|
82
|
+
}
|
83
|
+
|
84
|
+
|
85
|
+
def try_query(self, query_to_execute: str, organize: bool = False, use_legacy: bool = False, use_cache: bool = False, query_parameters: list = []) -> dict:
|
86
|
+
|
87
|
+
"""
|
88
|
+
Executa uma consulta no BigQuery e retorna o resultado.
|
89
|
+
Args:
|
90
|
+
query_to_execute (str): A consulta a ser executada.
|
91
|
+
organize (bool, optional): Indica se o resultado deve ser organizado em um formato específico.
|
92
|
+
O padrão é True.
|
93
|
+
Returns:
|
94
|
+
dict: Um dicionário contendo o status da consulta e o resultado, se houver.
|
95
|
+
Exemplo:
|
96
|
+
{
|
97
|
+
'status': True,
|
98
|
+
'resultado': result_query
|
99
|
+
Se ocorrer um erro durante a execução da consulta, o dicionário de retorno terá o seguinte formato:
|
100
|
+
{
|
101
|
+
'status': False,
|
102
|
+
"""
|
103
|
+
|
104
|
+
try:
|
105
|
+
|
106
|
+
tryQueryValidator(query_to_execute=query_to_execute, organize=organize, use_legacy=use_legacy, use_cache=use_cache, query_parameters=query_parameters)
|
107
|
+
|
108
|
+
except ValidationError as e:
|
109
|
+
|
110
|
+
raise ValueError("Erro na validação dos dados de input da função para tentar executar a query:", e.errors())
|
111
|
+
|
112
|
+
error = ""
|
113
|
+
|
114
|
+
job_config = bigquery.QueryJobConfig(
|
115
|
+
priority=bigquery.QueryPriority.INTERACTIVE,
|
116
|
+
use_legacy_sql=use_legacy,
|
117
|
+
use_query_cache=use_cache,
|
118
|
+
query_parameters=[
|
119
|
+
bigquery.ScalarQueryParameter(param["name"], param["type"], param["value"]) for param in query_parameters
|
120
|
+
],
|
121
|
+
)
|
122
|
+
|
123
|
+
for try_out in range(self.limit):
|
124
|
+
|
125
|
+
try:
|
126
|
+
|
127
|
+
result_query = self.client.query(query_to_execute,job_config=job_config).result()
|
128
|
+
|
129
|
+
error = False
|
130
|
+
|
131
|
+
if organize:
|
132
|
+
|
133
|
+
result_rows = [dict(row) for row in result_query]
|
134
|
+
|
135
|
+
result_query = result_rows
|
136
|
+
|
137
|
+
break
|
138
|
+
|
139
|
+
except Exception as e:
|
140
|
+
|
141
|
+
error = e
|
142
|
+
|
143
|
+
if not error:
|
144
|
+
|
145
|
+
return {
|
146
|
+
'status':True,
|
147
|
+
'resultado':result_query
|
148
|
+
}
|
149
|
+
|
150
|
+
else:
|
151
|
+
|
152
|
+
return {
|
153
|
+
'status':False,
|
154
|
+
'error': str(error)
|
155
|
+
}
|
156
|
+
|
157
|
+
|
158
|
+
def insert_list(self, table: str, list_to_insert: list = [], insert_limit: int = 10000) -> dict:
|
159
|
+
|
160
|
+
"""
|
161
|
+
Insere uma lista de dicionários em uma tabela do BigQuery.
|
162
|
+
Args:
|
163
|
+
client (bigquery.Client): Cliente do BigQuery.
|
164
|
+
table (str): Nome da tabela onde os dados serão inseridos.
|
165
|
+
list_to_insert (dict, optional): Lista de dicionários a serem inseridos. O padrão é [].
|
166
|
+
limit_trys (int, optional): Número máximo de tentativas de inserção. O padrão é 3.
|
167
|
+
Returns:
|
168
|
+
dict: Dicionário contendo o status da inserção e informações adicionais.
|
169
|
+
- Se a inserção for bem-sucedida:
|
170
|
+
{'status': True, 'inserted': inserted}
|
171
|
+
- Se ocorrer um erro durante a inserção:
|
172
|
+
{'status': False, 'error': error, 'last_try': list_to_insert, 'inserted': inserted}
|
173
|
+
"""
|
174
|
+
|
175
|
+
try:
|
176
|
+
|
177
|
+
tryInsertListValidator(table=table, list_to_insert=list_to_insert, insert_limit=insert_limit)
|
178
|
+
|
179
|
+
except ValidationError as e:
|
180
|
+
|
181
|
+
raise ValueError("Erro na validação dos dados de input da função para tentar inserir dados em uma tabela:", e.errors())
|
182
|
+
|
183
|
+
table_ref = self.client.get_table(table)
|
184
|
+
|
185
|
+
error = ""
|
186
|
+
|
187
|
+
inserted = []
|
188
|
+
|
189
|
+
for data in range(0, len(list_to_insert), insert_limit):
|
190
|
+
|
191
|
+
# listagem que será inserida no big query
|
192
|
+
list_to_insert = list_to_insert[data:data+10000]
|
193
|
+
|
194
|
+
for try_out in range(self.limit):
|
195
|
+
|
196
|
+
try:
|
197
|
+
|
198
|
+
self.client.insert_rows(table_ref, list_to_insert)
|
199
|
+
|
200
|
+
error = False
|
201
|
+
|
202
|
+
except Exception as e:
|
203
|
+
|
204
|
+
error = e
|
205
|
+
|
206
|
+
if not error:
|
207
|
+
|
208
|
+
inserted.extend(list_to_insert)
|
209
|
+
|
210
|
+
continue
|
211
|
+
|
212
|
+
else:
|
213
|
+
|
214
|
+
return{
|
215
|
+
'status':False,
|
216
|
+
'error':str(error),
|
217
|
+
'last_try':list_to_insert,
|
218
|
+
'inserted':inserted
|
219
|
+
}
|
220
|
+
|
221
|
+
return {
|
222
|
+
'status':True,
|
223
|
+
'inserted':inserted
|
224
|
+
}
|
@@ -0,0 +1,268 @@
|
|
1
|
+
import os, logging
|
2
|
+
from googleapiclient.discovery import build
|
3
|
+
from googleapiclient.http import MediaFileUpload
|
4
|
+
from googleapiclient.errors import HttpError
|
5
|
+
from io import BytesIO
|
6
|
+
from google.oauth2 import service_account
|
7
|
+
from .utilitarios.validations.GoogleDriveValidator import InitParamsValidator, CreateFolderValidator, ListFolderValidator, UploadValidator
|
8
|
+
from pydantic import ValidationError
|
9
|
+
|
10
|
+
|
11
|
+
class GoogleDrive():
|
12
|
+
|
13
|
+
"""
|
14
|
+
Classe responsável por gerenciar operações no Google Drive, como upload de arquivos, criação de pastas
|
15
|
+
e listagem de conteúdo. Utiliza a API do Google Drive para realizar essas operações.
|
16
|
+
|
17
|
+
Args:
|
18
|
+
key (str): Chave de autenticação para acessar a API do Google Drive.
|
19
|
+
"""
|
20
|
+
_instance = None # Atributo de classe para armazenar a única instância.
|
21
|
+
|
22
|
+
def __new__(cls, *args, **kwargs):
|
23
|
+
# Verifica se já existe uma instância da classe.
|
24
|
+
if cls._instance is None:
|
25
|
+
# Cria e armazena a instância na primeira chamada.
|
26
|
+
cls._instance = super().__new__(cls)
|
27
|
+
return cls._instance
|
28
|
+
|
29
|
+
def __init__(self, token : dict, with_subject : str, scopes : list = ["https://www.googleapis.com/auth/drive"], version : str = "v3"):
|
30
|
+
"""
|
31
|
+
Inicializa uma instância da classe GoogleDrive.
|
32
|
+
Parâmetros:
|
33
|
+
- key (str): A chave para acessar o segredo necessário para autenticação.
|
34
|
+
- with_subject (str): O assunto para o qual a autenticação será realizada.
|
35
|
+
- scopes (list): Uma lista de escopos de permissão para acesso ao Google Drive. O valor padrão é ["https://www.googleapis.com/auth/drive"].
|
36
|
+
- version (str): A versão da API do Google Drive a ser utilizada. O valor padrão é "v3".
|
37
|
+
Raises:
|
38
|
+
- ValueError: Se ocorrer um erro na validação dos dados de input da inicialização da instância.
|
39
|
+
Exemplo de uso:
|
40
|
+
```
|
41
|
+
google_drive = GoogleDrive(key="chave_secreta", with_subject="assunto", scopes=["https://www.googleapis.com/auth/drive"], version="v3")
|
42
|
+
```
|
43
|
+
"""
|
44
|
+
|
45
|
+
try:
|
46
|
+
InitParamsValidator(token=token, with_subject=with_subject, scopes=scopes, version=version)
|
47
|
+
except ValidationError as e:
|
48
|
+
raise ValueError("Erro na validação dos dados de input da inicialização da instância:", e.errors())
|
49
|
+
self.__token = token
|
50
|
+
self.version = version
|
51
|
+
self.scopes = scopes
|
52
|
+
self.with_subject = with_subject
|
53
|
+
self.page_size = 1000
|
54
|
+
self.service = self.__create_service()
|
55
|
+
|
56
|
+
|
57
|
+
def __create_service(self):
|
58
|
+
"""
|
59
|
+
Cria um serviço do Google Drive.
|
60
|
+
Returns:
|
61
|
+
cred: Objeto de credenciais do Google Drive.
|
62
|
+
False: Caso ocorra algum erro ao criar o serviço.
|
63
|
+
Raises:
|
64
|
+
Exception: Caso ocorra algum erro ao criar o serviço do Google Drive.
|
65
|
+
Exemplo de uso:
|
66
|
+
service = create_service()
|
67
|
+
if service:
|
68
|
+
# Fazer algo com o serviço do Google Drive
|
69
|
+
else:
|
70
|
+
# Tratar o erro de criação do serviço
|
71
|
+
"""
|
72
|
+
|
73
|
+
try:
|
74
|
+
auth = self.__autentica(self.with_subject)
|
75
|
+
service = build(f"drive", f"{self.version}", credentials=auth)
|
76
|
+
logging.info(f"Serviço do Google drive criado")
|
77
|
+
return service
|
78
|
+
except Exception as e:
|
79
|
+
logging.info(f"Erro ao criar o serviço do Google drive: Error: {e}")
|
80
|
+
return False
|
81
|
+
|
82
|
+
|
83
|
+
def __autentica(self, with_subject : str):
|
84
|
+
"""
|
85
|
+
Autentica o usuário com as credenciais fornecidas e retorna as credenciais delegadas para o assunto especificado.
|
86
|
+
Args:
|
87
|
+
with_subject (str): O assunto para o qual as credenciais serão delegadas.
|
88
|
+
Returns:
|
89
|
+
google.auth.credentials.Credentials: As credenciais delegadas para o assunto especificado.
|
90
|
+
Raises:
|
91
|
+
Exception: Se ocorrer um erro durante a autenticação.
|
92
|
+
Example:
|
93
|
+
# Autenticar com o assunto "user@example.com"
|
94
|
+
credentials = self.__autentica("user@example.com")
|
95
|
+
"""
|
96
|
+
|
97
|
+
|
98
|
+
try:
|
99
|
+
credentials = service_account.Credentials.from_service_account_info(self.__token, scopes=self.scopes)
|
100
|
+
delegated_credencial = credentials.with_subject(with_subject)
|
101
|
+
return delegated_credencial
|
102
|
+
|
103
|
+
except Exception as e:
|
104
|
+
logging.debug(f"Erro ao tentar autenticar. Verifique o erro: {e}")
|
105
|
+
return False
|
106
|
+
|
107
|
+
|
108
|
+
def upload(self, folder_id: str, name: str, file_path: str, mimetype: str):
|
109
|
+
"""
|
110
|
+
Faz o upload de um arquivo para o Google Drive em uma pasta especificada.
|
111
|
+
|
112
|
+
Args:
|
113
|
+
folder_id (str): ID da pasta no Google Drive onde o arquivo será armazenado.
|
114
|
+
name (str): Nome do arquivo que será carregado.
|
115
|
+
file_path (str): Caminho completo do arquivo no sistema local.
|
116
|
+
mimetype (str): Tipo MIME do arquivo a ser carregado.
|
117
|
+
exemplos: text/plain
|
118
|
+
text/html
|
119
|
+
image/jpeg
|
120
|
+
image/png
|
121
|
+
audio/mpeg
|
122
|
+
audio/ogg
|
123
|
+
audio/*
|
124
|
+
video/mp4
|
125
|
+
application/octet-stream
|
126
|
+
|
127
|
+
Returns:
|
128
|
+
dict: Informações sobre o arquivo carregado, incluindo o ID do arquivo.
|
129
|
+
None: Caso o caminho do arquivo não seja encontrado.
|
130
|
+
"""
|
131
|
+
try:
|
132
|
+
UploadValidator(folder_id=folder_id, name=name, file_path=file_path, mimetype=mimetype)
|
133
|
+
except ValidationError as e:
|
134
|
+
raise ValueError("Erro na validação dos dados para realizar o upload do arquivo", e.errors())
|
135
|
+
|
136
|
+
|
137
|
+
|
138
|
+
file_metadata = {"name": name, "parents": [folder_id]}
|
139
|
+
if not os.path.exists(file_path):
|
140
|
+
logging.debug(f"Pasta {file_path} não encontrada")
|
141
|
+
return {"success" : False, "result" : None, "error" : "Diretório ou arquivo não encontrado"}
|
142
|
+
|
143
|
+
try:
|
144
|
+
logging.debug(f"Realizando o upload do arquivo")
|
145
|
+
media = MediaFileUpload(file_path, mimetype=mimetype, resumable=True)
|
146
|
+
file = (
|
147
|
+
self.service.files()
|
148
|
+
.create(body=file_metadata, media_body=media, fields="id", supportsAllDrives=True)
|
149
|
+
.execute()
|
150
|
+
)
|
151
|
+
|
152
|
+
logging.debug(f"Upload realizado com sucesso")
|
153
|
+
return {"success" : True, "result" : file}
|
154
|
+
except Exception as e:
|
155
|
+
logging.debug(f"Erro ao realizar o upload do arquivo {name} no google drive. Erro: {e}")
|
156
|
+
return {"success" : False, "result" : None, "error" : str(e)}
|
157
|
+
|
158
|
+
|
159
|
+
def create_folder(self, name: str, parent_folder_id: str):
|
160
|
+
"""
|
161
|
+
Cria uma pasta no Google Drive dentro de uma pasta existente.
|
162
|
+
|
163
|
+
Args:
|
164
|
+
name (str): Nome da pasta a ser criada.
|
165
|
+
parent_folder_id (int): ID da pasta pai onde a nova pasta será criada.
|
166
|
+
|
167
|
+
Returns:
|
168
|
+
str: ID da pasta criada.
|
169
|
+
"""
|
170
|
+
try:
|
171
|
+
CreateFolderValidator(name=name, parent_folder_id=parent_folder_id)
|
172
|
+
except ValidationError as e:
|
173
|
+
raise ValueError("Erro na validação dos dados de input da inicialização da instância:", e.errors())
|
174
|
+
|
175
|
+
try:
|
176
|
+
folder_metadata = {
|
177
|
+
"name": name,
|
178
|
+
"parents": [parent_folder_id],
|
179
|
+
"mimeType": "application/vnd.google-apps.folder",
|
180
|
+
}
|
181
|
+
folder = (
|
182
|
+
self.service.files().create(body=folder_metadata, fields="id", supportsAllDrives=True).execute()
|
183
|
+
)
|
184
|
+
return {"success" : True, "result": folder}
|
185
|
+
except Exception as e:
|
186
|
+
logging.debug(f"Não foi possível criar a pasta {name}")
|
187
|
+
return {"success" : False, "result": None, "error" : str(e)}
|
188
|
+
|
189
|
+
|
190
|
+
def list_items_folder(self, query: str = "", spaces: str = "drive", fields: str = "nextPageToken, files(id, name)"):
|
191
|
+
"""
|
192
|
+
Lista os arquivos e pastas no Google Drive com base nos critérios fornecidos.
|
193
|
+
|
194
|
+
Args:
|
195
|
+
query (str, optional): Critério de busca para os arquivos ou pastas no Google Drive.
|
196
|
+
Consulte https://developers.google.com/drive/api/v3/ref-search-terms.
|
197
|
+
Defaults to "".
|
198
|
+
exemplo: query = 'ID_DA_PASTA_NO_GOOGLE_DRIVE' in parents and trashed=false"
|
199
|
+
spaces (str, optional): Especifica os locais de armazenamento a serem consultados. Pode ser 'drive',
|
200
|
+
'appDataFolder', ou 'photos'. Defaults to 'drive'.
|
201
|
+
fields (str, optional): Campos a serem retornados na resposta. Consulte a documentação para os campos disponíveis.
|
202
|
+
Defaults to "nextPageToken, files(id, name)".
|
203
|
+
|
204
|
+
Returns:
|
205
|
+
dict: Dicionário contendo o resultado da busca.
|
206
|
+
"""
|
207
|
+
try:
|
208
|
+
ListFolderValidator(query=query, fields=fields, spaces=spaces)
|
209
|
+
except ValidationError as e:
|
210
|
+
raise ValueError("Erro na validação dos dados de input da lista:", e.errors())
|
211
|
+
try:
|
212
|
+
results = (
|
213
|
+
self.service.files()
|
214
|
+
.list(q=query,
|
215
|
+
spaces=spaces,
|
216
|
+
pageSize=self.page_size,
|
217
|
+
fields=fields,
|
218
|
+
supportsAllDrives=True,
|
219
|
+
includeItemsFromAllDrives=True)
|
220
|
+
.execute()
|
221
|
+
)
|
222
|
+
return {"success" : True, "result" : results}
|
223
|
+
except HttpError as hr:
|
224
|
+
logging.debug(f"Ocorreu um de http. Erro: {hr}")
|
225
|
+
return {"success" : False, "result" : None, "error" : str(hr)}
|
226
|
+
except Exception as e:
|
227
|
+
logging.error(f"Ocorreu um erro ao fazer a requisição. Error: {e}")
|
228
|
+
|
229
|
+
|
230
|
+
def get_file(self, file : str, ):
|
231
|
+
"""
|
232
|
+
Obtém o conteúdo de um arquivo armazenado no Google Drive.
|
233
|
+
|
234
|
+
Esta função acessa o Google Drive usando a API e lê os dados do arquivo especificado, retornando-os como um objeto binário de memória (`BytesIO`).
|
235
|
+
|
236
|
+
Parâmetros:
|
237
|
+
- file (str): Dicionário contendo informações do arquivo no Google Drive, incluindo as chaves:
|
238
|
+
- `"name"`: Nome do arquivo.
|
239
|
+
- `"id"`: ID do arquivo.
|
240
|
+
|
241
|
+
Retorna:
|
242
|
+
- BytesIO: Objeto em memória contendo os dados do arquivo.
|
243
|
+
- None: Caso ocorra um erro ao tentar abrir ou ler o arquivo.
|
244
|
+
|
245
|
+
Logs:
|
246
|
+
- Registra mensagens indicando o início e o término da leitura do arquivo.
|
247
|
+
- Em caso de falha, registra o erro ocorrido.
|
248
|
+
|
249
|
+
Exceções:
|
250
|
+
- Qualquer erro durante o processo será capturado e registrado no log. A função retornará `None` nesses casos.
|
251
|
+
|
252
|
+
Dependências:
|
253
|
+
- A função assume a existência de um atributo `self.service` configurado para interagir com a API do Google Drive.
|
254
|
+
"""
|
255
|
+
try:
|
256
|
+
logging.debug(f"Lendo o arquivo {file.get('name')}")
|
257
|
+
request = self.service.files().get_media(fileId=file.get("id"))
|
258
|
+
file_data = BytesIO(request.execute())
|
259
|
+
logging.debug("Leitura do arquivo finalizada")
|
260
|
+
|
261
|
+
return {"success" : True, "result" : file_data}
|
262
|
+
|
263
|
+
except Exception as e:
|
264
|
+
logging.debug(f"Erro ao tentar abrir o arquivo. Erro {e}")
|
265
|
+
return {"success" : False, "result" : None}
|
266
|
+
|
267
|
+
|
268
|
+
|
csc_cia_stne/karavela.py
ADDED
@@ -0,0 +1,135 @@
|
|
1
|
+
import os
|
2
|
+
|
3
|
+
class Karavela():
|
4
|
+
|
5
|
+
def __init__(self)->None:
|
6
|
+
"""Inicia a instância da classe Karavela
|
7
|
+
|
8
|
+
"""
|
9
|
+
self.healthy_check_file = None
|
10
|
+
|
11
|
+
def create_health_check_file(self,health_check_filename:str = None)->bool:
|
12
|
+
"""
|
13
|
+
Cria um arquivo de verificação de saúde.
|
14
|
+
Args:
|
15
|
+
health_check_filename (str, optional): O nome do arquivo de verificação de saúde.
|
16
|
+
Se não for fornecido, um ValueError será levantado.
|
17
|
+
Returns:
|
18
|
+
bool: True se o arquivo for criado com sucesso.
|
19
|
+
Raises:
|
20
|
+
ValueError: Se o parâmetro health_check_filename não for fornecido.
|
21
|
+
Example:
|
22
|
+
>>> karavela = Karavela()
|
23
|
+
>>> karavela.create_health_check_file("health_check.txt")
|
24
|
+
True
|
25
|
+
"""
|
26
|
+
|
27
|
+
|
28
|
+
if health_check_filename is None or health_check_filename == "":
|
29
|
+
|
30
|
+
raise ValueError("O método 'create_health_check_file' precisa do parâmetro health_check_filename especificado")
|
31
|
+
|
32
|
+
self.health_check_filename = health_check_filename
|
33
|
+
|
34
|
+
try:
|
35
|
+
|
36
|
+
if not os.path.exists(self.health_check_filename):
|
37
|
+
|
38
|
+
directory = os.path.dirname(self.health_check_filename)
|
39
|
+
|
40
|
+
if not os.path.exists(directory) and str(directory).strip() != "":
|
41
|
+
|
42
|
+
os.makedirs(directory)
|
43
|
+
|
44
|
+
with open(f'{self.health_check_filename}', 'w') as f:
|
45
|
+
|
46
|
+
f.write('OK!')
|
47
|
+
return True
|
48
|
+
|
49
|
+
except Exception as e:
|
50
|
+
|
51
|
+
raise e
|
52
|
+
|
53
|
+
def destroy_health_check_file(self)->bool:
|
54
|
+
"""
|
55
|
+
Remove o arquivo de verificação de saúde.
|
56
|
+
Retorna:
|
57
|
+
bool: True se o arquivo foi removido com sucesso, False caso contrário.
|
58
|
+
Raises:
|
59
|
+
ValueError: Se o método 'create_health_check_file' não foi executado antes.
|
60
|
+
Exception: Se ocorrer algum erro durante a remoção do arquivo.
|
61
|
+
"""
|
62
|
+
|
63
|
+
|
64
|
+
if self.health_check_filename is None:
|
65
|
+
|
66
|
+
raise ValueError("O método 'create_health_check_file' precisa ser executado antes")
|
67
|
+
|
68
|
+
try:
|
69
|
+
|
70
|
+
if os.path.exists(self.health_check_filename):
|
71
|
+
|
72
|
+
os.remove(self.health_check_filename)
|
73
|
+
return True
|
74
|
+
|
75
|
+
else:
|
76
|
+
|
77
|
+
return True
|
78
|
+
|
79
|
+
except Exception as e:
|
80
|
+
|
81
|
+
raise e
|
82
|
+
|
83
|
+
def get_secret(self,name:str)->str:
|
84
|
+
"""Extrai a secret do ambiente
|
85
|
+
|
86
|
+
Args:
|
87
|
+
name (str): nome da variavel ou arquivo da secret
|
88
|
+
|
89
|
+
Returns:
|
90
|
+
str: string da secret armazenada na variável de ambiente ou no arquivo de secret
|
91
|
+
"""
|
92
|
+
|
93
|
+
# Tentando extrair da variavel de ambiente
|
94
|
+
secret = os.getenv(name)
|
95
|
+
|
96
|
+
# secret não encontrada em variavel de ambiente, tentando extrair do arquivo em /secret
|
97
|
+
if secret is None:
|
98
|
+
|
99
|
+
# verifica na pasta ./secrets
|
100
|
+
if os.path.exists(f"./secrets/{name}"):
|
101
|
+
|
102
|
+
with open(f"./secrets/{name}",'r') as secret_file:
|
103
|
+
|
104
|
+
secret = secret_file.read()
|
105
|
+
|
106
|
+
# verifica na pasta ./.secrets
|
107
|
+
elif os.path.exists(f"./.secrets/{name}"):
|
108
|
+
|
109
|
+
with open(f"./.secrets/{name}",'r') as secret_file:
|
110
|
+
|
111
|
+
secret = secret_file.read()
|
112
|
+
|
113
|
+
# verifica na pasta ./private
|
114
|
+
elif os.path.exists(f"./private/{name}"):
|
115
|
+
|
116
|
+
with open(f"./private/{name}",'r') as secret_file:
|
117
|
+
|
118
|
+
secret = secret_file.read()
|
119
|
+
|
120
|
+
# verifica na pasta ./.private
|
121
|
+
elif os.path.exists(f"./.private/{name}"):
|
122
|
+
|
123
|
+
with open(f"./.private/{name}",'r') as secret_file:
|
124
|
+
|
125
|
+
secret = secret_file.read()
|
126
|
+
|
127
|
+
# verifica na pasta /secrets
|
128
|
+
elif os.path.exists(f"/secrets/{name}"):
|
129
|
+
|
130
|
+
with open(f"/secrets/{name}",'r') as secret_file:
|
131
|
+
|
132
|
+
secret = secret_file.read()
|
133
|
+
|
134
|
+
return secret
|
135
|
+
|