csc-cia-stne 0.0.67__py3-none-any.whl → 0.0.68__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/google_drive.py +158 -128
- {csc_cia_stne-0.0.67.dist-info → csc_cia_stne-0.0.68.dist-info}/METADATA +1 -1
- {csc_cia_stne-0.0.67.dist-info → csc_cia_stne-0.0.68.dist-info}/RECORD +6 -6
- {csc_cia_stne-0.0.67.dist-info → csc_cia_stne-0.0.68.dist-info}/LICENCE +0 -0
- {csc_cia_stne-0.0.67.dist-info → csc_cia_stne-0.0.68.dist-info}/WHEEL +0 -0
- {csc_cia_stne-0.0.67.dist-info → csc_cia_stne-0.0.68.dist-info}/top_level.txt +0 -0
csc_cia_stne/google_drive.py
CHANGED
@@ -1,22 +1,27 @@
|
|
1
|
-
import os
|
1
|
+
import os
|
2
2
|
from googleapiclient.discovery import build
|
3
3
|
from googleapiclient.http import MediaFileUpload
|
4
4
|
from googleapiclient.errors import HttpError
|
5
5
|
from io import BytesIO
|
6
6
|
from google.oauth2 import service_account
|
7
|
-
from .utilitarios.validations.GoogleDriveValidator import
|
7
|
+
from .utilitarios.validations.GoogleDriveValidator import (
|
8
|
+
InitParamsValidator,
|
9
|
+
CreateFolderValidator,
|
10
|
+
ListFolderValidator,
|
11
|
+
UploadValidator,
|
12
|
+
)
|
8
13
|
from pydantic import ValidationError
|
9
14
|
|
10
15
|
|
11
|
-
class GoogleDrive
|
12
|
-
|
16
|
+
class GoogleDrive:
|
13
17
|
"""
|
14
|
-
|
15
|
-
|
18
|
+
Classe responsável por gerenciar operações no Google Drive, como upload de arquivos, criação de pastas
|
19
|
+
e listagem de conteúdo. Utiliza a API do Google Drive para realizar essas operações.
|
16
20
|
|
17
|
-
|
18
|
-
|
21
|
+
Args:
|
22
|
+
key (str): Chave de autenticação para acessar a API do Google Drive.
|
19
23
|
"""
|
24
|
+
|
20
25
|
_instance = None # Atributo de classe para armazenar a única instância.
|
21
26
|
|
22
27
|
def __new__(cls, *args, **kwargs):
|
@@ -25,8 +30,14 @@ class GoogleDrive():
|
|
25
30
|
# Cria e armazena a instância na primeira chamada.
|
26
31
|
cls._instance = super().__new__(cls)
|
27
32
|
return cls._instance
|
28
|
-
|
29
|
-
def __init__(
|
33
|
+
|
34
|
+
def __init__(
|
35
|
+
self,
|
36
|
+
token: dict,
|
37
|
+
with_subject: str,
|
38
|
+
scopes: list = ["https://www.googleapis.com/auth/drive"],
|
39
|
+
version: str = "v3",
|
40
|
+
):
|
30
41
|
"""
|
31
42
|
Inicializa uma instância da classe GoogleDrive.
|
32
43
|
Parâmetros:
|
@@ -41,11 +52,16 @@ class GoogleDrive():
|
|
41
52
|
google_drive = GoogleDrive(key="chave_secreta", with_subject="assunto", scopes=["https://www.googleapis.com/auth/drive"], version="v3")
|
42
53
|
```
|
43
54
|
"""
|
44
|
-
|
55
|
+
|
45
56
|
try:
|
46
|
-
InitParamsValidator(
|
57
|
+
InitParamsValidator(
|
58
|
+
token=token, with_subject=with_subject, scopes=scopes, version=version
|
59
|
+
)
|
47
60
|
except ValidationError as e:
|
48
|
-
raise ValueError(
|
61
|
+
raise ValueError(
|
62
|
+
"Erro na validação dos dados de input da inicialização da instância:",
|
63
|
+
e.errors(),
|
64
|
+
)
|
49
65
|
self.__token = token
|
50
66
|
self.version = version
|
51
67
|
self.scopes = scopes
|
@@ -53,7 +69,6 @@ class GoogleDrive():
|
|
53
69
|
self.page_size = 1000
|
54
70
|
self.service = self.__create_service()
|
55
71
|
|
56
|
-
|
57
72
|
def __create_service(self):
|
58
73
|
"""
|
59
74
|
Cria um serviço do Google Drive.
|
@@ -69,18 +84,15 @@ class GoogleDrive():
|
|
69
84
|
else:
|
70
85
|
# Tratar o erro de criação do serviço
|
71
86
|
"""
|
72
|
-
|
87
|
+
|
73
88
|
try:
|
74
89
|
auth = self.__autentica(self.with_subject)
|
75
90
|
service = build(f"drive", f"{self.version}", credentials=auth)
|
76
|
-
logging.info(f"Serviço do Google drive criado")
|
77
91
|
return service
|
78
92
|
except Exception as e:
|
79
|
-
logging.info(f"Erro ao criar o serviço do Google drive: Error: {e}")
|
80
93
|
return False
|
81
94
|
|
82
|
-
|
83
|
-
def __autentica(self, with_subject : str):
|
95
|
+
def __autentica(self, with_subject: str):
|
84
96
|
"""
|
85
97
|
Autentica o usuário com as credenciais fornecidas e retorna as credenciais delegadas para o assunto especificado.
|
86
98
|
Args:
|
@@ -93,85 +105,95 @@ class GoogleDrive():
|
|
93
105
|
# Autenticar com o assunto "user@example.com"
|
94
106
|
credentials = self.__autentica("user@example.com")
|
95
107
|
"""
|
96
|
-
|
97
108
|
|
98
109
|
try:
|
99
|
-
credentials = service_account.Credentials.from_service_account_info(
|
110
|
+
credentials = service_account.Credentials.from_service_account_info(
|
111
|
+
self.__token, scopes=self.scopes
|
112
|
+
)
|
100
113
|
delegated_credencial = credentials.with_subject(with_subject)
|
101
114
|
return delegated_credencial
|
102
115
|
|
103
116
|
except Exception as e:
|
104
|
-
logging.debug(f"Erro ao tentar autenticar. Verifique o erro: {e}")
|
105
117
|
return False
|
106
118
|
|
107
|
-
|
108
119
|
def upload(self, folder_id: str, name: str, file_path: str, mimetype: str):
|
109
120
|
"""
|
110
|
-
|
111
|
-
|
112
|
-
|
113
|
-
|
114
|
-
|
115
|
-
|
116
|
-
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
121
|
+
Faz o upload de um arquivo para o Google Drive em uma pasta especificada.
|
122
|
+
|
123
|
+
Args:
|
124
|
+
folder_id (str): ID da pasta no Google Drive onde o arquivo será armazenado.
|
125
|
+
name (str): Nome do arquivo que será carregado.
|
126
|
+
file_path (str): Caminho completo do arquivo no sistema local.
|
127
|
+
mimetype (str): Tipo MIME do arquivo a ser carregado.
|
128
|
+
exemplos: text/plain
|
129
|
+
text/html
|
130
|
+
image/jpeg
|
131
|
+
image/png
|
132
|
+
audio/mpeg
|
133
|
+
audio/ogg
|
134
|
+
audio/*
|
135
|
+
video/mp4
|
136
|
+
application/octet-stream
|
137
|
+
|
138
|
+
Returns:
|
139
|
+
dict: Informações sobre o arquivo carregado, incluindo o ID do arquivo.
|
140
|
+
None: Caso o caminho do arquivo não seja encontrado.
|
130
141
|
"""
|
131
142
|
try:
|
132
|
-
UploadValidator(
|
143
|
+
UploadValidator(
|
144
|
+
folder_id=folder_id, name=name, file_path=file_path, mimetype=mimetype
|
145
|
+
)
|
133
146
|
except ValidationError as e:
|
134
|
-
raise ValueError(
|
135
|
-
|
147
|
+
raise ValueError(
|
148
|
+
"Erro na validação dos dados para realizar o upload do arquivo",
|
149
|
+
e.errors(),
|
150
|
+
)
|
136
151
|
|
137
|
-
|
138
152
|
file_metadata = {"name": name, "parents": [folder_id]}
|
139
153
|
if not os.path.exists(file_path):
|
140
|
-
|
141
|
-
|
142
|
-
|
154
|
+
return {
|
155
|
+
"success": False,
|
156
|
+
"result": None,
|
157
|
+
"error": "Diretório ou arquivo não encontrado",
|
158
|
+
}
|
159
|
+
|
143
160
|
try:
|
144
|
-
logging.debug(f"Realizando o upload do arquivo")
|
145
161
|
media = MediaFileUpload(file_path, mimetype=mimetype, resumable=True)
|
146
162
|
file = (
|
147
163
|
self.service.files()
|
148
|
-
.create(
|
164
|
+
.create(
|
165
|
+
body=file_metadata,
|
166
|
+
media_body=media,
|
167
|
+
fields="id",
|
168
|
+
supportsAllDrives=True,
|
169
|
+
)
|
149
170
|
.execute()
|
150
171
|
)
|
151
172
|
|
152
|
-
|
153
|
-
return {"success" : True, "result" : file}
|
173
|
+
return {"success": True, "result": file}
|
154
174
|
except Exception as e:
|
155
|
-
|
156
|
-
return {"success"
|
157
|
-
|
175
|
+
|
176
|
+
return {"success": False, "result": None, "error": str(e)}
|
158
177
|
|
159
178
|
def create_folder(self, name: str, parent_folder_id: str):
|
160
179
|
"""
|
161
|
-
|
180
|
+
Cria uma pasta no Google Drive dentro de uma pasta existente.
|
162
181
|
|
163
|
-
|
164
|
-
|
165
|
-
|
182
|
+
Args:
|
183
|
+
name (str): Nome da pasta a ser criada.
|
184
|
+
parent_folder_id (int): ID da pasta pai onde a nova pasta será criada.
|
166
185
|
|
167
|
-
|
168
|
-
|
186
|
+
Returns:
|
187
|
+
str: ID da pasta criada.
|
169
188
|
"""
|
170
189
|
try:
|
171
190
|
CreateFolderValidator(name=name, parent_folder_id=parent_folder_id)
|
172
191
|
except ValidationError as e:
|
173
|
-
raise ValueError(
|
174
|
-
|
192
|
+
raise ValueError(
|
193
|
+
"Erro na validação dos dados de input da inicialização da instância:",
|
194
|
+
e.errors(),
|
195
|
+
)
|
196
|
+
|
175
197
|
try:
|
176
198
|
folder_metadata = {
|
177
199
|
"name": name,
|
@@ -179,91 +201,101 @@ class GoogleDrive():
|
|
179
201
|
"mimeType": "application/vnd.google-apps.folder",
|
180
202
|
}
|
181
203
|
folder = (
|
182
|
-
self.service.files()
|
204
|
+
self.service.files()
|
205
|
+
.create(body=folder_metadata, fields="id", supportsAllDrives=True)
|
206
|
+
.execute()
|
183
207
|
)
|
184
|
-
return {"success"
|
208
|
+
return {"success": True, "result": folder}
|
185
209
|
except Exception as e:
|
186
|
-
|
187
|
-
|
210
|
+
return {"success": False, "result": None, "error": str(e)}
|
211
|
+
|
212
|
+
def list_items_folder(
|
213
|
+
self,
|
214
|
+
query: str = "",
|
215
|
+
spaces: str = "drive",
|
216
|
+
fields: str = "nextPageToken, files(id, name)",
|
217
|
+
):
|
218
|
+
"""
|
219
|
+
Lista os arquivos e pastas no Google Drive com base nos critérios fornecidos.
|
188
220
|
|
221
|
+
Args:
|
222
|
+
query (str, optional): Critério de busca para os arquivos ou pastas no Google Drive.
|
223
|
+
Consulte https://developers.google.com/drive/api/v3/ref-search-terms.
|
224
|
+
Defaults to "".
|
225
|
+
exemplo: query = 'ID_DA_PASTA_NO_GOOGLE_DRIVE' in parents and trashed=false"
|
226
|
+
spaces (str, optional): Especifica os locais de armazenamento a serem consultados. Pode ser 'drive',
|
227
|
+
'appDataFolder', ou 'photos'. Defaults to 'drive'.
|
228
|
+
fields (str, optional): Campos a serem retornados na resposta. Consulte a documentação para os campos disponíveis.
|
229
|
+
Defaults to "nextPageToken, files(id, name)".
|
189
230
|
|
190
|
-
|
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.
|
231
|
+
Returns:
|
232
|
+
dict: Dicionário contendo o resultado da busca.
|
206
233
|
"""
|
207
234
|
try:
|
208
235
|
ListFolderValidator(query=query, fields=fields, spaces=spaces)
|
209
236
|
except ValidationError as e:
|
210
|
-
raise ValueError(
|
211
|
-
|
237
|
+
raise ValueError(
|
238
|
+
"Erro na validação dos dados de input da lista:", e.errors()
|
239
|
+
)
|
240
|
+
try:
|
212
241
|
results = (
|
213
242
|
self.service.files()
|
214
|
-
.list(
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
243
|
+
.list(
|
244
|
+
q=query,
|
245
|
+
spaces=spaces,
|
246
|
+
pageSize=self.page_size,
|
247
|
+
fields=fields,
|
248
|
+
supportsAllDrives=True,
|
249
|
+
includeItemsFromAllDrives=True,
|
250
|
+
)
|
220
251
|
.execute()
|
221
252
|
)
|
222
|
-
return {"success"
|
253
|
+
return {"success": True, "result": results}
|
223
254
|
except HttpError as hr:
|
224
|
-
|
225
|
-
return {"success" : False, "result" : None, "error" : str(hr)}
|
255
|
+
return {"success": False, "result": None, "error": str(hr)}
|
226
256
|
except Exception as e:
|
227
|
-
|
228
|
-
|
257
|
+
return {"success": False, "result": None, "error": str(e)}
|
229
258
|
|
230
|
-
def download_file(self, file
|
259
|
+
def download_file(self, file: str, mimeType: str):
|
231
260
|
"""
|
232
|
-
|
261
|
+
Obtém o conteúdo de um arquivo armazenado no Google Drive.
|
233
262
|
|
234
|
-
|
263
|
+
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
264
|
|
236
|
-
|
237
|
-
|
238
|
-
|
239
|
-
|
265
|
+
Parâmetros:
|
266
|
+
- file (str): Dicionário contendo informações do arquivo no Google Drive, incluindo as chaves:
|
267
|
+
- `"name"`: Nome do arquivo.
|
268
|
+
- `"id"`: ID do arquivo.
|
240
269
|
|
241
|
-
|
242
|
-
|
243
|
-
|
270
|
+
Retorna:
|
271
|
+
- BytesIO: Objeto em memória contendo os dados do arquivo.
|
272
|
+
- None: Caso ocorra um erro ao tentar abrir ou ler o arquivo.
|
244
273
|
|
245
|
-
|
246
|
-
|
247
|
-
|
274
|
+
Logs:
|
275
|
+
- Registra mensagens indicando o início e o término da leitura do arquivo.
|
276
|
+
- Em caso de falha, registra o erro ocorrido.
|
248
277
|
|
249
|
-
|
250
|
-
|
278
|
+
Exceções:
|
279
|
+
- Qualquer erro durante o processo será capturado e registrado no log. A função retornará `None` nesses casos.
|
251
280
|
|
252
|
-
|
253
|
-
|
281
|
+
Dependências:
|
282
|
+
- A função assume a existência de um atributo `self.service` configurado para interagir com a API do Google Drive.
|
254
283
|
"""
|
255
284
|
try:
|
256
|
-
request = self.service.files().export_media(
|
257
|
-
|
285
|
+
request = self.service.files().export_media(
|
286
|
+
fileId=file.get("id"), mimeType=mimeType
|
287
|
+
)
|
288
|
+
with open(file["name"], "wb") as f:
|
258
289
|
f.write(request.execute())
|
259
|
-
return {
|
260
|
-
|
290
|
+
return {
|
291
|
+
"success": True,
|
292
|
+
"result": f"Arquivo baixado com sucesso. Diretório: {file}",
|
293
|
+
}
|
294
|
+
|
261
295
|
except Exception as e:
|
262
|
-
|
263
|
-
return {"success" : False, "result" : None}
|
264
|
-
|
296
|
+
return {"success": False, "result": None}
|
265
297
|
|
266
|
-
def get_base_data(self, id_sheet:str,page:str) -> list:
|
298
|
+
def get_base_data(self, id_sheet: str, page: str) -> list:
|
267
299
|
"""
|
268
300
|
Retorna os dados da planilha especificada.
|
269
301
|
Parâmetros:
|
@@ -281,9 +313,7 @@ class GoogleDrive():
|
|
281
313
|
try:
|
282
314
|
sheet = self.service.spreadsheets()
|
283
315
|
result = sheet.values().get(spreadsheetId=id_sheet, range=page).execute()
|
284
|
-
values = result.get(
|
285
|
-
return {"success"
|
316
|
+
values = result.get("values", [])
|
317
|
+
return {"success": True, "result": values}
|
286
318
|
except Exception as e:
|
287
|
-
return {"success"
|
288
|
-
|
289
|
-
|
319
|
+
return {"success": False, "result": None, "error": str(e)}
|
@@ -3,7 +3,7 @@ csc_cia_stne/bc_correios.py,sha256=pQAnRrcXEMrx3N1MWydZVIhEQLerh3x8-0B045zZIzk,2
|
|
3
3
|
csc_cia_stne/bc_sta.py,sha256=KWHTytM3msAFayt8y5_97RwWHE8Dv8ssfwyh6zU7xI0,25836
|
4
4
|
csc_cia_stne/email.py,sha256=RK_TzWBVnUfpP-s5NvjTJJjzhICy8e2fME9EuaiySMY,8162
|
5
5
|
csc_cia_stne/gcp_bigquery.py,sha256=jYxvqrWDOPkxc05U4aef7V5lL8ptqsE93lfn0dLFyvc,7385
|
6
|
-
csc_cia_stne/google_drive.py,sha256=
|
6
|
+
csc_cia_stne/google_drive.py,sha256=0gZMW69jEvBMcUl3s9qaL5-q2IXOEAghnfhXp6-6ooY,12357
|
7
7
|
csc_cia_stne/karavela.py,sha256=jJCYX43D49gGuzmwwK6bN9XVnv2dXdp9iHnnV5H1LMQ,4794
|
8
8
|
csc_cia_stne/logger_json.py,sha256=CXxSCOFGMymDi8XE9SKnPKjW4D0wJLqDLnxqePS26i8,3187
|
9
9
|
csc_cia_stne/logger_rich.py,sha256=WlMqxH1lMy-tzK0I4NpBRgSzPdHc2-YSU71N3SsKM5A,8338
|
@@ -26,8 +26,8 @@ csc_cia_stne/utilitarios/validations/GoogleDriveValidator.py,sha256=PBo-AV2bjR__
|
|
26
26
|
csc_cia_stne/utilitarios/validations/ServiceNowValidator.py,sha256=yleKUIo1ZfyloP9fDPNjv3JJXdLcocT81WIgRSYmqEA,14423
|
27
27
|
csc_cia_stne/utilitarios/validations/__init__.py,sha256=O_qyEU2ji3u6LHUXZCXvUFsMpoMWL625qqHTXyXivTA,106
|
28
28
|
csc_cia_stne/utilitarios/validations/web_validator.py,sha256=HYKYSpDv1RvRjZIuwTPt-AbEz-9392MxM_O329iYuSA,5722
|
29
|
-
csc_cia_stne-0.0.
|
30
|
-
csc_cia_stne-0.0.
|
31
|
-
csc_cia_stne-0.0.
|
32
|
-
csc_cia_stne-0.0.
|
33
|
-
csc_cia_stne-0.0.
|
29
|
+
csc_cia_stne-0.0.68.dist-info/LICENCE,sha256=LPGMtgKki2C3KEZP7hDhA1HBrlq5JCHkIeStUCLEMx4,1073
|
30
|
+
csc_cia_stne-0.0.68.dist-info/METADATA,sha256=Rtr1P2z_LC8R8NSeqCtJhMZFF_AYCi0vYjPwMSRGBUo,1340
|
31
|
+
csc_cia_stne-0.0.68.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
32
|
+
csc_cia_stne-0.0.68.dist-info/top_level.txt,sha256=ldo7GVv3tQx5KJvwBzdZzzQmjPys2NDVVn1rv0BOF2Q,13
|
33
|
+
csc_cia_stne-0.0.68.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|