Skip to content

Commit 73b8069

Browse files
msfrisbieclaude
andcommitted
t3api-utils 2.0.1
Fixes and additions from porting the T3 example scripts to 2.0: - bulk() wraps rows in a list on routes whose body is an array (68 of 85 Metrc writes), which previously answered every row with a 500 - bulk(submit="ask") validates, shows a summary and asks before submitting; bulk(batch_size=N); dynamic=True on writes and bulk() - warn when a json= body's shape doesn't match the spec - public t3.confirm(), t3.ask(parse=...) and t3.choose() - sandbox: ignore production default licenses, warn about licenses the session doesn't have, T3_SANDBOX, t3api --sandbox, client.sandbox and client.hostname - client.download() for file endpoints, streamed and renamed atomically - include= on collect(), iter_rows() and get(), sent repeated - to_csv()/to_json() accept a folder - docs: dry runs are static validation only; array bodies, uploads, downloads, super collections, prompts guide Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 021c22e commit 73b8069

41 files changed

Lines changed: 2090 additions & 175 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,76 @@
11
# Changelog
22

3+
## 2.0.1
4+
5+
Fixes and additions from porting the T3 example scripts to 2.0. Use this
6+
release instead of 2.0.0.
7+
8+
### Fixed
9+
10+
- **`bulk()` on list routes.** Most Metrc write routes (68 of 85) take a JSON
11+
list, even for one object, and answer a bare object with an unexplained
12+
HTTP 500. `bulk()` sent every row as an object, so on those routes every row
13+
came back `invalid`. It now wraps each row in a list where the spec says the
14+
body is one. You still pass one dict per object.
15+
- **Production licenses in the sandbox.** `connect(sandbox=True)` kept
16+
`T3_LICENSE` or the profile's license, and the sandbox answers a request
17+
for a license it doesn't have with an empty 200, so scripts quietly found
18+
nothing. In the sandbox those defaults are now ignored (an explicit
19+
`connect(license=...)` still counts), `enter_sandbox()` clears
20+
`client.license`, and a call naming a license the sandbox session doesn't
21+
have logs a warning.
22+
- **Dry-run wording.** A dry run is static validation: format, required fields
23+
and types, not whether the records a request names exist. The docs,
24+
docstrings and `BulkResult.summary()` now say so. `summary()` reads
25+
`12 passed validation, 1 failed validation` rather than `12 valid, 1 invalid`
26+
(the row statuses themselves are unchanged), and lists statuses in pipeline
27+
order: passed validation, failed validation, submitted, failed, not sent.
28+
29+
### Added
30+
31+
- **`bulk(submit="ask")`** validates every row, shows the route, license,
32+
counts and any failures (and says "sandbox" in the sandbox), then asks
33+
whether to submit, default no. Without a terminal it raises `NotInteractive`
34+
before sending anything. A script can map its flag in one line:
35+
`submit=True if args.yes else "ask"`. On routes with no dry run it asks
36+
instead of needing `confirm=True`.
37+
- **`bulk(batch_size=N)`** sends up to N rows per request on list routes. A
38+
failed request marks every row in it. The default stays 1.
39+
- **`dynamic=True`** on `post()`, `put()`, `patch()`, `delete()` and `bulk()`
40+
sends `applyDynamicValidation=true`, for the routes that offer it.
41+
- **A warning when a `json=` body's shape doesn't match the route**: an object
42+
sent to a list route, or a list to an object route.
43+
- **`t3.confirm()`, `t3.ask()` and `t3.choose()`**, public prompts that match
44+
the library's pickers and raise `NotInteractive` without a terminal.
45+
`confirm()` defaults to no. `ask(parse=float)` asks again until `parse`
46+
succeeds. `choose()` (the existing picker, now exported) turns filtering on
47+
for more than 10 items unless `filterable=` says otherwise. New guide page:
48+
Prompts and pickers.
49+
- **Sandbox:** the `T3_SANDBOX` environment variable (`1`, `true`, `yes` or
50+
`on`), a global `t3api --sandbox` option for the data commands,
51+
`client.sandbox`, `client.hostname` (the Metrc hostname, from `whoami`), and
52+
an INFO log line on entering the sandbox. `t3api whoami` shows a `sandbox`
53+
row there.
54+
- **`client.download(endpoint, to, ...)`** streams a `file` endpoint (manifest
55+
and COA PDFs, item photos) to disk through a temporary file that's renamed
56+
when complete, so a failed download never leaves a partial file.
57+
- **`include=`** on `collect()`, `iter_rows()` and `get()` for super
58+
endpoints, sent as a repeated parameter (the server rejects a comma-joined
59+
one). Values the spec doesn't list are warned about.
60+
- **`to_csv()` and `to_json()` accept a folder**: an existing folder, or a
61+
path ending in `/`, gets the default `<dataModel>__<license>__<time>` file
62+
name inside it.
63+
- `Endpoint.body_type` / `Endpoint.body_is_array` and `Param.choices` in the
64+
spec registry.
65+
- Docs: array bodies, uploads with `files=`, downloads, super collections and
66+
`include`, and the difference between `bulk(confirm=True)` and
67+
`submit="ask"`.
68+
69+
### Changed
70+
71+
- `connect(sandbox=True)` now calls `whoami` once even with `validate=False`,
72+
to log the sandbox hostname.
73+
374
## 2.0.0
475

576
A hard-break rewrite. No 1.x import path still works, and there is no

‎CLAUDE.md‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,20 @@ A release isn't finished until the docs site at <https://classvsoftware.github.i
6464
```
6565
t3api_utils/
6666
__init__.py public API: connect, T3Client, inspect, filter_rows, to_csv, to_json, read_rows,
67-
pick_file, errors, WriteResult/BulkResult/RowResult, TagList, Endpoint, auth classes
68-
client.py T3Client: request(), get/post/put/patch/delete(), collect(), iter_rows(), bulk(),
69-
report(), report_url(), whoami(), licenses(), pickers, namespaces
67+
pick_file, confirm, ask, choose, errors, WriteResult/BulkResult/RowResult, TagList,
68+
Endpoint, auth classes
69+
client.py T3Client: request(), get/post/put/patch/delete(), download(), collect(), iter_rows(),
70+
bulk(), report(), report_url(), whoami(), licenses(), sandbox state, pickers, namespaces
7071
errors.py exception hierarchy; error_from_response() maps status codes to classes
7172
writes.py WriteResult, BulkResult, RowResult, bulk()
7273
reports.py report(), report_url()
7374
tag_lists.py TagLists (client.tag_lists) and TagList
7475
local.py filter_rows(), to_csv(), to_json(), read_rows(), flatten()
7576
pickers.py choose(), pick_license(), pick_endpoint(), pick_file() as Rich tables
77+
prompts.py public confirm() (default no) and ask(parse=...)
7678
_http.py httpx2 client builder, RetryTransport, HTTP log redaction
7779
_ratelimit.py thread-safe token bucket
78-
_api.py send/parse helpers that raise APIError subclasses
80+
_api.py send/parse helpers that raise APIError subclasses; atomic streaming download()
7981
_console.py Rich consoles, purple theme, message/prompt/progress helpers (internal)
8082
_paths.py platformdirs config and cache folders (tests patch these)
8183
spec/
@@ -110,11 +112,13 @@ docs/ mkdocs-material site; reference pages are mkdocstrings
110112
### Key behaviours to preserve
111113

112114
- **Endpoint kinds** come from spec structure alone (`registry.classify`): collection, report, metrc_write, immediate_write, file, object, other. Tests check named endpoints' kinds, not counts.
113-
- **Writes**: `metrc_write` routes are a dry run unless `submit=True`; `immediate_write` routes reject `submit=` entirely. `bulk()` validates every row before submitting; row statuses are valid/invalid/submitted/failed/not_sent.
115+
- **Writes**: `metrc_write` routes are a dry run unless `submit=True`; `immediate_write` routes reject `submit=` entirely. A dry run is static validation only (format, required fields, types), never call it more than that. `bulk()` validates every row before submitting; row statuses are valid/invalid/submitted/failed/not_sent. `submit="ask"` raises `NotInteractive` without a terminal before sending anything.
116+
- **Body shape**: `Endpoint.body_type` comes from the spec. Most Metrc write routes take a JSON list; `bulk()` wraps each row in a list for them, and single writes warn when the `json=` shape doesn't match.
114117
- **Retries** (`_http.RetryTransport`): GET/HEAD/OPTIONS retry on connection errors and 429/502/503/504; writes retry only on 429 and pre-send connection failures. Never retry a write on 5xx or a post-send timeout. Max 3 attempts.
115118
- **Credentials**: secret keys go in the `X-T3-API-Key` header, never the query string, except `report_url()`. The Metrc password is never stored.
116119
- **Redaction**: HTTP debug logs mask auth headers, `/v2/auth/secretkey/{key}` paths, `secretKey=` queries, and `password`/`otp`/`otpSeed`/`secretKey`/`accessToken`/`refreshToken` body fields.
117120
- **Default license** (`client.license`) is applied only to endpoints whose `licenseNumber` is required. An explicit `license=` always wins.
121+
- **Sandbox**: `connect(sandbox=True)` / `T3_SANDBOX` ignores `T3_LICENSE` and the profile's license, `enter_sandbox()` clears `client.license`, and explicit licenses are checked against the session's (the sandbox returns an empty 200 for other licenses). The CLI's `--sandbox` applies to data commands only, never to `login`, `logout`, `keys` or `license`.
118122

119123
### Docs
120124

@@ -220,7 +224,7 @@ def pick_something(items: Sequence[SomeType]) -> SomeType:
220224
items,
221225
["Name", "Details"], # columns after the "#" column
222226
lambda item: [item.name, item.details], # one string per column
223-
filterable=len(items) > 10, # typing text narrows the list
227+
filterable=None, # default: typing text narrows lists of more than 10
224228
)
225229
```
226230

@@ -237,5 +241,6 @@ def pick_something(items: Sequence[SomeType]) -> SomeType:
237241

238242
**Examples in Codebase:**
239243
- `choose()`, `pick_license()`, `pick_endpoint()` and `pick_file()` in `t3api_utils/pickers.py`
244+
- The public `t3.confirm()` and `t3.ask()` in `t3api_utils/prompts.py`
240245
- `T3Client.pick_license()` and `T3Client.pick_endpoint()` in `t3api_utils/client.py`
241246
- The failed-rows table in `writes._show_invalid()` and the CLI tables in `t3api_utils/cli/main.py`

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ A few more things it does:
4747
# Writes are a dry run unless submit=True
4848
client.post("/v2/items/discontinue", license="LIC-00001", json={"id": 12345}, submit=True)
4949

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")
5252

5353
# Server-side report straight to a file
5454
client.report("ITEMS_REPORT", licenses=["LIC-00001"], to="items.xlsx")

‎docs/getting-started.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,8 @@ model, license and time. More in [Local data](guide/local-data.md).
257257
## 9. Write to Metrc
258258

259259
Writes that reach Metrc are a **dry run unless you pass `submit=True`**. A dry
260-
run sends the request to T3, which validates it and stops before Metrc:
260+
run sends the request to T3, which checks its format, required fields and types
261+
and stops before Metrc. It doesn't check that the records you name exist:
261262

262263
```python
263264
result = client.post("/v2/items/discontinue", license=lic, json={"id": 12345})
@@ -274,6 +275,10 @@ print(result.dry_run, result.message) # False Success
274275
A validation failure raises `t3.ValidationError` with the server's explanation
275276
in `.detail`.
276277

278+
Most Metrc write routes take a list of objects, even for one, so their `json=`
279+
is `[{...}]`. `/v2/items/discontinue` is one of the few that take a single
280+
object.
281+
277282
A few T3 routes, such as tag lists and secret keys, act immediately and have
278283
no dry run. Passing `submit=` to one of them raises `ValueError`, so you can't
279284
mistake one for the other. More in [Writes](guide/writes.md).
@@ -297,7 +302,9 @@ print(result.summary())
297302
If any row fails validation, nothing is submitted. In a terminal you're shown
298303
the failures and asked whether to send just the valid rows; in a script,
299304
`on_error="skip"` does that without asking. Leave out `submit=True` to only
300-
validate. `log_to` writes one line per row with its status and message.
305+
validate, or pass `submit="ask"` to see the results and be asked before
306+
anything is submitted. `log_to` writes one line per row with its status and
307+
message.
301308

302309
## 11. Download a report
303310

‎docs/guide/authentication.md‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,15 @@ then `https://api.trackandtrace.tools`.
104104
available as `client.license`, and it's used only by calls whose endpoint
105105
requires a `licenseNumber`. A license passed to a call always wins.
106106

107+
In the [sandbox](#sandbox), only `connect(license=...)` counts: `T3_LICENSE`
108+
and the profile's license are production licenses.
109+
107110
### Other connect() options
108111

109112
| Option | Default | What it does |
110113
|---|---|---|
111114
| `validate` | `True` | Check the credential with `/v2/auth/whoami`. |
112-
| `sandbox` | `False` | Swap the credential for a Metrc sandbox JWT. See [Sandbox](#sandbox). |
115+
| `sandbox` | `T3_SANDBOX`, then `False` | Swap the credential for a Metrc sandbox JWT. See [Sandbox](#sandbox). |
113116
| `spec` | `T3_SPEC`, then `"auto"` | `"bundled"` pins the spec shipped with the package. See [Endpoints and the spec](endpoints-and-spec.md#where-the-spec-comes-from). |
114117
| `rate_limit` | `10.0` | Requests per second across all threads. `None` turns it off. |
115118
| `concurrency` | `10` | Threads used to fetch collection pages. |
@@ -164,15 +167,16 @@ The first profile you create becomes the default.
164167

165168
## Environment variables
166169

167-
These are the only environment variables 2.0 reads. There's no `.t3.env`
168-
file.
170+
These are the only environment variables the library reads. There's no
171+
`.t3.env` file.
169172

170173
| Variable | What it does |
171174
|---|---|
172175
| `T3_SECRET_KEY` | Secret key to use. Wins over any saved profile. |
173176
| `T3_JWT` | JWT to use, if `T3_SECRET_KEY` isn't set. |
174177
| `T3_PROFILE` | Profile to use instead of the default. `t3api` commands that take `--profile` read it too. |
175-
| `T3_LICENSE` | Default license number. |
178+
| `T3_LICENSE` | Default license number. Ignored in the sandbox. |
179+
| `T3_SANDBOX` | `1`, `true`, `yes` or `on` makes `connect()` and the `t3api` data commands use the [Metrc sandbox](#sandbox). |
176180
| `T3_API_HOST` | T3 API base URL, e.g. a staging host. |
177181
| `T3_SPEC` | `bundled` pins the spec shipped with the package. |
178182
| `T3_LOG_HTTP` | `1`, `true`, `yes` or `on` logs every request and response at DEBUG. |
@@ -254,13 +258,36 @@ production:
254258

255259
```python
256260
with t3.connect(sandbox=True) as client:
257-
lic = client.licenses()[0]["licenseNumber"]
261+
lic = client.pick_license() # the sandbox's own licenses
258262
client.post("/v2/items/discontinue", license=lic, json={"id": 12345}, submit=True)
259263
```
260264

265+
To point an existing script or scheduled job at the sandbox without editing
266+
it, set `T3_SANDBOX=1`. The `t3api` command takes `--sandbox` before the
267+
command name (`t3api --sandbox pull ...`); see [the CLI guide](cli.md#conventions).
268+
269+
**Licenses.** The sandbox has its own licenses (such as `SF-SBX-1-101`), and it
270+
answers a request for any other license with an empty result, not an error. A
271+
production license would quietly return nothing. So in the sandbox:
272+
273+
- `T3_LICENSE` and the profile's default license are ignored, and
274+
`client.license` is `None` unless you passed `connect(license=...)`. The
275+
common `license or client.license or client.pick_license()` pattern then
276+
asks you to pick a sandbox license.
277+
- The first time a call names a license, the client lists the session's
278+
licenses (one request, cached) and logs a warning for any license that isn't
279+
one of them.
280+
281+
**Telling where you are.** `client.sandbox` is `True` in the sandbox, and
282+
`client.hostname` is the Metrc hostname behind the credential, such as
283+
`sandbox-me.metrc.com` (from `whoami`). Entering the sandbox logs
284+
`Using the Metrc sandbox (sandbox-me.metrc.com).` at INFO, and
285+
`bulk(submit="ask")` says "sandbox" when it asks.
286+
261287
The client's credential is a JWT from then on (`client.credential_kind ==
262288
"jwt"`), so `report_url()`, which needs a secret key, isn't available. An
263-
existing client can switch with `client.enter_sandbox()`.
289+
existing client can switch with `client.enter_sandbox()`, which also clears
290+
`client.license`.
264291

265292
## Using a credential directly
266293

‎docs/guide/cli.md‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,18 @@ How to run it:
3131
- **Exit codes.** 0 on success, 1 on an error (with a red ✗ message), 130 when
3232
cancelled with Ctrl-C.
3333
- **Global options**, before the command: `--verbose` / `-v` shows the
34-
library's progress logs, and `--version` prints the version.
34+
library's progress logs, `--version` prints the version, and `--sandbox`
35+
uses the [Metrc sandbox](authentication.md#sandbox).
36+
- **Sandbox.** `t3api --sandbox COMMAND` (or `T3_SANDBOX=1`) runs `whoami`,
37+
`pull`, `report` and the `tag-lists` commands against the Metrc sandbox.
38+
The profile's default license is ignored there, so pass `-l` with a sandbox
39+
license (or pick one when asked). `login`, `logout`, `keys` and `license`
40+
manage the credential and the profile, and always use the real account.
41+
42+
```bash
43+
t3api --sandbox whoami
44+
t3api --sandbox pull METRC_ACTIVE_PLANTBATCHES -l SF-SBX-1-101 -o batches.csv
45+
```
3546

3647
## Logging in
3748

@@ -70,7 +81,9 @@ t3api whoami [--profile P]
7081
```
7182

7283
Shows the profile, credential type, API host and default license, plus the
73-
username, Metrc hostname and subscription details T3 reports.
84+
username, Metrc hostname and subscription details T3 reports. With
85+
`t3api --sandbox whoami` it adds a `sandbox` row and shows the sandbox's
86+
hostname.
7487

7588
## Profiles
7689

‎docs/guide/collections.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,38 @@ package = client.get("METRC_ACTIVE_PACKAGES", object_id=67890, license="LIC-0000
137137

138138
`object_id` is the record's Metrc `id`.
139139

140+
## Super collections and include=
141+
142+
Super collections (`/v2/packages/active/super`, `/v2/items/super`,
143+
`/v2/processingjobs/active/super` and others, with IDs like
144+
`METRC_ACTIVE_SUPERPACKAGES`) attach related data to each row. Pick what to
145+
attach with `include=`, a list:
146+
147+
```python
148+
packages = client.collect(
149+
"METRC_ACTIVE_SUPERPACKAGES",
150+
license="LIC-00001",
151+
include=["labResults", "sourceHarvests"],
152+
)
153+
item = client.get("METRC_ACTIVE_SUPERITEMS", object_id=12345, license="LIC-00001", include=["history"])
154+
```
155+
156+
`collect()`, `iter_rows()` and `get()` take it. Each value is sent as its own
157+
`include` parameter, which is what the server needs: a comma-joined
158+
`include=labResults,sourceHarvests` gets a 400. A comma-separated string is
159+
split for you.
160+
161+
Each collection allows its own values. For packages they're `labResults`,
162+
`labResultBatches`, `sourceHarvests`, `history` and `coaResults`; for items,
163+
`notes`, `history`, `ingredients` and `images`. To see them for any endpoint:
164+
165+
```python
166+
client.spec.endpoint("METRC_ACTIVE_SUPERPACKAGES", kind="collection").param("include").choices
167+
```
168+
169+
A value the spec doesn't list logs a warning and is sent anyway, in case your
170+
copy of the spec is behind the server.
171+
140172
## Licenses and the default license
141173

142174
`license=` can be left out when the client has a default license

‎docs/guide/endpoints-and-spec.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,12 @@ Each `Endpoint` has:
6666
| `tags` | `("Items",)` |
6767
| `summary` | `"List of active items"` |
6868
| `params` | the operation's parameters, each with `name`, `location`, `required`, `description` and `schema` |
69+
| `body_type` | `"array"` or `"object"` for routes with a JSON body, else `None`. `body_is_array` is `True` for the [list routes](writes.md#array-bodies). |
6970

7071
`ep.param("licenseNumber")` returns one parameter, and `ep.label()` gives a
71-
readable `GET /v2/items (METRC_ACTIVE_ITEMS)`.
72+
readable `GET /v2/items (METRC_ACTIVE_ITEMS)`. A parameter's `choices` are the
73+
values the spec allows, such as a super collection's `include` values, or `()`
74+
when it doesn't list any.
7275

7376
In a terminal, `client.pick_endpoint()` shows a numbered table of collections
7477
that you can narrow by typing. `client.pick_endpoint(kind=None)` shows every
@@ -92,7 +95,7 @@ structure. The rules are checked top to bottom:
9295
| `report` | Can respond with CSV or XLSX | 83 | `report()`, `report_url()` |
9396
| `metrc_write` | Non-GET that takes the `submit` parameter | 85 | `post()` / `put()` / `patch()` / `delete()`, `bulk()` |
9497
| `immediate_write` | Non-GET without `submit` | 28 | the same, without `submit=` |
95-
| `file` | GET returning a PDF or an image | 5 | `get()`, which returns `bytes` |
98+
| `file` | GET returning a PDF or an image | 5 | `download()` to a file, or `get()`, which returns `bytes` |
9699
| `object` | GET with an `{object_id}` path parameter | 144 | `get(..., object_id=...)` |
97100
| `other` | Everything else, e.g. `/v2/licenses`, `/v2/auth/whoami` | 124 | `get()` / `request()` |
98101

@@ -125,6 +128,7 @@ The common collection parameters have Python names:
125128
| `filter_logic` | `filterLogic` |
126129
| `sort` | `sort` |
127130
| `mask` (string or list) | `collectionMask`, comma-joined |
131+
| `include` (string or list) | one `include=` per item |
128132
| `page_size` | `pageSize` |
129133

130134
`page`, `submit` and `secretKey` are managed by the library; don't pass them in

0 commit comments

Comments
 (0)