rtcloud 1.0.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.
- rtcloud/__init__.py +372 -0
- rtcloud/py.typed +0 -0
- rtcloud-1.0.0.dist-info/METADATA +89 -0
- rtcloud-1.0.0.dist-info/RECORD +7 -0
- rtcloud-1.0.0.dist-info/WHEEL +5 -0
- rtcloud-1.0.0.dist-info/licenses/LICENSE +21 -0
- rtcloud-1.0.0.dist-info/top_level.txt +1 -0
rtcloud/__init__.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"""
|
|
2
|
+
rtcloud — a biblioteca oficial da RTCloud para Python.
|
|
3
|
+
|
|
4
|
+
from rtcloud import RTCloud
|
|
5
|
+
rt = RTCloud() # lê RTCLOUD_API_KEY
|
|
6
|
+
for app in rt.apps.list():
|
|
7
|
+
print(app["name"], "no ar" if app["online"] else "parada")
|
|
8
|
+
|
|
9
|
+
Fala com a API pública (/api/v1). A resposta da API vem num envelope
|
|
10
|
+
``{"status", "response"}``; aqui você recebe só o ``response``. Erro vira
|
|
11
|
+
``RTCloudError`` com ``status`` (HTTP), ``code`` e a mensagem da API.
|
|
12
|
+
|
|
13
|
+
Repetições automáticas (as mesmas da CLI):
|
|
14
|
+
* 503 "em atualização" (a RTCloud publicando uma versão nova): o pedido
|
|
15
|
+
nem chegou a rodar, então repete — inclusive POST — por até 5 minutos;
|
|
16
|
+
* 429 em leitura (GET): espera o tempo pedido (até 30 s), no máximo 2 vezes.
|
|
17
|
+
|
|
18
|
+
Só biblioteca padrão: nenhuma dependência para instalar.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import time
|
|
25
|
+
import uuid
|
|
26
|
+
import urllib.error
|
|
27
|
+
import urllib.parse
|
|
28
|
+
import urllib.request
|
|
29
|
+
from typing import Any, Dict, Iterable, List, Optional
|
|
30
|
+
|
|
31
|
+
__all__ = ["RTCloud", "RTCloudError", "__version__"]
|
|
32
|
+
__version__ = "1.0.0"
|
|
33
|
+
|
|
34
|
+
_BASE_PADRAO = "https://rtcloud.com.br/api/v1"
|
|
35
|
+
_ATUALIZACAO_MAX_S = 5 * 60
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class RTCloudError(Exception):
|
|
39
|
+
"""Erro devolvido pela API (status 0 = sem resposta)."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, message: str, status: int = 0, code: str = "UNKNOWN", body: Any = None):
|
|
42
|
+
super().__init__(message)
|
|
43
|
+
self.message = message
|
|
44
|
+
self.status = status
|
|
45
|
+
self.code = code
|
|
46
|
+
self.body = body
|
|
47
|
+
|
|
48
|
+
def __repr__(self) -> str: # pragma: no cover - só exibição
|
|
49
|
+
return f"RTCloudError(status={self.status}, code={self.code!r}, message={self.message!r})"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _q(**valores: Any) -> str:
|
|
53
|
+
pares = []
|
|
54
|
+
for k, v in valores.items():
|
|
55
|
+
if v is None or v == "" or v is False:
|
|
56
|
+
continue
|
|
57
|
+
pares.append((k, "1" if v is True else str(v)))
|
|
58
|
+
return ("?" + urllib.parse.urlencode(pares)) if pares else ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _id(v: str) -> str:
|
|
62
|
+
return urllib.parse.quote(str(v), safe="")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _Area:
|
|
66
|
+
def __init__(self, cliente: "RTCloud"):
|
|
67
|
+
self._c = cliente
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _Conta(_Area):
|
|
71
|
+
def me(self) -> Dict[str, Any]:
|
|
72
|
+
"""Perfil, plano e uso de memória da conta."""
|
|
73
|
+
return self._c.request("GET", "/users/me")
|
|
74
|
+
|
|
75
|
+
def teams(self) -> List[Dict[str, Any]]:
|
|
76
|
+
"""Equipes que você criou ou de que participa."""
|
|
77
|
+
return self._c.request("GET", "/teams")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _Plataforma(_Area):
|
|
81
|
+
def status(self) -> Dict[str, Any]:
|
|
82
|
+
return self._c.request("GET", "/service/status")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _Apps(_Area):
|
|
86
|
+
def list(self) -> List[Dict[str, Any]]:
|
|
87
|
+
return self._c.request("GET", "/apps")
|
|
88
|
+
|
|
89
|
+
def status_all(self) -> List[Dict[str, Any]]:
|
|
90
|
+
return self._c.request("GET", "/apps/status")
|
|
91
|
+
|
|
92
|
+
def get(self, app: str) -> Dict[str, Any]:
|
|
93
|
+
return self._c.request("GET", f"/apps/{_id(app)}")
|
|
94
|
+
|
|
95
|
+
def status(self, app: str) -> Dict[str, Any]:
|
|
96
|
+
return self._c.request("GET", f"/apps/{_id(app)}/status")
|
|
97
|
+
|
|
98
|
+
def metrics(self, app: str, range: str = "24h") -> Dict[str, Any]: # noqa: A002 - nome da API
|
|
99
|
+
return self._c.request("GET", f"/apps/{_id(app)}/metrics{_q(range=range)}")
|
|
100
|
+
|
|
101
|
+
def logs(self, app: str) -> Dict[str, Any]:
|
|
102
|
+
return self._c.request("GET", f"/apps/{_id(app)}/logs")
|
|
103
|
+
|
|
104
|
+
def start(self, app: str) -> Dict[str, Any]:
|
|
105
|
+
return self._c.request("POST", f"/apps/{_id(app)}/start")
|
|
106
|
+
|
|
107
|
+
def stop(self, app: str) -> Dict[str, Any]:
|
|
108
|
+
return self._c.request("POST", f"/apps/{_id(app)}/stop")
|
|
109
|
+
|
|
110
|
+
def restart(self, app: str) -> Dict[str, Any]:
|
|
111
|
+
return self._c.request("POST", f"/apps/{_id(app)}/restart")
|
|
112
|
+
|
|
113
|
+
def deployments(self, app: str) -> List[Dict[str, Any]]:
|
|
114
|
+
return self._c.request("GET", f"/apps/{_id(app)}/deployments")
|
|
115
|
+
|
|
116
|
+
def commit(self, app: str, zip_bytes: bytes, filename: str = "projeto.zip") -> Dict[str, Any]:
|
|
117
|
+
"""Publica uma versão nova a partir dos bytes de um .zip."""
|
|
118
|
+
return self._c.request("POST", f"/apps/{_id(app)}/commit", arquivo=("file", filename, zip_bytes), timeout=max(self._c.timeout, 600))
|
|
119
|
+
|
|
120
|
+
def delete(self, app: str, confirm: str) -> Dict[str, Any]:
|
|
121
|
+
"""Exclui de vez. ``confirm`` precisa ser o nome exato da aplicação."""
|
|
122
|
+
return self._c.request("DELETE", f"/apps/{_id(app)}", json_body={"confirm": confirm})
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class _Arquivos(_Area):
|
|
126
|
+
def list(self, app: str, path: str = "") -> Dict[str, Any]:
|
|
127
|
+
return self._c.request("GET", f"/apps/{_id(app)}/files{_q(path=path)}")
|
|
128
|
+
|
|
129
|
+
def read(self, app: str, path: str) -> Dict[str, Any]:
|
|
130
|
+
return self._c.request("GET", f"/apps/{_id(app)}/files/content{_q(path=path)}")
|
|
131
|
+
|
|
132
|
+
def write(self, app: str, path: str, content: str) -> Dict[str, Any]:
|
|
133
|
+
return self._c.request("PUT", f"/apps/{_id(app)}/files", json_body={"path": path, "content": content})
|
|
134
|
+
|
|
135
|
+
def edit(self, app: str, path: str, edits: Iterable[Dict[str, str]]) -> Dict[str, Any]:
|
|
136
|
+
"""Troca trechos: ``edits=[{"old": "...", "new": "..."}]`` (cada old aparece uma vez)."""
|
|
137
|
+
return self._c.request("PATCH", f"/apps/{_id(app)}/files", json_body={"path": path, "edits": list(edits)})
|
|
138
|
+
|
|
139
|
+
def move(self, app: str, from_path: str, to_path: str) -> Dict[str, Any]:
|
|
140
|
+
return self._c.request("PATCH", f"/apps/{_id(app)}/files", json_body={"from": from_path, "to": to_path})
|
|
141
|
+
|
|
142
|
+
def delete(self, app: str, path: str) -> Dict[str, Any]:
|
|
143
|
+
return self._c.request("DELETE", f"/apps/{_id(app)}/files{_q(path=path)}")
|
|
144
|
+
|
|
145
|
+
def search(
|
|
146
|
+
self,
|
|
147
|
+
app: str,
|
|
148
|
+
q: str,
|
|
149
|
+
case_sensitive: bool = False,
|
|
150
|
+
whole_word: bool = False,
|
|
151
|
+
path: str = "",
|
|
152
|
+
ext: str = "",
|
|
153
|
+
) -> Dict[str, Any]:
|
|
154
|
+
"""Busca um texto em todos os arquivos da aplicação."""
|
|
155
|
+
return self._c.request("GET", f"/apps/{_id(app)}/files/search{_q(q=q, case=case_sensitive, word=whole_word, path=path, ext=ext)}")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class _Variaveis(_Area):
|
|
159
|
+
def list(self, app: str) -> Dict[str, str]:
|
|
160
|
+
return self._c.request("GET", f"/apps/{_id(app)}/envs")
|
|
161
|
+
|
|
162
|
+
def set(self, app: str, envs: Dict[str, str], restart: Optional[bool] = None) -> Dict[str, Any]:
|
|
163
|
+
"""Grava só as chaves enviadas (as outras ficam como estão)."""
|
|
164
|
+
return self._c.request("POST", f"/apps/{_id(app)}/envs", json_body=_sem_none({"envs": envs, "restart": restart}))
|
|
165
|
+
|
|
166
|
+
def replace(self, app: str, envs: Dict[str, str], restart: Optional[bool] = None) -> Dict[str, Any]:
|
|
167
|
+
"""Substitui TODAS — as que ficarem de fora são apagadas."""
|
|
168
|
+
return self._c.request("PUT", f"/apps/{_id(app)}/envs", json_body=_sem_none({"envs": envs, "restart": restart}))
|
|
169
|
+
|
|
170
|
+
def remove(self, app: str, keys: Iterable[str], restart: Optional[bool] = None) -> Dict[str, Any]:
|
|
171
|
+
return self._c.request("DELETE", f"/apps/{_id(app)}/envs", json_body=_sem_none({"keys": list(keys), "restart": restart}))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class _Snapshots(_Area):
|
|
175
|
+
def list(self, app: str) -> List[Dict[str, Any]]:
|
|
176
|
+
return self._c.request("GET", f"/apps/{_id(app)}/snapshots")
|
|
177
|
+
|
|
178
|
+
def create(self, app: str) -> Dict[str, Any]:
|
|
179
|
+
return self._c.request("POST", f"/apps/{_id(app)}/snapshots")
|
|
180
|
+
|
|
181
|
+
def restore(self, app: str, version: str) -> Dict[str, Any]:
|
|
182
|
+
return self._c.request("POST", f"/apps/{_id(app)}/snapshots/restore", json_body={"version": version})
|
|
183
|
+
|
|
184
|
+
def restore_status(self, app: str) -> Dict[str, Any]:
|
|
185
|
+
return self._c.request("GET", f"/apps/{_id(app)}/snapshots/restore")
|
|
186
|
+
|
|
187
|
+
def restore_and_wait(self, app: str, version: str, interval: float = 5.0, timeout: float = 900.0) -> Dict[str, Any]:
|
|
188
|
+
"""Restaura e espera terminar, consultando o andamento."""
|
|
189
|
+
inicio = self.restore(app, version)
|
|
190
|
+
if not inicio.get("pending"):
|
|
191
|
+
return inicio
|
|
192
|
+
limite = time.monotonic() + timeout
|
|
193
|
+
while time.monotonic() < limite:
|
|
194
|
+
time.sleep(max(2.0, interval))
|
|
195
|
+
s = self.restore_status(app)
|
|
196
|
+
if s.get("state") == "success":
|
|
197
|
+
return s
|
|
198
|
+
if s.get("state") == "error":
|
|
199
|
+
raise RTCloudError(s.get("message") or "A restauração falhou.", 200, "RESTORE_FAILED", s)
|
|
200
|
+
raise RTCloudError("A restauração passou do tempo de espera; ela continua rodando.", 0, "RESTORE_TIMEOUT")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class _Monitor(_Area):
|
|
204
|
+
def get(self, app: str) -> Dict[str, Any]:
|
|
205
|
+
return self._c.request("GET", f"/apps/{_id(app)}/monitor")
|
|
206
|
+
|
|
207
|
+
def check(self, app: str) -> Dict[str, Any]:
|
|
208
|
+
return self._c.request("POST", f"/apps/{_id(app)}/monitor/check")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class _Rede(_Area):
|
|
212
|
+
def analytics(self, app: str, days: int = 1) -> Dict[str, Any]:
|
|
213
|
+
return self._c.request("GET", f"/apps/{_id(app)}/network/analytics{_q(days=days)}")
|
|
214
|
+
|
|
215
|
+
def errors(self, app: str, days: int = 1, include_4xx: bool = False) -> Dict[str, Any]:
|
|
216
|
+
return self._c.request("GET", f"/apps/{_id(app)}/network/errors{_q(days=days, include4xx=include_4xx)}")
|
|
217
|
+
|
|
218
|
+
def performance(self, app: str, days: int = 1) -> Dict[str, Any]:
|
|
219
|
+
return self._c.request("GET", f"/apps/{_id(app)}/network/performance{_q(days=days)}")
|
|
220
|
+
|
|
221
|
+
def purge_cache(self, app: str) -> Dict[str, Any]:
|
|
222
|
+
return self._c.request("POST", f"/apps/{_id(app)}/purge-cache")
|
|
223
|
+
|
|
224
|
+
def domain(self, app: str) -> Dict[str, Any]:
|
|
225
|
+
"""O domínio próprio e os registros de DNS."""
|
|
226
|
+
return self._c.request("GET", f"/apps/{_id(app)}/domain")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class _Bancos(_Area):
|
|
230
|
+
def list(self) -> List[Dict[str, Any]]:
|
|
231
|
+
return self._c.request("GET", "/databases")
|
|
232
|
+
|
|
233
|
+
def get(self, db: str) -> Dict[str, Any]:
|
|
234
|
+
return self._c.request("GET", f"/databases/{_id(db)}")
|
|
235
|
+
|
|
236
|
+
def metrics(self, db: str) -> Dict[str, Any]:
|
|
237
|
+
return self._c.request("GET", f"/databases/{_id(db)}/metrics")
|
|
238
|
+
|
|
239
|
+
def start(self, db: str) -> Dict[str, Any]:
|
|
240
|
+
return self._c.request("POST", f"/databases/{_id(db)}/start")
|
|
241
|
+
|
|
242
|
+
def stop(self, db: str) -> Dict[str, Any]:
|
|
243
|
+
return self._c.request("POST", f"/databases/{_id(db)}/stop")
|
|
244
|
+
|
|
245
|
+
def restart(self, db: str) -> Dict[str, Any]:
|
|
246
|
+
return self._c.request("POST", f"/databases/{_id(db)}/restart")
|
|
247
|
+
|
|
248
|
+
def backups(self, db: str) -> List[Dict[str, Any]]:
|
|
249
|
+
return self._c.request("GET", f"/databases/{_id(db)}/backups")
|
|
250
|
+
|
|
251
|
+
def create_backup(self, db: str) -> Dict[str, Any]:
|
|
252
|
+
return self._c.request("POST", f"/databases/{_id(db)}/backups")
|
|
253
|
+
|
|
254
|
+
def certificate(self, db: str) -> Dict[str, Any]:
|
|
255
|
+
"""O .pem do banco (precisa de chave de acesso total)."""
|
|
256
|
+
return self._c.request("GET", f"/databases/{_id(db)}/certificate")
|
|
257
|
+
|
|
258
|
+
def reset_credentials(self, db: str, type: str) -> Dict[str, Any]: # noqa: A002 - nome da API
|
|
259
|
+
"""``type`` = "password" ou "certificate"."""
|
|
260
|
+
return self._c.request("POST", f"/databases/{_id(db)}/credentials/reset", json_body={"type": type})
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _sem_none(d: Dict[str, Any]) -> Dict[str, Any]:
|
|
264
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class RTCloud:
|
|
268
|
+
"""Cliente da API pública da RTCloud."""
|
|
269
|
+
|
|
270
|
+
def __init__(
|
|
271
|
+
self,
|
|
272
|
+
api_key: Optional[str] = None,
|
|
273
|
+
base_url: Optional[str] = None,
|
|
274
|
+
timeout: float = 60.0,
|
|
275
|
+
user_agent: Optional[str] = None,
|
|
276
|
+
):
|
|
277
|
+
chave = (api_key or os.environ.get("RTCLOUD_API_KEY") or "").strip()
|
|
278
|
+
if not chave:
|
|
279
|
+
raise RTCloudError(
|
|
280
|
+
"Informe a chave da API (api_key) ou defina RTCLOUD_API_KEY. Gere uma no painel: menu da conta → Chaves de API.",
|
|
281
|
+
code="MISSING_API_KEY",
|
|
282
|
+
)
|
|
283
|
+
if chave.startswith("rtm_"):
|
|
284
|
+
raise RTCloudError(
|
|
285
|
+
"Essa é uma chave do servidor MCP (rtm_). A biblioteca usa uma chave da API (rtc_), criada em Chaves de API.",
|
|
286
|
+
code="WRONG_KEY_TYPE",
|
|
287
|
+
)
|
|
288
|
+
self.api_key = chave
|
|
289
|
+
self.base_url = (base_url or os.environ.get("RTCLOUD_API_URL") or _BASE_PADRAO).rstrip("/")
|
|
290
|
+
self.timeout = float(timeout)
|
|
291
|
+
self.user_agent = user_agent or f"rtcloud-python/{__version__}"
|
|
292
|
+
|
|
293
|
+
self.account = _Conta(self)
|
|
294
|
+
self.platform = _Plataforma(self)
|
|
295
|
+
self.apps = _Apps(self)
|
|
296
|
+
self.files = _Arquivos(self)
|
|
297
|
+
self.envs = _Variaveis(self)
|
|
298
|
+
self.snapshots = _Snapshots(self)
|
|
299
|
+
self.monitor = _Monitor(self)
|
|
300
|
+
self.network = _Rede(self)
|
|
301
|
+
self.databases = _Bancos(self)
|
|
302
|
+
|
|
303
|
+
def request(
|
|
304
|
+
self,
|
|
305
|
+
method: str,
|
|
306
|
+
path: str,
|
|
307
|
+
json_body: Any = None,
|
|
308
|
+
arquivo: Optional[tuple] = None,
|
|
309
|
+
timeout: Optional[float] = None,
|
|
310
|
+
) -> Any:
|
|
311
|
+
"""Pedido cru à API (``path`` depois de /api/v1, começando com "/")."""
|
|
312
|
+
url = f"{self.base_url}{path}"
|
|
313
|
+
cabecalhos = {"Authorization": self.api_key, "Accept": "application/json", "User-Agent": self.user_agent}
|
|
314
|
+
corpo: Optional[bytes] = None
|
|
315
|
+
if arquivo is not None:
|
|
316
|
+
campo, nome, dados = arquivo
|
|
317
|
+
fronteira = f"----rtcloud{uuid.uuid4().hex}"
|
|
318
|
+
corpo = (
|
|
319
|
+
f"--{fronteira}\r\nContent-Disposition: form-data; name=\"{campo}\"; filename=\"{nome}\"\r\n"
|
|
320
|
+
f"Content-Type: application/zip\r\n\r\n"
|
|
321
|
+
).encode() + bytes(dados) + f"\r\n--{fronteira}--\r\n".encode()
|
|
322
|
+
cabecalhos["Content-Type"] = f"multipart/form-data; boundary={fronteira}"
|
|
323
|
+
elif json_body is not None:
|
|
324
|
+
corpo = json.dumps(json_body, ensure_ascii=False).encode("utf-8")
|
|
325
|
+
cabecalhos["Content-Type"] = "application/json"
|
|
326
|
+
|
|
327
|
+
inicio = time.monotonic()
|
|
328
|
+
repeticoes_429 = 0
|
|
329
|
+
tentativa = 0
|
|
330
|
+
while True:
|
|
331
|
+
pedido = urllib.request.Request(url, data=corpo, method=method.upper(), headers=cabecalhos)
|
|
332
|
+
try:
|
|
333
|
+
with urllib.request.urlopen(pedido, timeout=timeout or self.timeout) as r:
|
|
334
|
+
status, texto, h = r.status, r.read().decode("utf-8", "replace"), r.headers
|
|
335
|
+
except urllib.error.HTTPError as e:
|
|
336
|
+
status, texto, h = e.code, e.read().decode("utf-8", "replace"), e.headers
|
|
337
|
+
e.close()
|
|
338
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
339
|
+
motivo = getattr(e, "reason", e)
|
|
340
|
+
raise RTCloudError(f"Sem conexão com a RTCloud: {motivo}", 0, "NETWORK_ERROR") from None
|
|
341
|
+
|
|
342
|
+
try:
|
|
343
|
+
dados = json.loads(texto) if texto else None
|
|
344
|
+
except ValueError:
|
|
345
|
+
dados = None
|
|
346
|
+
|
|
347
|
+
if 200 <= status < 300:
|
|
348
|
+
if isinstance(dados, dict) and dados.get("status") == "success":
|
|
349
|
+
return dados.get("response")
|
|
350
|
+
return dados if dados is not None else texto
|
|
351
|
+
|
|
352
|
+
mensagem = (dados or {}).get("message") if isinstance(dados, dict) else None
|
|
353
|
+
atualizando = status == 503 and (h.get("x-rtcloud-atualizando") or "atualiza" in (mensagem or texto).lower())
|
|
354
|
+
if atualizando and time.monotonic() - inicio < _ATUALIZACAO_MAX_S:
|
|
355
|
+
tentativa += 1
|
|
356
|
+
time.sleep(min(15.0, 3.0 * tentativa))
|
|
357
|
+
continue
|
|
358
|
+
if status == 429 and method.upper() == "GET" and repeticoes_429 < 2:
|
|
359
|
+
repeticoes_429 += 1
|
|
360
|
+
try:
|
|
361
|
+
espera = float(h.get("retry-after") or 5)
|
|
362
|
+
except ValueError:
|
|
363
|
+
espera = 5.0
|
|
364
|
+
time.sleep(min(30.0, max(1.0, espera)))
|
|
365
|
+
continue
|
|
366
|
+
codigo = (dados or {}).get("code") if isinstance(dados, dict) else None
|
|
367
|
+
raise RTCloudError(
|
|
368
|
+
mensagem or f"A API respondeu {status}.",
|
|
369
|
+
status,
|
|
370
|
+
codigo or ("UNAVAILABLE" if status >= 500 else "BAD_REQUEST"),
|
|
371
|
+
dados if dados is not None else texto,
|
|
372
|
+
)
|
rtcloud/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rtcloud
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Biblioteca oficial da RTCloud para Python: aplicações, arquivos, variáveis, snapshots, bancos e equipes pela API pública.
|
|
5
|
+
Author: RT Cloud
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://rtcloud.com.br
|
|
8
|
+
Project-URL: Documentation, https://docs.rtcloud.com.br/sdk-python
|
|
9
|
+
Keywords: rtcloud,hospedagem,api,sdk,deploy,bot,discord
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Natural Language :: Portuguese (Brazilian)
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.8
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# rtcloud (Python)
|
|
21
|
+
|
|
22
|
+
Biblioteca oficial da **RTCloud** para Python. Controle aplicações, arquivos, variáveis, snapshots, bancos de dados e equipes pelo seu código — a mesma API pública que a CLI e a extensão do VS Code usam.
|
|
23
|
+
|
|
24
|
+
- Só biblioteca padrão: nenhuma dependência.
|
|
25
|
+
- Python 3.8 ou mais novo, com tipos.
|
|
26
|
+
- Repete sozinha quando a RTCloud está publicando uma atualização (503) e quando uma leitura bate no limite (429).
|
|
27
|
+
|
|
28
|
+
## Instalação
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install rtcloud
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Primeiros passos
|
|
35
|
+
|
|
36
|
+
Gere uma chave no painel (**menu da conta → Chaves de API**) e guarde em `RTCLOUD_API_KEY`.
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from rtcloud import RTCloud
|
|
40
|
+
|
|
41
|
+
rt = RTCloud() # lê RTCLOUD_API_KEY
|
|
42
|
+
|
|
43
|
+
for app in rt.apps.list():
|
|
44
|
+
print(app["name"], "no ar" if app["online"] else "parada")
|
|
45
|
+
|
|
46
|
+
rt.apps.restart("meu-bot") # aceita o id ou o nome exato
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Exemplos
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
# publicar uma versão nova
|
|
53
|
+
with open("projeto.zip", "rb") as f:
|
|
54
|
+
rt.apps.commit("minha-api", f.read())
|
|
55
|
+
|
|
56
|
+
# buscar texto em todos os arquivos
|
|
57
|
+
r = rt.files.search("meu-bot", "DISCORD_TOKEN", ext="py")
|
|
58
|
+
for f in r["files"]:
|
|
59
|
+
print(f["path"], f["matches"])
|
|
60
|
+
|
|
61
|
+
# trocar um trecho de arquivo e reiniciar
|
|
62
|
+
rt.files.edit("meu-bot", "config.py", [{"old": 'PREFIXO = "!"', "new": 'PREFIXO = "?"'}])
|
|
63
|
+
rt.apps.restart("meu-bot")
|
|
64
|
+
|
|
65
|
+
# variáveis: grava só as enviadas
|
|
66
|
+
rt.envs.set("minha-api", {"LOG_LEVEL": "debug"})
|
|
67
|
+
|
|
68
|
+
# restaurar o snapshot mais novo e esperar terminar
|
|
69
|
+
ultimo = rt.snapshots.list("minha-api")[0]
|
|
70
|
+
rt.snapshots.restore_and_wait("minha-api", ultimo["version"])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Erros
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from rtcloud import RTCloudError
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
rt.apps.get("nao-existe")
|
|
80
|
+
except RTCloudError as e:
|
|
81
|
+
print(e.status, e.code, e.message) # 404 NOT_FOUND Aplicação não encontrada.
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Segurança
|
|
85
|
+
|
|
86
|
+
- A chave age como você: guarde em variável de ambiente, nunca no código.
|
|
87
|
+
- Arquivos de credenciais (`.env`, chaves, certificados) não passam pela API de arquivos — use `rt.envs`.
|
|
88
|
+
|
|
89
|
+
Documentação: <https://docs.rtcloud.com.br/sdk-python> · Licença MIT.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
rtcloud/__init__.py,sha256=YVBny2J0tb6HT-Mze4973DBttpLHCTQnWZNgL3FIDLM,15668
|
|
2
|
+
rtcloud/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
rtcloud-1.0.0.dist-info/licenses/LICENSE,sha256=KJr4_RtHeylX3QRL-g5JwletmAMzrUHpd0TOntCUnlg,1065
|
|
4
|
+
rtcloud-1.0.0.dist-info/METADATA,sha256=iavyIcGqh-qwd64YW6LLTtdi_NS8mkvucOG-SyR1AtU,2818
|
|
5
|
+
rtcloud-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
rtcloud-1.0.0.dist-info/top_level.txt,sha256=Lko9yxCsA_lQkbg6uyNyVOIK_e1rTqhSnWGpn4lIBm4,8
|
|
7
|
+
rtcloud-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RT Cloud
|
|
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 @@
|
|
|
1
|
+
rtcloud
|