gapi-tools 0.2.0__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.
- gapi_tools/__init__.py +100 -0
- gapi_tools/auth.py +50 -0
- gapi_tools/cli.py +227 -0
- gapi_tools/config.py +72 -0
- gapi_tools/drive.py +446 -0
- gapi_tools/exceptions.py +19 -0
- gapi_tools/sheets.py +58 -0
- gapi_tools-0.2.0.dist-info/METADATA +175 -0
- gapi_tools-0.2.0.dist-info/RECORD +12 -0
- gapi_tools-0.2.0.dist-info/WHEEL +4 -0
- gapi_tools-0.2.0.dist-info/entry_points.txt +2 -0
- gapi_tools-0.2.0.dist-info/licenses/LICENSE +21 -0
gapi_tools/__init__.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""gapi_tools — utilitários para Google Drive e Sheets.
|
|
2
|
+
|
|
3
|
+
API pública:
|
|
4
|
+
|
|
5
|
+
* :mod:`gapi_tools.drive` — operações sobre arquivos/pastas.
|
|
6
|
+
* :mod:`gapi_tools.sheets` — operações sobre Google Sheets.
|
|
7
|
+
* :mod:`gapi_tools.cli` — interface de linha de comando ``gapi``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import warnings as _warnings
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .drive import (
|
|
16
|
+
copy_file,
|
|
17
|
+
create_file,
|
|
18
|
+
create_folder,
|
|
19
|
+
delete_file,
|
|
20
|
+
download_spreadsheet,
|
|
21
|
+
empty_folder,
|
|
22
|
+
find_file_id,
|
|
23
|
+
get_file_modification_time,
|
|
24
|
+
list_files,
|
|
25
|
+
list_files_detailed,
|
|
26
|
+
list_permissions,
|
|
27
|
+
list_revisions,
|
|
28
|
+
move_file,
|
|
29
|
+
rename_file,
|
|
30
|
+
trash_file,
|
|
31
|
+
untrash_file,
|
|
32
|
+
update_metadata,
|
|
33
|
+
upload_file,
|
|
34
|
+
)
|
|
35
|
+
from .exceptions import (
|
|
36
|
+
ConfigError,
|
|
37
|
+
DriveOperationError,
|
|
38
|
+
GoogleApiUtilsError,
|
|
39
|
+
RemoteFileNotFound,
|
|
40
|
+
)
|
|
41
|
+
from .sheets import export_dataframe_to_gsheet
|
|
42
|
+
|
|
43
|
+
__version__ = '0.2.0'
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
'__version__',
|
|
47
|
+
'GoogleApiUtilsError',
|
|
48
|
+
'ConfigError',
|
|
49
|
+
'RemoteFileNotFound',
|
|
50
|
+
'DriveOperationError',
|
|
51
|
+
'list_files',
|
|
52
|
+
'list_files_detailed',
|
|
53
|
+
'find_file_id',
|
|
54
|
+
'download_spreadsheet',
|
|
55
|
+
'upload_file',
|
|
56
|
+
'empty_folder',
|
|
57
|
+
'get_file_modification_time',
|
|
58
|
+
'move_file',
|
|
59
|
+
'create_folder',
|
|
60
|
+
'create_file',
|
|
61
|
+
'copy_file',
|
|
62
|
+
'rename_file',
|
|
63
|
+
'update_metadata',
|
|
64
|
+
'trash_file',
|
|
65
|
+
'untrash_file',
|
|
66
|
+
'delete_file',
|
|
67
|
+
'list_permissions',
|
|
68
|
+
'list_revisions',
|
|
69
|
+
'export_dataframe_to_gsheet',
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def send_file_to_folder(
|
|
74
|
+
folder_id: str, file_name: str, file_path: str
|
|
75
|
+
) -> Any:
|
|
76
|
+
"""Alias depreciado de :func:`upload_file`.
|
|
77
|
+
|
|
78
|
+
Na assinatura legada, ``file_path`` apontava para a *pasta* contendo
|
|
79
|
+
``file_name``.
|
|
80
|
+
"""
|
|
81
|
+
_warnings.warn(
|
|
82
|
+
'send_file_to_folder está depreciado; use upload_file(folder_id, '
|
|
83
|
+
'file_path, file_name).',
|
|
84
|
+
DeprecationWarning,
|
|
85
|
+
stacklevel=2,
|
|
86
|
+
)
|
|
87
|
+
from pathlib import Path
|
|
88
|
+
|
|
89
|
+
return upload_file(folder_id, str(Path(file_path) / file_name), file_name)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def empty_a_folder(folder_id: str) -> bool:
|
|
93
|
+
"""Alias depreciado de :func:`empty_folder`."""
|
|
94
|
+
_warnings.warn(
|
|
95
|
+
'empty_a_folder está depreciado; use empty_folder.',
|
|
96
|
+
DeprecationWarning,
|
|
97
|
+
stacklevel=2,
|
|
98
|
+
)
|
|
99
|
+
empty_folder(folder_id)
|
|
100
|
+
return True
|
gapi_tools/auth.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Autenticação e cache de serviços Google API.
|
|
2
|
+
|
|
3
|
+
Usa credenciais de service account (formato JSON) e cacheia o objeto de serviço
|
|
4
|
+
por par ``(service_name, version)`` para evitar chamadas redundantes a
|
|
5
|
+
``discovery.build`` durante a vida do processo.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Dict, Tuple
|
|
11
|
+
|
|
12
|
+
from googleapiclient import discovery
|
|
13
|
+
from googleapiclient.discovery import Resource
|
|
14
|
+
from google.oauth2.service_account import Credentials
|
|
15
|
+
|
|
16
|
+
from .config import SCOPES, resolve_token_path
|
|
17
|
+
|
|
18
|
+
_service_cache: Dict[Tuple[str, str], Resource] = {}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _build_credentials() -> Credentials:
|
|
22
|
+
"""Carrega as credenciais da service account a partir do token resolvido."""
|
|
23
|
+
token_path = resolve_token_path()
|
|
24
|
+
return Credentials.from_service_account_file(
|
|
25
|
+
str(token_path), scopes=list(SCOPES)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def get_service(service_name: str, version: str) -> Resource:
|
|
30
|
+
"""Retorna um cliente Google API, reutilizando instâncias já criadas.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
service_name: Nome do serviço (ex.: ``'drive'``, ``'sheets'``).
|
|
34
|
+
version: Versão da API (ex.: ``'v3'``, ``'v4'``).
|
|
35
|
+
"""
|
|
36
|
+
key = (service_name, version)
|
|
37
|
+
if key not in _service_cache:
|
|
38
|
+
credentials = _build_credentials()
|
|
39
|
+
_service_cache[key] = discovery.build(
|
|
40
|
+
service_name,
|
|
41
|
+
version,
|
|
42
|
+
credentials=credentials,
|
|
43
|
+
cache_discovery=False,
|
|
44
|
+
)
|
|
45
|
+
return _service_cache[key]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def reset_service_cache() -> None:
|
|
49
|
+
"""Limpa o cache interno — útil em testes ou ao trocar credenciais."""
|
|
50
|
+
_service_cache.clear()
|
gapi_tools/cli.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""CLI unificada do pacote, exposta como ``gapi``.
|
|
2
|
+
|
|
3
|
+
As assinaturas dos comandos usam ``typing.Optional`` / ``typing.List`` em vez
|
|
4
|
+
de ``X | None`` ou ``list[str]`` porque Typer chama ``typing.get_type_hints``
|
|
5
|
+
em runtime e o alvo de execução é Python 3.8.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from typing import List, Optional
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
|
|
13
|
+
from . import drive, sheets
|
|
14
|
+
from .exceptions import GoogleApiUtilsError
|
|
15
|
+
|
|
16
|
+
app = typer.Typer(
|
|
17
|
+
add_completion=False,
|
|
18
|
+
help='Utilitários para Google Drive e Sheets.',
|
|
19
|
+
no_args_is_help=True,
|
|
20
|
+
)
|
|
21
|
+
sheets_app = typer.Typer(help='Operações no Google Sheets.', no_args_is_help=True)
|
|
22
|
+
app.add_typer(sheets_app, name='sheets')
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _print_json(data) -> None:
|
|
26
|
+
typer.echo(json.dumps(data, indent=2, ensure_ascii=False, default=str))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _run(callable_, *args, **kwargs):
|
|
30
|
+
"""Executa uma operação tratando exceções do pacote como erro de CLI."""
|
|
31
|
+
try:
|
|
32
|
+
return callable_(*args, **kwargs)
|
|
33
|
+
except GoogleApiUtilsError as error:
|
|
34
|
+
typer.secho(str(error), err=True, fg=typer.colors.RED)
|
|
35
|
+
raise typer.Exit(code=1)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@app.command('list')
|
|
39
|
+
def list_cmd(
|
|
40
|
+
page_size: int = typer.Option(100, '--page-size', '-n'),
|
|
41
|
+
query: Optional[str] = typer.Option(None, '--query', '-q', help='Filtro Drive (campo q).'),
|
|
42
|
+
detailed: bool = typer.Option(False, '--detailed', help='Inclui mimeType e modifiedTime.'),
|
|
43
|
+
) -> None:
|
|
44
|
+
"""Lista arquivos visíveis pela service account."""
|
|
45
|
+
if detailed or query:
|
|
46
|
+
items = _run(drive.list_files_detailed, query=query, page_size=page_size)
|
|
47
|
+
_print_json(items)
|
|
48
|
+
else:
|
|
49
|
+
_print_json(_run(drive.list_files, page_size=page_size))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@app.command('download')
|
|
53
|
+
def download_cmd(
|
|
54
|
+
file_name: str = typer.Argument(..., help='Nome exato do arquivo no Drive.'),
|
|
55
|
+
folder: str = typer.Option('outputs', '--folder', '-f'),
|
|
56
|
+
with_date: bool = typer.Option(False, '--with-date'),
|
|
57
|
+
) -> None:
|
|
58
|
+
"""Baixa uma planilha (xlsx/xls/Google Sheets)."""
|
|
59
|
+
path = _run(drive.download_spreadsheet, file_name, folder=folder, with_date=with_date)
|
|
60
|
+
typer.echo(str(path))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@app.command('upload')
|
|
64
|
+
def upload_cmd(
|
|
65
|
+
file_path: str = typer.Argument(..., help='Caminho local do arquivo.'),
|
|
66
|
+
folder_id: str = typer.Argument(..., help='ID da pasta de destino no Drive.'),
|
|
67
|
+
name: Optional[str] = typer.Option(None, '--name'),
|
|
68
|
+
mimetype: Optional[str] = typer.Option(None, '--mimetype'),
|
|
69
|
+
) -> None:
|
|
70
|
+
"""Envia um arquivo local para uma pasta do Drive."""
|
|
71
|
+
_print_json(
|
|
72
|
+
_run(drive.upload_file, folder_id, file_path, file_name=name, mimetype=mimetype)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@app.command('move')
|
|
77
|
+
def move_cmd(
|
|
78
|
+
file_id: str = typer.Argument(...),
|
|
79
|
+
new_parent_id: str = typer.Argument(...),
|
|
80
|
+
old_parent: Optional[str] = typer.Option(None, '--old-parent'),
|
|
81
|
+
) -> None:
|
|
82
|
+
"""Move um arquivo entre pastas."""
|
|
83
|
+
_print_json(_run(drive.move_file, file_id, new_parent_id, old_parent_id=old_parent))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@app.command('copy')
|
|
87
|
+
def copy_cmd(
|
|
88
|
+
file_id: str = typer.Argument(...),
|
|
89
|
+
name: Optional[str] = typer.Option(None, '--name'),
|
|
90
|
+
parent: Optional[str] = typer.Option(None, '--parent'),
|
|
91
|
+
) -> None:
|
|
92
|
+
"""Duplica um arquivo."""
|
|
93
|
+
_print_json(_run(drive.copy_file, file_id, new_name=name, parent_id=parent))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@app.command('create-folder')
|
|
97
|
+
def create_folder_cmd(
|
|
98
|
+
name: str = typer.Argument(...),
|
|
99
|
+
parent: Optional[str] = typer.Option(None, '--parent'),
|
|
100
|
+
) -> None:
|
|
101
|
+
"""Cria uma pasta vazia."""
|
|
102
|
+
_print_json(_run(drive.create_folder, name, parent_id=parent))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@app.command('create-file')
|
|
106
|
+
def create_file_cmd(
|
|
107
|
+
name: str = typer.Argument(...),
|
|
108
|
+
parent: Optional[str] = typer.Option(None, '--parent'),
|
|
109
|
+
mime_type: str = typer.Option('application/octet-stream', '--mime-type'),
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Cria um arquivo vazio com o mime-type informado."""
|
|
112
|
+
_print_json(
|
|
113
|
+
_run(drive.create_file, name, parent_id=parent, mime_type=mime_type)
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@app.command('rename')
|
|
118
|
+
def rename_cmd(
|
|
119
|
+
file_id: str = typer.Argument(...),
|
|
120
|
+
new_name: str = typer.Argument(...),
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Renomeia um arquivo."""
|
|
123
|
+
_print_json(_run(drive.rename_file, file_id, new_name))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@app.command('update')
|
|
127
|
+
def update_cmd(
|
|
128
|
+
file_id: str = typer.Argument(...),
|
|
129
|
+
fields: List[str] = typer.Argument(
|
|
130
|
+
..., help="Pares chave=valor (ex.: name='Novo' description='ETL diário')."
|
|
131
|
+
),
|
|
132
|
+
) -> None:
|
|
133
|
+
"""Atualiza metadados arbitrários (name, description, starred, etc.)."""
|
|
134
|
+
body = {}
|
|
135
|
+
for raw in fields:
|
|
136
|
+
if '=' not in raw:
|
|
137
|
+
typer.secho(f'Argumento inválido: {raw!r} (esperado chave=valor)', err=True, fg=typer.colors.RED)
|
|
138
|
+
raise typer.Exit(code=2)
|
|
139
|
+
key, value = raw.split('=', 1)
|
|
140
|
+
body[key] = value
|
|
141
|
+
_print_json(_run(drive.update_metadata, file_id, **body))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@app.command('trash')
|
|
145
|
+
def trash_cmd(file_id: str = typer.Argument(...)) -> None:
|
|
146
|
+
"""Move um arquivo para a lixeira."""
|
|
147
|
+
_print_json(_run(drive.trash_file, file_id))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@app.command('untrash')
|
|
151
|
+
def untrash_cmd(file_id: str = typer.Argument(...)) -> None:
|
|
152
|
+
"""Restaura um arquivo da lixeira."""
|
|
153
|
+
_print_json(_run(drive.untrash_file, file_id))
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@app.command('delete')
|
|
157
|
+
def delete_cmd(
|
|
158
|
+
file_id: str = typer.Argument(...),
|
|
159
|
+
yes: bool = typer.Option(False, '--yes', '-y', help='Confirma exclusão permanente.'),
|
|
160
|
+
) -> None:
|
|
161
|
+
"""Apaga um arquivo permanentemente."""
|
|
162
|
+
if not yes:
|
|
163
|
+
typer.confirm(
|
|
164
|
+
f'Confirma exclusão PERMANENTE de {file_id}?', abort=True
|
|
165
|
+
)
|
|
166
|
+
_run(drive.delete_file, file_id)
|
|
167
|
+
typer.echo('ok')
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@app.command('empty-folder')
|
|
171
|
+
def empty_folder_cmd(
|
|
172
|
+
folder_id: str = typer.Argument(...),
|
|
173
|
+
yes: bool = typer.Option(False, '--yes', '-y'),
|
|
174
|
+
) -> None:
|
|
175
|
+
"""Apaga todos os arquivos diretamente contidos na pasta."""
|
|
176
|
+
if not yes:
|
|
177
|
+
typer.confirm(
|
|
178
|
+
f'Confirma esvaziamento de {folder_id}?', abort=True
|
|
179
|
+
)
|
|
180
|
+
deleted = _run(drive.empty_folder, folder_id)
|
|
181
|
+
typer.echo(f'arquivos removidos: {deleted}')
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@app.command('permissions')
|
|
185
|
+
def permissions_cmd(file_id: str = typer.Argument(...)) -> None:
|
|
186
|
+
"""Lista as permissões de um arquivo."""
|
|
187
|
+
_print_json(_run(drive.list_permissions, file_id))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@app.command('revisions')
|
|
191
|
+
def revisions_cmd(file_id: str = typer.Argument(...)) -> None:
|
|
192
|
+
"""Lista o histórico de revisões de um arquivo."""
|
|
193
|
+
_print_json(_run(drive.list_revisions, file_id))
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@app.command('mtime')
|
|
197
|
+
def mtime_cmd(file_id: str = typer.Argument(...)) -> None:
|
|
198
|
+
"""Mostra o ``modifiedTime`` (RFC 3339) de um arquivo."""
|
|
199
|
+
typer.echo(_run(drive.get_file_modification_time, file_id))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@sheets_app.command('export-df')
|
|
203
|
+
def export_df_cmd(
|
|
204
|
+
csv_path: str = typer.Argument(..., help='Caminho do CSV a enviar.'),
|
|
205
|
+
gsheet_name: str = typer.Argument(..., help='Nome do Google Sheet de destino.'),
|
|
206
|
+
sheet_name: str = typer.Argument(..., help='Nome da aba dentro do Sheet.'),
|
|
207
|
+
cell: str = typer.Option('A2', '--cell'),
|
|
208
|
+
value_input: str = typer.Option('RAW', '--value-input', help="'RAW' ou 'USER_ENTERED'."),
|
|
209
|
+
) -> None:
|
|
210
|
+
"""Lê um CSV local e escreve no Google Sheet indicado."""
|
|
211
|
+
import pandas as pd
|
|
212
|
+
|
|
213
|
+
df = pd.read_csv(csv_path)
|
|
214
|
+
_print_json(
|
|
215
|
+
_run(
|
|
216
|
+
sheets.export_dataframe_to_gsheet,
|
|
217
|
+
df,
|
|
218
|
+
gsheet_name,
|
|
219
|
+
sheet_name,
|
|
220
|
+
cell_address=cell,
|
|
221
|
+
value_input_option=value_input,
|
|
222
|
+
)
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
if __name__ == '__main__':
|
|
227
|
+
app()
|
gapi_tools/config.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Resolução de configuração e credenciais do pacote.
|
|
2
|
+
|
|
3
|
+
Estratégia de resolução do token (em ordem):
|
|
4
|
+
1. Variável de ambiente ``GAPI_TOOLS_TOKEN`` apontando para o JSON da
|
|
5
|
+
service account.
|
|
6
|
+
2. Arquivo ``.env`` no diretório de trabalho atual com chave ``GTOKEN``.
|
|
7
|
+
3. Arquivo ``.env`` em ``~/.config/gapi-tools/``.
|
|
8
|
+
|
|
9
|
+
O nome ``GTOKEN`` é interpretado como caminho relativo a ``~`` (home), preservando
|
|
10
|
+
o comportamento histórico do projeto.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Optional
|
|
18
|
+
|
|
19
|
+
from dotenv import dotenv_values
|
|
20
|
+
|
|
21
|
+
from .exceptions import ConfigError
|
|
22
|
+
|
|
23
|
+
ENV_VAR_TOKEN = 'GAPI_TOOLS_TOKEN'
|
|
24
|
+
ENV_FILE_KEY = 'GTOKEN'
|
|
25
|
+
|
|
26
|
+
SCOPES = (
|
|
27
|
+
'https://www.googleapis.com/auth/drive',
|
|
28
|
+
'https://www.googleapis.com/auth/drive.file',
|
|
29
|
+
'https://www.googleapis.com/auth/spreadsheets',
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _load_dotenv_token() -> Optional[Path]:
|
|
34
|
+
"""Procura ``GTOKEN`` em ``.env`` no cwd e em ``~/.config/gapi-tools/``."""
|
|
35
|
+
candidates = (
|
|
36
|
+
Path.cwd() / '.env',
|
|
37
|
+
Path.home() / '.config' / 'gapi-tools' / '.env',
|
|
38
|
+
)
|
|
39
|
+
for env_path in candidates:
|
|
40
|
+
if not env_path.is_file():
|
|
41
|
+
continue
|
|
42
|
+
values = dotenv_values(env_path)
|
|
43
|
+
token = values.get(ENV_FILE_KEY)
|
|
44
|
+
if token:
|
|
45
|
+
return Path.home() / token
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def resolve_token_path() -> Path:
|
|
50
|
+
"""Retorna o ``Path`` do arquivo JSON da service account.
|
|
51
|
+
|
|
52
|
+
Raises:
|
|
53
|
+
ConfigError: quando nenhuma fonte fornece um caminho válido.
|
|
54
|
+
"""
|
|
55
|
+
env_value = os.environ.get(ENV_VAR_TOKEN)
|
|
56
|
+
if env_value:
|
|
57
|
+
token_path = Path(env_value).expanduser()
|
|
58
|
+
else:
|
|
59
|
+
token_path = _load_dotenv_token()
|
|
60
|
+
|
|
61
|
+
if token_path is None:
|
|
62
|
+
raise ConfigError(
|
|
63
|
+
'Token da service account não encontrado. Defina '
|
|
64
|
+
f'{ENV_VAR_TOKEN}=/caminho/para/credenciais.json ou crie um '
|
|
65
|
+
f'.env com {ENV_FILE_KEY}=<arquivo-relativo-ao-home>.'
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
if not token_path.is_file():
|
|
69
|
+
raise ConfigError(
|
|
70
|
+
f'Arquivo de credenciais não existe: {token_path}'
|
|
71
|
+
)
|
|
72
|
+
return token_path
|
gapi_tools/drive.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""Operações sobre arquivos e pastas do Google Drive (API v3).
|
|
2
|
+
|
|
3
|
+
Todas as funções deste módulo levantam :class:`DriveOperationError` ou
|
|
4
|
+
:class:`RemoteFileNotFound` em vez de imprimir erros silenciosamente.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import logging
|
|
11
|
+
import mimetypes
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
15
|
+
|
|
16
|
+
from googleapiclient.errors import HttpError
|
|
17
|
+
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
|
|
18
|
+
|
|
19
|
+
from .auth import get_service
|
|
20
|
+
from .exceptions import DriveOperationError, RemoteFileNotFound
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
GSHEET_EXPORT_MIME = (
|
|
25
|
+
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
|
26
|
+
)
|
|
27
|
+
FOLDER_MIME = 'application/vnd.google-apps.folder'
|
|
28
|
+
EXCEL_EXTENSIONS = ('.xlsx', '.xls', '.xlsm', '.xlsb')
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _drive():
|
|
32
|
+
return get_service('drive', 'v3')
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _timestamp_suffix() -> str:
|
|
36
|
+
"""Retorna timestamp ``YYYYMMDD_HHMMSS`` para uso em nomes de arquivo."""
|
|
37
|
+
return datetime.now().strftime('%Y%m%d_%H%M%S')
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _insert_suffix_before_ext(path: Path, suffix: str) -> Path:
|
|
41
|
+
"""Insere ``suffix`` antes da extensão preservando o sufixo original."""
|
|
42
|
+
return path.with_name(f'{path.stem}{suffix}{path.suffix}')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _iter_file_pages(
|
|
46
|
+
query: Optional[str] = None,
|
|
47
|
+
page_size: int = 100,
|
|
48
|
+
fields: str = 'nextPageToken, files(id, name, mimeType, modifiedTime)',
|
|
49
|
+
) -> Iterator[Dict[str, Any]]:
|
|
50
|
+
"""Itera todos os arquivos respeitando ``nextPageToken``."""
|
|
51
|
+
service = _drive()
|
|
52
|
+
page_token: Optional[str] = None
|
|
53
|
+
while True:
|
|
54
|
+
params: Dict[str, Any] = {
|
|
55
|
+
'pageSize': page_size,
|
|
56
|
+
'fields': fields,
|
|
57
|
+
'supportsAllDrives': True,
|
|
58
|
+
'includeItemsFromAllDrives': True,
|
|
59
|
+
}
|
|
60
|
+
if query:
|
|
61
|
+
params['q'] = query
|
|
62
|
+
if page_token:
|
|
63
|
+
params['pageToken'] = page_token
|
|
64
|
+
response = service.files().list(**params).execute()
|
|
65
|
+
for item in response.get('files', []):
|
|
66
|
+
yield item
|
|
67
|
+
page_token = response.get('nextPageToken')
|
|
68
|
+
if not page_token:
|
|
69
|
+
break
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def list_files(page_size: int = 100) -> Dict[str, str]:
|
|
73
|
+
"""Lista arquivos visíveis e retorna dicionário ``{nome: id}``.
|
|
74
|
+
|
|
75
|
+
Mantém compatibilidade com a API legada. Para casos com nomes duplicados,
|
|
76
|
+
prefira :func:`list_files_detailed`.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
page_size: Tamanho de página da requisição à API.
|
|
80
|
+
"""
|
|
81
|
+
try:
|
|
82
|
+
return {
|
|
83
|
+
item['name']: item['id']
|
|
84
|
+
for item in _iter_file_pages(page_size=page_size)
|
|
85
|
+
}
|
|
86
|
+
except HttpError as error:
|
|
87
|
+
raise DriveOperationError(f'Falha ao listar arquivos: {error}') from error
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def list_files_detailed(
|
|
91
|
+
query: Optional[str] = None, page_size: int = 100
|
|
92
|
+
) -> List[Dict[str, Any]]:
|
|
93
|
+
"""Lista arquivos com metadados completos, suportando query do Drive.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
query: Expressão ``q`` da API (ex.: ``"'<folder_id>' in parents"``).
|
|
97
|
+
page_size: Tamanho de página.
|
|
98
|
+
"""
|
|
99
|
+
try:
|
|
100
|
+
return list(_iter_file_pages(query=query, page_size=page_size))
|
|
101
|
+
except HttpError as error:
|
|
102
|
+
raise DriveOperationError(f'Falha ao listar arquivos: {error}') from error
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def find_file_id(name: str) -> str:
|
|
106
|
+
"""Retorna o ``id`` do primeiro arquivo cujo nome bate exatamente.
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
RemoteFileNotFound: se nenhum arquivo com esse nome for encontrado.
|
|
110
|
+
"""
|
|
111
|
+
safe_name = name.replace("'", "\\'")
|
|
112
|
+
matches = list_files_detailed(query=f"name = '{safe_name}'", page_size=10)
|
|
113
|
+
if not matches:
|
|
114
|
+
raise RemoteFileNotFound(f'Arquivo não encontrado no Drive: {name!r}')
|
|
115
|
+
return matches[0]['id']
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _save_bytes(buffer: io.BytesIO, destination: Path) -> Path:
|
|
119
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
destination.write_bytes(buffer.getvalue())
|
|
121
|
+
return destination
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _download_media(file_id: str, destination: Path, export: bool) -> Path:
|
|
125
|
+
service = _drive()
|
|
126
|
+
try:
|
|
127
|
+
if export:
|
|
128
|
+
request = service.files().export_media(
|
|
129
|
+
fileId=file_id, mimeType=GSHEET_EXPORT_MIME
|
|
130
|
+
)
|
|
131
|
+
else:
|
|
132
|
+
request = service.files().get_media(
|
|
133
|
+
fileId=file_id, supportsAllDrives=True
|
|
134
|
+
)
|
|
135
|
+
buffer = io.BytesIO()
|
|
136
|
+
downloader = MediaIoBaseDownload(buffer, request)
|
|
137
|
+
done = False
|
|
138
|
+
while not done:
|
|
139
|
+
status, done = downloader.next_chunk()
|
|
140
|
+
logger.info('Download %d%%.', int(status.progress() * 100))
|
|
141
|
+
except HttpError as error:
|
|
142
|
+
raise DriveOperationError(
|
|
143
|
+
f'Falha ao baixar arquivo {file_id!r}: {error}'
|
|
144
|
+
) from error
|
|
145
|
+
return _save_bytes(buffer, destination)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def download_spreadsheet(
|
|
149
|
+
file_name: str,
|
|
150
|
+
folder: str = 'outputs',
|
|
151
|
+
with_date: bool = False,
|
|
152
|
+
) -> Path:
|
|
153
|
+
"""Baixa uma planilha (Excel ou Google Sheets) para a pasta indicada.
|
|
154
|
+
|
|
155
|
+
Quando o nome termina em ``.xlsx`` / ``.xls`` / ``.xlsm`` / ``.xlsb``, baixa
|
|
156
|
+
o binário diretamente. Caso contrário, exporta um Google Sheet como
|
|
157
|
+
``.xlsx``. Se ``with_date`` for ``True``, o timestamp é inserido antes da
|
|
158
|
+
extensão (preservando o tipo do arquivo).
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
file_name: Nome do arquivo no Drive.
|
|
162
|
+
folder: Pasta local de destino.
|
|
163
|
+
with_date: Se ``True``, anexa timestamp ao nome de saída.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
Caminho completo do arquivo gravado em disco.
|
|
167
|
+
"""
|
|
168
|
+
file_id = find_file_id(file_name)
|
|
169
|
+
suffix = '_' + _timestamp_suffix() if with_date else ''
|
|
170
|
+
output_dir = Path(folder)
|
|
171
|
+
|
|
172
|
+
is_excel_native = file_name.lower().endswith(EXCEL_EXTENSIONS)
|
|
173
|
+
if is_excel_native:
|
|
174
|
+
base = output_dir / file_name
|
|
175
|
+
destination = _insert_suffix_before_ext(base, suffix) if suffix else base
|
|
176
|
+
return _download_media(file_id, destination, export=False)
|
|
177
|
+
|
|
178
|
+
base = output_dir / f'{file_name}.xlsx'
|
|
179
|
+
destination = _insert_suffix_before_ext(base, suffix) if suffix else base
|
|
180
|
+
return _download_media(file_id, destination, export=True)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def upload_file(
|
|
184
|
+
folder_id: str,
|
|
185
|
+
file_path: str,
|
|
186
|
+
file_name: Optional[str] = None,
|
|
187
|
+
mimetype: Optional[str] = None,
|
|
188
|
+
) -> Dict[str, Any]:
|
|
189
|
+
"""Faz upload de um arquivo local para uma pasta do Drive.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
folder_id: ID da pasta de destino.
|
|
193
|
+
file_path: Caminho do arquivo local.
|
|
194
|
+
file_name: Nome a usar no Drive. Se omitido, usa o nome do arquivo local.
|
|
195
|
+
mimetype: MIME type. Se omitido, é inferido por
|
|
196
|
+
:func:`mimetypes.guess_type`.
|
|
197
|
+
"""
|
|
198
|
+
source = Path(file_path)
|
|
199
|
+
if not source.is_file():
|
|
200
|
+
raise FileNotFoundError(f'Arquivo local não existe: {source}')
|
|
201
|
+
name = file_name or source.name
|
|
202
|
+
guessed, _ = mimetypes.guess_type(str(source))
|
|
203
|
+
media = MediaFileUpload(
|
|
204
|
+
str(source),
|
|
205
|
+
mimetype=mimetype or guessed or 'application/octet-stream',
|
|
206
|
+
resumable=True,
|
|
207
|
+
)
|
|
208
|
+
body = {'name': name, 'parents': [folder_id]}
|
|
209
|
+
try:
|
|
210
|
+
return (
|
|
211
|
+
_drive()
|
|
212
|
+
.files()
|
|
213
|
+
.create(body=body, media_body=media, fields='id, name, parents')
|
|
214
|
+
.execute()
|
|
215
|
+
)
|
|
216
|
+
except HttpError as error:
|
|
217
|
+
raise DriveOperationError(f'Falha no upload: {error}') from error
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def empty_folder(folder_id: str) -> int:
|
|
221
|
+
"""Apaga todos os arquivos diretamente contidos em ``folder_id``.
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
Quantidade de arquivos removidos.
|
|
225
|
+
"""
|
|
226
|
+
deleted = 0
|
|
227
|
+
service = _drive()
|
|
228
|
+
try:
|
|
229
|
+
files = list_files_detailed(
|
|
230
|
+
query=f"'{folder_id}' in parents", page_size=1000
|
|
231
|
+
)
|
|
232
|
+
for item in files:
|
|
233
|
+
service.files().delete(fileId=item['id']).execute()
|
|
234
|
+
deleted += 1
|
|
235
|
+
except HttpError as error:
|
|
236
|
+
raise DriveOperationError(
|
|
237
|
+
f'Falha ao esvaziar pasta {folder_id!r}: {error}'
|
|
238
|
+
) from error
|
|
239
|
+
return deleted
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def get_file_modification_time(file_id: str) -> str:
|
|
243
|
+
"""Retorna o ``modifiedTime`` (RFC 3339) do arquivo."""
|
|
244
|
+
try:
|
|
245
|
+
file = (
|
|
246
|
+
_drive()
|
|
247
|
+
.files()
|
|
248
|
+
.get(fileId=file_id, fields='modifiedTime', supportsAllDrives=True)
|
|
249
|
+
.execute()
|
|
250
|
+
)
|
|
251
|
+
return file['modifiedTime']
|
|
252
|
+
except HttpError as error:
|
|
253
|
+
raise DriveOperationError(
|
|
254
|
+
f'Falha ao obter modifiedTime de {file_id!r}: {error}'
|
|
255
|
+
) from error
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def move_file(
|
|
259
|
+
file_id: str,
|
|
260
|
+
new_parent_id: str,
|
|
261
|
+
old_parent_id: Optional[str] = None,
|
|
262
|
+
) -> Dict[str, Any]:
|
|
263
|
+
"""Move um arquivo para outra pasta.
|
|
264
|
+
|
|
265
|
+
Se ``old_parent_id`` não for informado, todos os parents atuais são
|
|
266
|
+
removidos e substituídos pelo novo.
|
|
267
|
+
"""
|
|
268
|
+
service = _drive()
|
|
269
|
+
try:
|
|
270
|
+
if old_parent_id is None:
|
|
271
|
+
current = (
|
|
272
|
+
service.files().get(fileId=file_id, fields='parents').execute()
|
|
273
|
+
)
|
|
274
|
+
old_parents = ','.join(current.get('parents', []))
|
|
275
|
+
else:
|
|
276
|
+
old_parents = old_parent_id
|
|
277
|
+
return (
|
|
278
|
+
service.files()
|
|
279
|
+
.update(
|
|
280
|
+
fileId=file_id,
|
|
281
|
+
addParents=new_parent_id,
|
|
282
|
+
removeParents=old_parents,
|
|
283
|
+
fields='id, parents',
|
|
284
|
+
)
|
|
285
|
+
.execute()
|
|
286
|
+
)
|
|
287
|
+
except HttpError as error:
|
|
288
|
+
raise DriveOperationError(
|
|
289
|
+
f'Falha ao mover {file_id!r}: {error}'
|
|
290
|
+
) from error
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def create_folder(
|
|
294
|
+
name: str, parent_id: Optional[str] = None
|
|
295
|
+
) -> Dict[str, Any]:
|
|
296
|
+
"""Cria uma pasta vazia no Drive."""
|
|
297
|
+
body: Dict[str, Any] = {'name': name, 'mimeType': FOLDER_MIME}
|
|
298
|
+
if parent_id:
|
|
299
|
+
body['parents'] = [parent_id]
|
|
300
|
+
try:
|
|
301
|
+
return (
|
|
302
|
+
_drive()
|
|
303
|
+
.files()
|
|
304
|
+
.create(body=body, fields='id, name, parents')
|
|
305
|
+
.execute()
|
|
306
|
+
)
|
|
307
|
+
except HttpError as error:
|
|
308
|
+
raise DriveOperationError(
|
|
309
|
+
f'Falha ao criar pasta {name!r}: {error}'
|
|
310
|
+
) from error
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def create_file(
|
|
314
|
+
name: str,
|
|
315
|
+
parent_id: Optional[str] = None,
|
|
316
|
+
mime_type: str = 'application/octet-stream',
|
|
317
|
+
content: bytes = b'',
|
|
318
|
+
) -> Dict[str, Any]:
|
|
319
|
+
"""Cria um arquivo (vazio ou com conteúdo) diretamente no Drive."""
|
|
320
|
+
body: Dict[str, Any] = {'name': name, 'mimeType': mime_type}
|
|
321
|
+
if parent_id:
|
|
322
|
+
body['parents'] = [parent_id]
|
|
323
|
+
media = None
|
|
324
|
+
if content:
|
|
325
|
+
from googleapiclient.http import MediaIoBaseUpload
|
|
326
|
+
|
|
327
|
+
media = MediaIoBaseUpload(io.BytesIO(content), mimetype=mime_type)
|
|
328
|
+
try:
|
|
329
|
+
request = _drive().files().create(
|
|
330
|
+
body=body,
|
|
331
|
+
media_body=media,
|
|
332
|
+
fields='id, name, parents, mimeType',
|
|
333
|
+
)
|
|
334
|
+
return request.execute()
|
|
335
|
+
except HttpError as error:
|
|
336
|
+
raise DriveOperationError(
|
|
337
|
+
f'Falha ao criar arquivo {name!r}: {error}'
|
|
338
|
+
) from error
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def copy_file(
|
|
342
|
+
file_id: str,
|
|
343
|
+
new_name: Optional[str] = None,
|
|
344
|
+
parent_id: Optional[str] = None,
|
|
345
|
+
) -> Dict[str, Any]:
|
|
346
|
+
"""Duplica um arquivo, opcionalmente renomeando e/ou movendo."""
|
|
347
|
+
body: Dict[str, Any] = {}
|
|
348
|
+
if new_name:
|
|
349
|
+
body['name'] = new_name
|
|
350
|
+
if parent_id:
|
|
351
|
+
body['parents'] = [parent_id]
|
|
352
|
+
try:
|
|
353
|
+
return (
|
|
354
|
+
_drive()
|
|
355
|
+
.files()
|
|
356
|
+
.copy(fileId=file_id, body=body, fields='id, name, parents')
|
|
357
|
+
.execute()
|
|
358
|
+
)
|
|
359
|
+
except HttpError as error:
|
|
360
|
+
raise DriveOperationError(
|
|
361
|
+
f'Falha ao copiar {file_id!r}: {error}'
|
|
362
|
+
) from error
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def rename_file(file_id: str, new_name: str) -> Dict[str, Any]:
|
|
366
|
+
"""Renomeia um arquivo (atalho de :func:`update_metadata`)."""
|
|
367
|
+
return update_metadata(file_id, name=new_name)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def update_metadata(file_id: str, **fields: Any) -> Dict[str, Any]:
|
|
371
|
+
"""Atualiza metadados editáveis (``name``, ``description``, ``starred``...)."""
|
|
372
|
+
if not fields:
|
|
373
|
+
raise ValueError('Forneça pelo menos um campo para atualizar.')
|
|
374
|
+
try:
|
|
375
|
+
return (
|
|
376
|
+
_drive()
|
|
377
|
+
.files()
|
|
378
|
+
.update(
|
|
379
|
+
fileId=file_id,
|
|
380
|
+
body=dict(fields),
|
|
381
|
+
fields='id, name, description',
|
|
382
|
+
)
|
|
383
|
+
.execute()
|
|
384
|
+
)
|
|
385
|
+
except HttpError as error:
|
|
386
|
+
raise DriveOperationError(
|
|
387
|
+
f'Falha ao atualizar metadados de {file_id!r}: {error}'
|
|
388
|
+
) from error
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def trash_file(file_id: str) -> Dict[str, Any]:
|
|
392
|
+
"""Move o arquivo para a lixeira do Drive."""
|
|
393
|
+
return update_metadata(file_id, trashed=True)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def untrash_file(file_id: str) -> Dict[str, Any]:
|
|
397
|
+
"""Restaura o arquivo da lixeira."""
|
|
398
|
+
return update_metadata(file_id, trashed=False)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def delete_file(file_id: str) -> None:
|
|
402
|
+
"""Apaga um arquivo permanentemente (ignora a lixeira)."""
|
|
403
|
+
try:
|
|
404
|
+
_drive().files().delete(fileId=file_id).execute()
|
|
405
|
+
except HttpError as error:
|
|
406
|
+
raise DriveOperationError(
|
|
407
|
+
f'Falha ao apagar {file_id!r}: {error}'
|
|
408
|
+
) from error
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def list_permissions(file_id: str) -> List[Dict[str, Any]]:
|
|
412
|
+
"""Lista as permissões (quem tem acesso) de um arquivo."""
|
|
413
|
+
try:
|
|
414
|
+
response = (
|
|
415
|
+
_drive()
|
|
416
|
+
.permissions()
|
|
417
|
+
.list(
|
|
418
|
+
fileId=file_id,
|
|
419
|
+
fields='permissions(id, type, role, emailAddress, displayName)',
|
|
420
|
+
)
|
|
421
|
+
.execute()
|
|
422
|
+
)
|
|
423
|
+
return response.get('permissions', [])
|
|
424
|
+
except HttpError as error:
|
|
425
|
+
raise DriveOperationError(
|
|
426
|
+
f'Falha ao listar permissões de {file_id!r}: {error}'
|
|
427
|
+
) from error
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def list_revisions(file_id: str) -> List[Dict[str, Any]]:
|
|
431
|
+
"""Retorna o histórico de revisões de um arquivo."""
|
|
432
|
+
try:
|
|
433
|
+
response = (
|
|
434
|
+
_drive()
|
|
435
|
+
.revisions()
|
|
436
|
+
.list(
|
|
437
|
+
fileId=file_id,
|
|
438
|
+
fields='revisions(id, modifiedTime, lastModifyingUser, size)',
|
|
439
|
+
)
|
|
440
|
+
.execute()
|
|
441
|
+
)
|
|
442
|
+
return response.get('revisions', [])
|
|
443
|
+
except HttpError as error:
|
|
444
|
+
raise DriveOperationError(
|
|
445
|
+
f'Falha ao listar revisões de {file_id!r}: {error}'
|
|
446
|
+
) from error
|
gapi_tools/exceptions.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Exceções tipadas do pacote gapi_tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class GoogleApiUtilsError(Exception):
|
|
7
|
+
"""Erro base do pacote."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ConfigError(GoogleApiUtilsError):
|
|
11
|
+
"""Configuração ausente ou inválida (token, .env, etc.)."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RemoteFileNotFound(GoogleApiUtilsError):
|
|
15
|
+
"""Arquivo procurado não existe no Google Drive."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DriveOperationError(GoogleApiUtilsError):
|
|
19
|
+
"""Falha durante uma chamada à API do Drive/Sheets."""
|
gapi_tools/sheets.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Operações específicas do Google Sheets (API v4)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from googleapiclient.errors import HttpError
|
|
8
|
+
|
|
9
|
+
from .auth import get_service
|
|
10
|
+
from .drive import find_file_id
|
|
11
|
+
from .exceptions import DriveOperationError
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _sheets():
|
|
18
|
+
return get_service('sheets', 'v4').spreadsheets()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def export_dataframe_to_gsheet(
|
|
22
|
+
dataframe: 'pd.DataFrame',
|
|
23
|
+
gsheet_name: str,
|
|
24
|
+
sheet_name: str,
|
|
25
|
+
cell_address: str = 'A2',
|
|
26
|
+
value_input_option: str = 'RAW',
|
|
27
|
+
) -> Dict[str, Any]:
|
|
28
|
+
"""Escreve um DataFrame em um Google Sheet existente.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
dataframe: DataFrame com os dados.
|
|
32
|
+
gsheet_name: Nome do arquivo Sheets no Drive (deve ser único).
|
|
33
|
+
sheet_name: Nome da aba dentro do arquivo.
|
|
34
|
+
cell_address: Célula inicial (ex.: ``'A2'``).
|
|
35
|
+
value_input_option: ``'RAW'`` ou ``'USER_ENTERED'``.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Resposta da API (``updatedRange``, ``updatedRows`` etc.).
|
|
39
|
+
"""
|
|
40
|
+
gsheet_id = find_file_id(gsheet_name)
|
|
41
|
+
body = {'values': dataframe.values.tolist()}
|
|
42
|
+
range_name = f'{sheet_name}!{cell_address}'
|
|
43
|
+
try:
|
|
44
|
+
return (
|
|
45
|
+
_sheets()
|
|
46
|
+
.values()
|
|
47
|
+
.update(
|
|
48
|
+
spreadsheetId=gsheet_id,
|
|
49
|
+
range=range_name,
|
|
50
|
+
valueInputOption=value_input_option,
|
|
51
|
+
body=body,
|
|
52
|
+
)
|
|
53
|
+
.execute()
|
|
54
|
+
)
|
|
55
|
+
except HttpError as error:
|
|
56
|
+
raise DriveOperationError(
|
|
57
|
+
f'Falha ao escrever em {gsheet_name!r}/{sheet_name!r}: {error}'
|
|
58
|
+
) from error
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gapi-tools
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Utilitários para automação de tarefas no Google Drive e Google Sheets via service account.
|
|
5
|
+
Project-URL: Repository, https://github.com/bernarducs/gapi-tools
|
|
6
|
+
Author-email: Bernardo Silva <bernarducs@gmail.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: automation,cli,google-drive,google-sheets
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
18
|
+
Classifier: Topic :: Office/Business
|
|
19
|
+
Classifier: Topic :: Utilities
|
|
20
|
+
Requires-Python: <3.9,>=3.8
|
|
21
|
+
Requires-Dist: cryptography<43,>=38.0.3
|
|
22
|
+
Requires-Dist: google-api-python-client<3,>=2.99
|
|
23
|
+
Requires-Dist: google-auth-httplib2<0.3,>=0.1.1
|
|
24
|
+
Requires-Dist: google-auth-oauthlib<2,>=1.1
|
|
25
|
+
Requires-Dist: google-auth<3,>=2.23
|
|
26
|
+
Requires-Dist: pandas<2.1,>=2.0
|
|
27
|
+
Requires-Dist: python-dotenv<2,>=1.0
|
|
28
|
+
Requires-Dist: typer<0.13,>=0.12
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest-mock<4,>=3; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest<9,>=7; extra == 'dev'
|
|
32
|
+
Requires-Dist: ruff<1,>=0.5; extra == 'dev'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# gapi-tools
|
|
36
|
+
|
|
37
|
+
Utilitários em Python para automatizar tarefas no Google Drive (v3) e Google Sheets (v4) via *service account*. Inclui uma CLI unificada (`gapi`) e uma API programática.
|
|
38
|
+
|
|
39
|
+
## Funcionalidades
|
|
40
|
+
|
|
41
|
+
- Listar arquivos (resumido ou detalhado) e localizar por nome.
|
|
42
|
+
- Download de planilhas (preserva extensão `.xlsx`/`.xls`/`.xlsm`/`.xlsb` ou exporta Google Sheets como `.xlsx`).
|
|
43
|
+
- Upload de arquivos com *mimetype* detectado automaticamente.
|
|
44
|
+
- Mover, copiar, renomear, criar pasta/arquivo.
|
|
45
|
+
- Atualizar metadados, mandar para a lixeira, restaurar, apagar.
|
|
46
|
+
- Esvaziar pasta (com paginação).
|
|
47
|
+
- Listar permissões e revisões.
|
|
48
|
+
- Ler/escrever planilhas a partir de um `pandas.DataFrame`.
|
|
49
|
+
|
|
50
|
+
## Requisitos
|
|
51
|
+
|
|
52
|
+
- Python **3.8.x** (cap por compatibilidade com o servidor de produção; veja seção abaixo).
|
|
53
|
+
- Service account no Google Cloud com APIs **Drive** e **Sheets** habilitadas e arquivo JSON de credenciais.
|
|
54
|
+
|
|
55
|
+
## Instalação
|
|
56
|
+
|
|
57
|
+
Em ambiente de desenvolvimento (Linux/WSL):
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
uv sync --extra dev
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Em produção (Windows Server):
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install .
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Após instalar, o comando `gapi` fica disponível no `PATH`.
|
|
70
|
+
|
|
71
|
+
## Configuração
|
|
72
|
+
|
|
73
|
+
Aponte para o JSON da service account de uma das três formas (resolvidas nessa ordem):
|
|
74
|
+
|
|
75
|
+
1. variável de ambiente `GAPI_TOOLS_TOKEN` com o caminho absoluto do arquivo JSON;
|
|
76
|
+
2. arquivo `.env` no diretório atual contendo `GTOKEN=/caminho/para/credenciais.json`;
|
|
77
|
+
3. arquivo `.env` em `~/.config/gapi-tools/`.
|
|
78
|
+
|
|
79
|
+
A planilha/arquivo precisa estar **compartilhado** com o e-mail da service account.
|
|
80
|
+
|
|
81
|
+
## Uso da CLI
|
|
82
|
+
|
|
83
|
+
```text
|
|
84
|
+
gapi list # nome -> id
|
|
85
|
+
gapi list --detailed --query "name = 'foo'" # JSON com metadados
|
|
86
|
+
gapi download minha-planilha --folder ./out --with-date
|
|
87
|
+
gapi upload ./local.csv FOLDER_ID --name remoto.csv
|
|
88
|
+
gapi move FILE_ID NEW_PARENT_ID --old-parent OLD
|
|
89
|
+
gapi copy FILE_ID --name "Cópia"
|
|
90
|
+
gapi create-folder Nova --parent root
|
|
91
|
+
gapi rename FILE_ID novo-nome
|
|
92
|
+
gapi update FILE_ID name=Foo description=Bar
|
|
93
|
+
gapi trash FILE_ID
|
|
94
|
+
gapi untrash FILE_ID
|
|
95
|
+
gapi delete FILE_ID --yes
|
|
96
|
+
gapi empty-folder FOLDER_ID --yes
|
|
97
|
+
gapi permissions FILE_ID
|
|
98
|
+
gapi revisions FILE_ID
|
|
99
|
+
gapi mtime FILE_ID
|
|
100
|
+
gapi sheets export-df dados.csv minha-planilha Plan1 --cell A2
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`gapi --help` mostra todos os comandos; cada subcomando tem `--help` próprio.
|
|
104
|
+
|
|
105
|
+
## Uso programático
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from gapi_tools import drive, sheets
|
|
109
|
+
import pandas as pd
|
|
110
|
+
|
|
111
|
+
# listar e baixar
|
|
112
|
+
files = drive.list_files_detailed(query="mimeType = 'application/vnd.google-apps.spreadsheet'")
|
|
113
|
+
out = drive.download_spreadsheet('minha-planilha', folder='./out', with_date=True)
|
|
114
|
+
|
|
115
|
+
# upload e organização
|
|
116
|
+
drive.upload_file('FOLDER_ID', './relatorio.xlsx')
|
|
117
|
+
drive.move_file('FILE_ID', 'NEW_PARENT_ID')
|
|
118
|
+
drive.rename_file('FILE_ID', 'novo-nome.xlsx')
|
|
119
|
+
|
|
120
|
+
# escrever DataFrame numa aba
|
|
121
|
+
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
|
|
122
|
+
sheets.export_dataframe_to_gsheet(df, 'minha-planilha', 'Plan1', cell_address='A2')
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Setup do servidor Windows Server 2008 R2
|
|
126
|
+
|
|
127
|
+
Este pacote é distribuído para um Windows Server 2008 R2 com Python **3.8.1**. Antes de instalar:
|
|
128
|
+
|
|
129
|
+
1. **Atualizações** — recomendado aplicar `KB3140245` ("Update to enable TLS 1.1 and TLS 1.2 as default secure protocols in WinHTTP").
|
|
130
|
+
2. **Habilitar TLS 1.2** no registro (chamadas à API do Google falham silenciosamente sem isso). Em `regedit`, criar/editar:
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client
|
|
134
|
+
Enabled = 1 (DWORD)
|
|
135
|
+
DisabledByDefault = 0 (DWORD)
|
|
136
|
+
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server
|
|
137
|
+
Enabled = 1 (DWORD)
|
|
138
|
+
DisabledByDefault = 0 (DWORD)
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Reiniciar após alterar.
|
|
142
|
+
3. **Verificar TLS** — após reiniciar:
|
|
143
|
+
|
|
144
|
+
```
|
|
145
|
+
python -c "import urllib.request; print(urllib.request.urlopen('https://www.googleapis.com').status)"
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Se falhar com erro de SSL, TLS 1.2 não está ativo.
|
|
149
|
+
4. **Instalar o pacote** — todas as dependências têm wheels `cp38-win_amd64`, então não é necessário compilador:
|
|
150
|
+
|
|
151
|
+
```
|
|
152
|
+
pip install .
|
|
153
|
+
```
|
|
154
|
+
5. **Sanity check** — `gapi --help` deve listar todos os subcomandos sem `ImportError`.
|
|
155
|
+
|
|
156
|
+
> Nota: o pacote evita `rich` (usa `typer` puro, não `typer[all]`) para funcionar bem no `cmd.exe` legado em cp1252.
|
|
157
|
+
|
|
158
|
+
## Testes
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
pytest -v
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Todos os testes usam mocks da Google API e não dependem de rede ou credenciais reais.
|
|
165
|
+
|
|
166
|
+
## Lint e formatação
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
ruff check .
|
|
170
|
+
ruff format .
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Licença
|
|
174
|
+
|
|
175
|
+
MIT — veja [LICENSE](LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
gapi_tools/__init__.py,sha256=Fkynjmm3SXjmBpaQC6x26ID1rBTYA-NEhprodCwoz3w,2291
|
|
2
|
+
gapi_tools/auth.py,sha256=gkA2tWvVmWhifiStXZ5swrTkq2DYrUjh9QuQrRaSkyU,1580
|
|
3
|
+
gapi_tools/cli.py,sha256=jz7HRgXBPz3ZblCmUCZE77x4pKw_dOMckaX5WsDoyh8,7369
|
|
4
|
+
gapi_tools/config.py,sha256=j6G508MNrfRF5-c5XFzK62tqT_BOoZIVLj1bxIzcaDc,2104
|
|
5
|
+
gapi_tools/drive.py,sha256=WGRDgC89btG-4-5aM10eZo-iSdHr_jWNf2myOPhGSAg,13993
|
|
6
|
+
gapi_tools/exceptions.py,sha256=HwNRUIEmZ3oWBC7GZqkZ2NMLaRfq_C8EEw7JZpbXjwo,479
|
|
7
|
+
gapi_tools/sheets.py,sha256=-813M7faaVH2kRq4c-sB76NH3zHLbihch1Bspsh5rdk,1636
|
|
8
|
+
gapi_tools-0.2.0.dist-info/METADATA,sha256=YTCif6zW-PeVoiXoBphh4tuAe-a1-qtJY0jB_iIBgHU,5901
|
|
9
|
+
gapi_tools-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
10
|
+
gapi_tools-0.2.0.dist-info/entry_points.txt,sha256=oiHgRlm6z4xMm7H5u_Z-7VH-3mRmc0d39TB1j8eHu4s,44
|
|
11
|
+
gapi_tools-0.2.0.dist-info/licenses/LICENSE,sha256=OJPYiduC9UsZcjYS4SYd8jm5otSKyEk79XAEUncnN48,1071
|
|
12
|
+
gapi_tools-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bernardo Silva
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|