t3api-utils 2.0.0__tar.gz → 2.0.1__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.
Files changed (35) hide show
  1. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/PKG-INFO +3 -3
  2. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/README.md +2 -2
  3. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/pyproject.toml +1 -1
  4. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/pyproject.toml.orig +1 -1
  5. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/__init__.py +5 -1
  6. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/_api.py +33 -0
  7. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/auth/resolve.py +22 -6
  8. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/cli/main.py +27 -6
  9. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/client.py +195 -16
  10. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/local.py +24 -3
  11. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/pickers.py +25 -5
  12. t3api_utils-2.0.1/t3api_utils/prompts.py +71 -0
  13. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/reports.py +9 -24
  14. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/spec/registry.py +30 -1
  15. t3api_utils-2.0.1/t3api_utils/writes.py +407 -0
  16. t3api_utils-2.0.0/t3api_utils/writes.py +0 -273
  17. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/_console.py +0 -0
  18. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/_http.py +0 -0
  19. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/_paths.py +0 -0
  20. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/_ratelimit.py +0 -0
  21. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/auth/__init__.py +0 -0
  22. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/auth/credentials.py +0 -0
  23. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/auth/login.py +0 -0
  24. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/auth/secret_keys.py +0 -0
  25. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/auth/states.py +0 -0
  26. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/auth/store.py +0 -0
  27. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/cli/__init__.py +0 -0
  28. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/errors.py +0 -0
  29. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/py.typed +0 -0
  30. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/spec/__init__.py +0 -0
  31. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/spec/loader.py +0 -0
  32. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/spec/openapi.json.gz +0 -0
  33. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/tag_lists.py +0 -0
  34. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/tui/__init__.py +0 -0
  35. {t3api_utils-2.0.0 → t3api_utils-2.0.1}/t3api_utils/tui/inspector.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: t3api-utils
3
- Version: 2.0.0
3
+ Version: 2.0.1
4
4
  Summary: Secret-key auth, collection loading, reports and tag lists for the T3 API
5
5
  Keywords: t3,metrc,track and trace,cannabis,api
6
6
  Author: Matt Frisbie
@@ -75,8 +75,8 @@ A few more things it does:
75
75
  # Writes are a dry run unless submit=True
76
76
  client.post("/v2/items/discontinue", license="LIC-00001", json={"id": 12345}, submit=True)
77
77
 
78
- # Validate every row, then submit
79
- client.bulk("/v2/items/discontinue", rows=[{"id": i["id"]} for i in items], license="LIC-00001", submit=True)
78
+ # Validate every row, show the results, and ask before submitting
79
+ client.bulk("/v2/items/discontinue", rows=[{"id": i["id"]} for i in items], license="LIC-00001", submit="ask")
80
80
 
81
81
  # Server-side report straight to a file
82
82
  client.report("ITEMS_REPORT", licenses=["LIC-00001"], to="items.xlsx")
@@ -47,8 +47,8 @@ A few more things it does:
47
47
  # Writes are a dry run unless submit=True
48
48
  client.post("/v2/items/discontinue", license="LIC-00001", json={"id": 12345}, submit=True)
49
49
 
50
- # Validate every row, then submit
51
- client.bulk("/v2/items/discontinue", rows=[{"id": i["id"]} for i in items], license="LIC-00001", submit=True)
50
+ # Validate every row, show the results, and ask before submitting
51
+ client.bulk("/v2/items/discontinue", rows=[{"id": i["id"]} for i in items], license="LIC-00001", submit="ask")
52
52
 
53
53
  # Server-side report straight to a file
54
54
  client.report("ITEMS_REPORT", licenses=["LIC-00001"], to="items.xlsx")
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "t3api-utils"
3
- version = "2.0.0"
3
+ version = "2.0.1"
4
4
  description = "Secret-key auth, collection loading, reports and tag lists for the T3 API"
5
5
  readme = "README.md"
6
6
  license = "GPL-3.0-only"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "t3api-utils"
3
- version = "2.0.0"
3
+ version = "2.0.1"
4
4
  description = "Secret-key auth, collection loading, reports and tag lists for the T3 API"
5
5
  authors = [{ name = "Matt Frisbie", email = "matt@classvsoftware.com" }]
6
6
  readme = "README.md"
@@ -36,7 +36,8 @@ from t3api_utils.errors import (
36
36
  ValidationError,
37
37
  )
38
38
  from t3api_utils.local import filter_rows, read_rows, to_csv, to_json
39
- from t3api_utils.pickers import pick_file
39
+ from t3api_utils.pickers import choose, pick_file
40
+ from t3api_utils.prompts import ask, confirm
40
41
  from t3api_utils.spec.registry import Endpoint
41
42
  from t3api_utils.tag_lists import TagList
42
43
  from t3api_utils.writes import BulkResult, RowResult, WriteResult
@@ -85,6 +86,9 @@ __all__ = [
85
86
  "ValidationError",
86
87
  "WriteResult",
87
88
  "__version__",
89
+ "ask",
90
+ "choose",
91
+ "confirm",
88
92
  "connect",
89
93
  "filter_rows",
90
94
  "inspect",
@@ -2,6 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
5
8
  from typing import Any
6
9
 
7
10
  import httpx2
@@ -50,3 +53,33 @@ def call(
50
53
  **kwargs: Any,
51
54
  ) -> Any:
52
55
  return parse(send(http, method, url, credential_kind=credential_kind, **kwargs))
56
+
57
+
58
+ def download(
59
+ http: httpx2.Client,
60
+ url: str,
61
+ target: Path,
62
+ *,
63
+ credential_kind: str | None = None,
64
+ **kwargs: Any,
65
+ ) -> Path:
66
+ """Stream a GET response to ``target``.
67
+
68
+ The body goes to a temporary file next to ``target`` that is renamed only
69
+ once the download finishes, so a failure never leaves a half-written file.
70
+ """
71
+ target.parent.mkdir(parents=True, exist_ok=True)
72
+ with http.stream("GET", url, **kwargs) as response:
73
+ if response.is_error:
74
+ response.read()
75
+ raise error_from_response(response, credential_kind=credential_kind)
76
+ fd, tmp = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.", suffix=".part")
77
+ try:
78
+ with os.fdopen(fd, "wb") as handle:
79
+ for chunk in response.iter_bytes():
80
+ handle.write(chunk)
81
+ os.replace(tmp, target)
82
+ except BaseException:
83
+ Path(tmp).unlink(missing_ok=True)
84
+ raise
85
+ return target
@@ -7,6 +7,7 @@ in a terminal), else :class:`~t3api_utils.errors.AuthRequired`.
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import logging
10
11
  import os
11
12
  from typing import Any, Literal
12
13
 
@@ -20,6 +21,8 @@ from t3api_utils.auth.store import Profile, Store
20
21
  from t3api_utils.client import T3Client
21
22
  from t3api_utils.errors import AuthRequired
22
23
 
24
+ logger = logging.getLogger("t3api_utils")
25
+
23
26
  SETUP_HELP = (
24
27
  "No T3 credential found. Do one of these:\n"
25
28
  " • Run `t3api login` in a terminal. It saves a secret key to a profile.\n"
@@ -43,7 +46,7 @@ def connect(
43
46
  license: str | None = None,
44
47
  interactive: bool | None = None,
45
48
  validate: bool = True,
46
- sandbox: bool = False,
49
+ sandbox: bool | None = None,
47
50
  spec: Literal["auto", "bundled"] | None = None,
48
51
  rate_limit: float | None = 10.0,
49
52
  concurrency: int = 10,
@@ -63,11 +66,15 @@ def connect(
63
66
  api_host: T3 API base URL. Defaults to ``T3_API_HOST``, then the
64
67
  profile's, then ``https://api.trackandtrace.tools``.
65
68
  license: Default license for calls that need one. Defaults to
66
- ``T3_LICENSE``, then the profile's.
69
+ ``T3_LICENSE``, then the profile's, except in the sandbox, where
70
+ only this argument counts.
67
71
  interactive: ``False`` never prompts; ``True`` always may. By default
68
72
  it prompts only in a terminal or Jupyter.
69
73
  validate: Check the credential with ``GET /v2/auth/whoami``.
70
- sandbox: Exchange the credential for a Metrc sandbox JWT.
74
+ sandbox: Exchange the credential for a Metrc sandbox JWT. Defaults to
75
+ ``T3_SANDBOX`` (``1``, ``true``, ``yes`` or ``on``). In the sandbox,
76
+ ``T3_LICENSE`` and the profile's license are ignored, since a
77
+ production license there returns no rows rather than an error.
71
78
  spec: ``"bundled"`` pins the spec that ships with the package.
72
79
  Defaults to ``T3_SPEC``, then ``"auto"``.
73
80
  rate_limit: Requests per second across all threads. ``None`` disables it.
@@ -137,7 +144,14 @@ def connect(
137
144
  )
138
145
  auth, use_profile = result.auth, result.profile
139
146
 
140
- default_license = license or _env("T3_LICENSE") or (use_profile.license if use_profile else None)
147
+ use_sandbox = env_flag("T3_SANDBOX") if sandbox is None else sandbox
148
+ saved_license = _env("T3_LICENSE") or (use_profile.license if use_profile else None)
149
+ default_license = license if use_sandbox else (license or saved_license)
150
+ if use_sandbox and not license and saved_license:
151
+ logger.info(
152
+ "Not using default license %s in the sandbox. Pass license= with a sandbox license.",
153
+ saved_license,
154
+ )
141
155
  spec_mode = spec or ("bundled" if (_env("T3_SPEC") or "").lower() == "bundled" else "auto")
142
156
  client = T3Client(
143
157
  auth=auth,
@@ -152,9 +166,11 @@ def connect(
152
166
  **http_options,
153
167
  )
154
168
  try:
155
- if sandbox:
169
+ if use_sandbox:
170
+ # Clears the default license and calls whoami, which validates.
156
171
  client.enter_sandbox()
157
- if validate:
172
+ client.license = license
173
+ elif validate:
158
174
  client.whoami()
159
175
  except BaseException:
160
176
  client.close()
@@ -56,6 +56,9 @@ OutputOpt = Annotated[
56
56
  Path | None, typer.Option("--output", "-o", help="File to write (.csv, .json or .jsonl).")
57
57
  ]
58
58
 
59
+ # Global options from the root callback, set again on every run.
60
+ _global = {"sandbox": False}
61
+
59
62
 
60
63
  def handle_errors(fn: Callable[P, R]) -> Callable[P, R]:
61
64
  """Turn library errors into a red message and exit code 1."""
@@ -87,10 +90,18 @@ def _version(value: bool) -> None:
87
90
  @app.callback()
88
91
  def main(
89
92
  verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Show progress logs.")] = False,
93
+ sandbox: Annotated[
94
+ bool,
95
+ typer.Option(
96
+ "--sandbox",
97
+ help="Use the Metrc sandbox (also T3_SANDBOX=1). Put it before the command.",
98
+ ),
99
+ ] = False,
90
100
  version: Annotated[
91
101
  bool, typer.Option("--version", callback=_version, is_eager=True, help="Show the version.")
92
102
  ] = False,
93
103
  ) -> None:
104
+ _global["sandbox"] = sandbox
94
105
  logger = logging.getLogger("t3api_utils")
95
106
  if not any(isinstance(h, RichHandler) for h in logger.handlers):
96
107
  handler = RichHandler(console=console, show_time=False, show_path=False, markup=False)
@@ -115,8 +126,15 @@ def _api_host(store: Store, profile: str | None) -> str:
115
126
  return os.environ.get("T3_API_HOST") or (saved.api_host if saved else None) or DEFAULT_HOST
116
127
 
117
128
 
118
- def _connect(profile: str | None, license: str | None = None) -> t3.T3Client:
119
- return t3.connect(profile, license=license, validate=False)
129
+ def _connect(profile: str | None, license: str | None = None, *, data: bool = True) -> t3.T3Client:
130
+ """A client for a command.
131
+
132
+ ``--sandbox`` (or ``T3_SANDBOX``) applies to data commands. ``data=False``
133
+ is for commands that manage the credential or the profile (logout, keys,
134
+ license pick).
135
+ """
136
+ sandbox = (True if _global["sandbox"] else None) if data else False
137
+ return t3.connect(profile, license=license, validate=False, sandbox=sandbox)
120
138
 
121
139
 
122
140
  def _registry(profile: str | None) -> Registry:
@@ -196,7 +214,7 @@ def logout(
196
214
  store = _store()
197
215
  saved = _require_profile(store, profile)
198
216
  if everywhere:
199
- with _connect(saved.name) as client:
217
+ with _connect(saved.name, data=False) as client:
200
218
  client._call("POST", "/v2/auth/logout")
201
219
  _console.success("Logged out of all Metrc sessions.")
202
220
  was_key = saved.credential == "secret_key"
@@ -221,6 +239,8 @@ def whoami(profile: ProfileOpt = None) -> None:
221
239
  if client.profile:
222
240
  table.add_row("profile", client.profile.name)
223
241
  table.add_row("credential", client.credential_kind or "none")
242
+ if client.sandbox:
243
+ table.add_row("sandbox", "yes")
224
244
  table.add_row("api host", client.base_url)
225
245
  table.add_row("default license", client.license or "")
226
246
  for key in ("username", "hostname", "authMode", "hasT3plus", "t3plusSubscriptionTier", "subscriptionStatus"):
@@ -301,7 +321,8 @@ def license_pick(ctx: typer.Context, profile: ProfileOpt = None) -> None:
301
321
  profile = profile or _group_profile(ctx)
302
322
  store = _store()
303
323
  saved = _require_profile(store, profile)
304
- with _connect(saved.name) as client:
324
+ # The profile's default license is a production setting, so never the sandbox.
325
+ with _connect(saved.name, data=False) as client:
305
326
  saved.license = client.pick_license()
306
327
  store.save_profile(saved, make_default=False)
307
328
  _console.success(f"Default license for {saved.name}: {saved.license}")
@@ -326,7 +347,7 @@ def license_set(ctx: typer.Context, license: str, profile: ProfileOpt = None) ->
326
347
  @handle_errors
327
348
  def keys_list(profile: ProfileOpt = None) -> None:
328
349
  """List the account's secret keys (masked)."""
329
- with _connect(profile) as client:
350
+ with _connect(profile, data=False) as client:
330
351
  keys = client.secret_keys.list()
331
352
  current = client.secret_key
332
353
  table = _console.table("Secret keys")
@@ -428,7 +449,7 @@ def keys_revoke(
428
449
  ):
429
450
  raise typer.Exit(1)
430
451
  store = _store()
431
- with _connect(profile) as client:
452
+ with _connect(profile, data=False) as client:
432
453
  client.secret_keys.delete(key)
433
454
  _console.success(f"Deleted {_console.mask_secret(key)}.")
434
455
  for p in store.profiles():