gapi-tools 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gapi_tools-0.2.0/.envtemplate +1 -0
- gapi_tools-0.2.0/.gitignore +165 -0
- gapi_tools-0.2.0/.python-version +1 -0
- gapi_tools-0.2.0/LICENSE +21 -0
- gapi_tools-0.2.0/PKG-INFO +175 -0
- gapi_tools-0.2.0/README.md +141 -0
- gapi_tools-0.2.0/gapi_tools/__init__.py +100 -0
- gapi_tools-0.2.0/gapi_tools/auth.py +50 -0
- gapi_tools-0.2.0/gapi_tools/cli.py +227 -0
- gapi_tools-0.2.0/gapi_tools/config.py +72 -0
- gapi_tools-0.2.0/gapi_tools/drive.py +446 -0
- gapi_tools-0.2.0/gapi_tools/exceptions.py +19 -0
- gapi_tools-0.2.0/gapi_tools/sheets.py +58 -0
- gapi_tools-0.2.0/pyproject.toml +66 -0
- gapi_tools-0.2.0/requirements.txt +6 -0
- gapi_tools-0.2.0/tests/__init__.py +0 -0
- gapi_tools-0.2.0/tests/conftest.py +39 -0
- gapi_tools-0.2.0/tests/test_cli.py +169 -0
- gapi_tools-0.2.0/tests/test_drive.py +243 -0
- gapi_tools-0.2.0/tests/test_sheets.py +52 -0
- gapi_tools-0.2.0/uv.lock +637 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
GTOKEN=XXXXXXX.json
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
outputs/
|
|
2
|
+
|
|
3
|
+
# Byte-compiled / optimized / DLL files
|
|
4
|
+
__pycache__/
|
|
5
|
+
*.py[cod]
|
|
6
|
+
*$py.class
|
|
7
|
+
|
|
8
|
+
# C extensions
|
|
9
|
+
*.so
|
|
10
|
+
|
|
11
|
+
# Distribution / packaging
|
|
12
|
+
.Python
|
|
13
|
+
build/
|
|
14
|
+
develop-eggs/
|
|
15
|
+
dist/
|
|
16
|
+
downloads/
|
|
17
|
+
eggs/
|
|
18
|
+
.eggs/
|
|
19
|
+
lib/
|
|
20
|
+
lib64/
|
|
21
|
+
parts/
|
|
22
|
+
sdist/
|
|
23
|
+
var/
|
|
24
|
+
wheels/
|
|
25
|
+
share/python-wheels/
|
|
26
|
+
*.egg-info/
|
|
27
|
+
.installed.cfg
|
|
28
|
+
*.egg
|
|
29
|
+
MANIFEST
|
|
30
|
+
|
|
31
|
+
# PyInstaller
|
|
32
|
+
# Usually these files are written by a python script from a template
|
|
33
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
34
|
+
*.manifest
|
|
35
|
+
*.spec
|
|
36
|
+
|
|
37
|
+
# Installer logs
|
|
38
|
+
pip-log.txt
|
|
39
|
+
pip-delete-this-directory.txt
|
|
40
|
+
|
|
41
|
+
# Unit test / coverage reports
|
|
42
|
+
htmlcov/
|
|
43
|
+
.tox/
|
|
44
|
+
.nox/
|
|
45
|
+
.coverage
|
|
46
|
+
.coverage.*
|
|
47
|
+
.cache
|
|
48
|
+
nosetests.xml
|
|
49
|
+
coverage.xml
|
|
50
|
+
*.cover
|
|
51
|
+
*.py,cover
|
|
52
|
+
.hypothesis/
|
|
53
|
+
.pytest_cache/
|
|
54
|
+
cover/
|
|
55
|
+
|
|
56
|
+
# Translations
|
|
57
|
+
*.mo
|
|
58
|
+
*.pot
|
|
59
|
+
|
|
60
|
+
# Django stuff:
|
|
61
|
+
*.log
|
|
62
|
+
local_settings.py
|
|
63
|
+
db.sqlite3
|
|
64
|
+
db.sqlite3-journal
|
|
65
|
+
|
|
66
|
+
# Flask stuff:
|
|
67
|
+
instance/
|
|
68
|
+
.webassets-cache
|
|
69
|
+
|
|
70
|
+
# Scrapy stuff:
|
|
71
|
+
.scrapy
|
|
72
|
+
|
|
73
|
+
# Sphinx documentation
|
|
74
|
+
docs/_build/
|
|
75
|
+
|
|
76
|
+
# PyBuilder
|
|
77
|
+
.pybuilder/
|
|
78
|
+
target/
|
|
79
|
+
|
|
80
|
+
# Jupyter Notebook
|
|
81
|
+
.ipynb_checkpoints
|
|
82
|
+
|
|
83
|
+
# IPython
|
|
84
|
+
profile_default/
|
|
85
|
+
ipython_config.py
|
|
86
|
+
|
|
87
|
+
# pyenv
|
|
88
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
89
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
90
|
+
# .python-version
|
|
91
|
+
|
|
92
|
+
# pipenv
|
|
93
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
94
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
95
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
96
|
+
# install all needed dependencies.
|
|
97
|
+
#Pipfile.lock
|
|
98
|
+
|
|
99
|
+
# poetry
|
|
100
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
101
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
102
|
+
# commonly ignored for libraries.
|
|
103
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
104
|
+
#poetry.lock
|
|
105
|
+
|
|
106
|
+
# pdm
|
|
107
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
108
|
+
#pdm.lock
|
|
109
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
110
|
+
# in version control.
|
|
111
|
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
112
|
+
.pdm.toml
|
|
113
|
+
.pdm-python
|
|
114
|
+
.pdm-build/
|
|
115
|
+
|
|
116
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
117
|
+
__pypackages__/
|
|
118
|
+
|
|
119
|
+
# Celery stuff
|
|
120
|
+
celerybeat-schedule
|
|
121
|
+
celerybeat.pid
|
|
122
|
+
|
|
123
|
+
# SageMath parsed files
|
|
124
|
+
*.sage.py
|
|
125
|
+
|
|
126
|
+
# Environment
|
|
127
|
+
.ve
|
|
128
|
+
.env
|
|
129
|
+
.venv
|
|
130
|
+
env/
|
|
131
|
+
venv/
|
|
132
|
+
ENV/
|
|
133
|
+
env.bak/
|
|
134
|
+
venv.bak/
|
|
135
|
+
|
|
136
|
+
# Spyder project settings
|
|
137
|
+
.spyderproject
|
|
138
|
+
.spyproject
|
|
139
|
+
|
|
140
|
+
# Rope project settings
|
|
141
|
+
.ropeproject
|
|
142
|
+
|
|
143
|
+
# mkdocs documentation
|
|
144
|
+
/site
|
|
145
|
+
|
|
146
|
+
# mypy
|
|
147
|
+
.mypy_cache/
|
|
148
|
+
.dmypy.json
|
|
149
|
+
dmypy.json
|
|
150
|
+
|
|
151
|
+
# Pyre type checker
|
|
152
|
+
.pyre/
|
|
153
|
+
|
|
154
|
+
# pytype static type analyzer
|
|
155
|
+
.pytype/
|
|
156
|
+
|
|
157
|
+
# Cython debug symbols
|
|
158
|
+
cython_debug/
|
|
159
|
+
|
|
160
|
+
# PyCharm
|
|
161
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
162
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
163
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
164
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
165
|
+
#.idea/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.8
|
gapi_tools-0.2.0/LICENSE
ADDED
|
@@ -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.
|
|
@@ -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,141 @@
|
|
|
1
|
+
# gapi-tools
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
## Funcionalidades
|
|
6
|
+
|
|
7
|
+
- Listar arquivos (resumido ou detalhado) e localizar por nome.
|
|
8
|
+
- Download de planilhas (preserva extensão `.xlsx`/`.xls`/`.xlsm`/`.xlsb` ou exporta Google Sheets como `.xlsx`).
|
|
9
|
+
- Upload de arquivos com *mimetype* detectado automaticamente.
|
|
10
|
+
- Mover, copiar, renomear, criar pasta/arquivo.
|
|
11
|
+
- Atualizar metadados, mandar para a lixeira, restaurar, apagar.
|
|
12
|
+
- Esvaziar pasta (com paginação).
|
|
13
|
+
- Listar permissões e revisões.
|
|
14
|
+
- Ler/escrever planilhas a partir de um `pandas.DataFrame`.
|
|
15
|
+
|
|
16
|
+
## Requisitos
|
|
17
|
+
|
|
18
|
+
- Python **3.8.x** (cap por compatibilidade com o servidor de produção; veja seção abaixo).
|
|
19
|
+
- Service account no Google Cloud com APIs **Drive** e **Sheets** habilitadas e arquivo JSON de credenciais.
|
|
20
|
+
|
|
21
|
+
## Instalação
|
|
22
|
+
|
|
23
|
+
Em ambiente de desenvolvimento (Linux/WSL):
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
uv sync --extra dev
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Em produção (Windows Server):
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install .
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Após instalar, o comando `gapi` fica disponível no `PATH`.
|
|
36
|
+
|
|
37
|
+
## Configuração
|
|
38
|
+
|
|
39
|
+
Aponte para o JSON da service account de uma das três formas (resolvidas nessa ordem):
|
|
40
|
+
|
|
41
|
+
1. variável de ambiente `GAPI_TOOLS_TOKEN` com o caminho absoluto do arquivo JSON;
|
|
42
|
+
2. arquivo `.env` no diretório atual contendo `GTOKEN=/caminho/para/credenciais.json`;
|
|
43
|
+
3. arquivo `.env` em `~/.config/gapi-tools/`.
|
|
44
|
+
|
|
45
|
+
A planilha/arquivo precisa estar **compartilhado** com o e-mail da service account.
|
|
46
|
+
|
|
47
|
+
## Uso da CLI
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
gapi list # nome -> id
|
|
51
|
+
gapi list --detailed --query "name = 'foo'" # JSON com metadados
|
|
52
|
+
gapi download minha-planilha --folder ./out --with-date
|
|
53
|
+
gapi upload ./local.csv FOLDER_ID --name remoto.csv
|
|
54
|
+
gapi move FILE_ID NEW_PARENT_ID --old-parent OLD
|
|
55
|
+
gapi copy FILE_ID --name "Cópia"
|
|
56
|
+
gapi create-folder Nova --parent root
|
|
57
|
+
gapi rename FILE_ID novo-nome
|
|
58
|
+
gapi update FILE_ID name=Foo description=Bar
|
|
59
|
+
gapi trash FILE_ID
|
|
60
|
+
gapi untrash FILE_ID
|
|
61
|
+
gapi delete FILE_ID --yes
|
|
62
|
+
gapi empty-folder FOLDER_ID --yes
|
|
63
|
+
gapi permissions FILE_ID
|
|
64
|
+
gapi revisions FILE_ID
|
|
65
|
+
gapi mtime FILE_ID
|
|
66
|
+
gapi sheets export-df dados.csv minha-planilha Plan1 --cell A2
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`gapi --help` mostra todos os comandos; cada subcomando tem `--help` próprio.
|
|
70
|
+
|
|
71
|
+
## Uso programático
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from gapi_tools import drive, sheets
|
|
75
|
+
import pandas as pd
|
|
76
|
+
|
|
77
|
+
# listar e baixar
|
|
78
|
+
files = drive.list_files_detailed(query="mimeType = 'application/vnd.google-apps.spreadsheet'")
|
|
79
|
+
out = drive.download_spreadsheet('minha-planilha', folder='./out', with_date=True)
|
|
80
|
+
|
|
81
|
+
# upload e organização
|
|
82
|
+
drive.upload_file('FOLDER_ID', './relatorio.xlsx')
|
|
83
|
+
drive.move_file('FILE_ID', 'NEW_PARENT_ID')
|
|
84
|
+
drive.rename_file('FILE_ID', 'novo-nome.xlsx')
|
|
85
|
+
|
|
86
|
+
# escrever DataFrame numa aba
|
|
87
|
+
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
|
|
88
|
+
sheets.export_dataframe_to_gsheet(df, 'minha-planilha', 'Plan1', cell_address='A2')
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Setup do servidor Windows Server 2008 R2
|
|
92
|
+
|
|
93
|
+
Este pacote é distribuído para um Windows Server 2008 R2 com Python **3.8.1**. Antes de instalar:
|
|
94
|
+
|
|
95
|
+
1. **Atualizações** — recomendado aplicar `KB3140245` ("Update to enable TLS 1.1 and TLS 1.2 as default secure protocols in WinHTTP").
|
|
96
|
+
2. **Habilitar TLS 1.2** no registro (chamadas à API do Google falham silenciosamente sem isso). Em `regedit`, criar/editar:
|
|
97
|
+
|
|
98
|
+
```
|
|
99
|
+
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client
|
|
100
|
+
Enabled = 1 (DWORD)
|
|
101
|
+
DisabledByDefault = 0 (DWORD)
|
|
102
|
+
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server
|
|
103
|
+
Enabled = 1 (DWORD)
|
|
104
|
+
DisabledByDefault = 0 (DWORD)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Reiniciar após alterar.
|
|
108
|
+
3. **Verificar TLS** — após reiniciar:
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
python -c "import urllib.request; print(urllib.request.urlopen('https://www.googleapis.com').status)"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Se falhar com erro de SSL, TLS 1.2 não está ativo.
|
|
115
|
+
4. **Instalar o pacote** — todas as dependências têm wheels `cp38-win_amd64`, então não é necessário compilador:
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
pip install .
|
|
119
|
+
```
|
|
120
|
+
5. **Sanity check** — `gapi --help` deve listar todos os subcomandos sem `ImportError`.
|
|
121
|
+
|
|
122
|
+
> Nota: o pacote evita `rich` (usa `typer` puro, não `typer[all]`) para funcionar bem no `cmd.exe` legado em cp1252.
|
|
123
|
+
|
|
124
|
+
## Testes
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
pytest -v
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Todos os testes usam mocks da Google API e não dependem de rede ou credenciais reais.
|
|
131
|
+
|
|
132
|
+
## Lint e formatação
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
ruff check .
|
|
136
|
+
ruff format .
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Licença
|
|
140
|
+
|
|
141
|
+
MIT — veja [LICENSE](LICENSE).
|
|
@@ -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
|
|
@@ -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()
|