discogs-sdk 0.6.0__tar.gz → 0.7.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.
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/PKG-INFO +111 -16
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/README.md +110 -15
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/pyproject.toml +2 -4
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/pyproject.toml.orig +5 -6
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/__init__.py +12 -2
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_client.py +67 -62
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_lazy.py +40 -1
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_oauth.py +4 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_paginator.py +20 -9
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_resource.py +11 -2
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/collection.py +21 -8
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/exports.py +13 -3
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/marketplace.py +107 -13
- discogs_sdk-0.7.0/src/discogs_sdk/_async/resources/uploads.py +70 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/users.py +0 -3
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/wantlist.py +15 -4
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_base_client.py +56 -1
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_cache.py +55 -6
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_exceptions.py +43 -12
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_client.py +5 -4
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_lazy.py +3 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_oauth.py +4 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_paginator.py +19 -9
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_resource.py +4 -1
- discogs_sdk-0.7.0/src/discogs_sdk/_sync/resources/__init__.py +2 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/collection.py +22 -7
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/exports.py +13 -3
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/marketplace.py +107 -11
- discogs_sdk-0.7.0/src/discogs_sdk/_sync/resources/uploads.py +71 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/users.py +0 -3
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/wantlist.py +11 -4
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/__init__.py +6 -2
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/_common.py +37 -14
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/_lazy_fields.py +2 -2
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/collection.py +1 -1
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/marketplace.py +13 -3
- discogs_sdk-0.7.0/src/discogs_sdk/py.typed +0 -0
- discogs_sdk-0.6.0/src/discogs_sdk/_async/resources/__init__.py +0 -75
- discogs_sdk-0.6.0/src/discogs_sdk/_async/resources/uploads.py +0 -48
- discogs_sdk-0.6.0/src/discogs_sdk/_sync/resources/__init__.py +0 -78
- discogs_sdk-0.6.0/src/discogs_sdk/_sync/resources/uploads.py +0 -49
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/LICENSE.txt +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/__init__.py +0 -0
- /discogs_sdk-0.6.0/src/discogs_sdk/py.typed → /discogs_sdk-0.7.0/src/discogs_sdk/_async/resources/__init__.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/artists.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/labels.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/lists.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/masters.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/releases.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/search.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_events.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_oauth_types.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/__init__.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/artists.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/labels.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/lists.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/masters.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/releases.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/search.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/_timestamp.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/artist.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/export.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/label.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/list_.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/master.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/release.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/search.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/upload.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/user.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/wantlist.py +0 -0
- {discogs_sdk-0.6.0 → discogs_sdk-0.7.0}/src/discogs_sdk/oauth.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: discogs-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Modern Python client for the Discogs API
|
|
5
5
|
Keywords: api,discogs,music,python,sdk
|
|
6
6
|
Author: Jean-Marc Fontaine
|
|
@@ -162,7 +162,9 @@ label = client.labels.get(647)
|
|
|
162
162
|
|
|
163
163
|
These lazy resources are read-only views: assigning to one of their attributes raises `AttributeError`, since the
|
|
164
164
|
value would never reach Discogs. Where the API accepts writes, they go through a resource method such as
|
|
165
|
-
`release.rating.update()` or `user.wantlist.update()`.
|
|
165
|
+
`release.rating.update()` or `user.wantlist.update()`. Those methods take the fields Discogs documents as typed
|
|
166
|
+
keyword parameters: an optional field you omit, or pass as `None`, is not sent, so an update leaves it unchanged, and a
|
|
167
|
+
misspelled name raises `TypeError` before any request is made.
|
|
166
168
|
|
|
167
169
|
Each identifier you pass (username, order id, release id and so on) is sent as a
|
|
168
170
|
single, percent-encoded path segment, so a `/`, `?` or `#` in it cannot reach a
|
|
@@ -251,13 +253,14 @@ for want in user.wantlist.list():
|
|
|
251
253
|
```python
|
|
252
254
|
# Listings
|
|
253
255
|
listing = client.marketplace.listings.get(123456789)
|
|
254
|
-
new
|
|
256
|
+
# The response identifies the new listing; it is not a full Listing.
|
|
257
|
+
created = client.marketplace.listings.create(
|
|
255
258
|
release_id=352665,
|
|
256
259
|
condition="Very Good Plus (VG+)",
|
|
257
260
|
price=25.00,
|
|
258
261
|
)
|
|
259
|
-
client.marketplace.listings.update(
|
|
260
|
-
client.marketplace.listings.delete(
|
|
262
|
+
client.marketplace.listings.update(created.listing_id, price=22.50)
|
|
263
|
+
client.marketplace.listings.delete(created.listing_id)
|
|
261
264
|
|
|
262
265
|
# Orders
|
|
263
266
|
for order in client.marketplace.orders.list(status="Payment Received"):
|
|
@@ -275,8 +278,8 @@ from discogs_sdk import NotFoundError, RateLimitError, AuthenticationError
|
|
|
275
278
|
try:
|
|
276
279
|
release = client.releases.get(999999999)
|
|
277
280
|
_ = release.title
|
|
278
|
-
except NotFoundError:
|
|
279
|
-
print("Not found")
|
|
281
|
+
except NotFoundError as exc:
|
|
282
|
+
print(f"Not found: {exc.method} {exc.url}")
|
|
280
283
|
except RateLimitError as exc:
|
|
281
284
|
print(f"Rate limited, retry after {exc.retry_after}s")
|
|
282
285
|
if exc.ratelimit: # the 429's own X-Discogs-Ratelimit* headers, when present
|
|
@@ -285,6 +288,13 @@ except AuthenticationError:
|
|
|
285
288
|
print("Bad credentials")
|
|
286
289
|
```
|
|
287
290
|
|
|
291
|
+
Every `DiscogsAPIError` names the request that failed: `exc.method` (upper-case) and
|
|
292
|
+
`exc.url` (fully resolved, query string included, as in `RequestEvent.url`), so an
|
|
293
|
+
error raised while iterating a listing points at the page that failed. `exc.ratelimit`
|
|
294
|
+
holds the `RateLimit` from the failing response's `X-Discogs-Ratelimit*` headers for
|
|
295
|
+
any status, or `None` when they are missing. All three are `None` on an exception you
|
|
296
|
+
construct yourself without them.
|
|
297
|
+
|
|
288
298
|
The full exception hierarchy:
|
|
289
299
|
|
|
290
300
|
```
|
|
@@ -306,10 +316,18 @@ raises `DiscogsConnectionError`, and a successful response missing either
|
|
|
306
316
|
`oauth_token` or `oauth_token_secret` raises `DiscogsAPIError` naming any
|
|
307
317
|
`oauth_problem`. They never retry: the access-token exchange is sent at most once.
|
|
308
318
|
|
|
319
|
+
`client.exports.request()` and `client.uploads.create()`, `change()` and `delete()`
|
|
320
|
+
return the new job's id, read from the `Location` header of the response, for
|
|
321
|
+
`exports.get()`, `exports.download()` and `uploads.get()`. A successful response
|
|
322
|
+
whose `Location` is missing or does not end in an integer raises `DiscogsAPIError`
|
|
323
|
+
with that 2xx status: Discogs accepted the request, so the job probably exists. Find
|
|
324
|
+
it with `exports.list()` or `uploads.list()` instead of submitting again.
|
|
325
|
+
|
|
309
326
|
`str(exc)` on a `DiscogsAPIError` is a short summary, `"<status>: <message>"`. The
|
|
310
327
|
message is the body's `message` when that is a non-empty string, otherwise the body
|
|
311
|
-
itself, cut to 500 characters so a gateway error page does not flood logs
|
|
312
|
-
|
|
328
|
+
itself, cut to 500 characters so a gateway error page does not flood logs; the errors
|
|
329
|
+
above that the SDK raises on a 2xx describe the problem instead. The full payload
|
|
330
|
+
stays in `exc.response_body`.
|
|
313
331
|
|
|
314
332
|
Every SDK exception survives `pickle`, `copy.copy` and `copy.deepcopy` with its
|
|
315
333
|
attributes (`status_code`, `response_body`, `retry_after`, `ratelimit`, `method`,
|
|
@@ -384,7 +402,7 @@ The [`examples/`](examples/) directory has runnable scripts for every feature:
|
|
|
384
402
|
| `base_url` | `https://api.discogs.com` | API base URL; pagination `next` links are rebased onto it, and a link to any origin other than it or `https://api.discogs.com` raises `DiscogsError` |
|
|
385
403
|
| `cache_dir` | `None` | Directory for SQLite cache; in-memory when omitted. Used only with `cache=True` |
|
|
386
404
|
| `cache_ttl` | `3600.0` | Cache time-to-live in seconds. Used only with `cache=True` |
|
|
387
|
-
| `cache` | `False` | `True` builds the built-in backend from `cache_dir` and `cache_ttl`; or pass a
|
|
405
|
+
| `cache` | `False` | `True` builds the built-in backend from `cache_dir` and `cache_ttl`; or pass a `ResponseCache` instance (see [Custom backends](#custom-backends)), which carries its own TTL and storage and is never closed by the client |
|
|
388
406
|
| `consumer_key` | `None` | OAuth consumer key |
|
|
389
407
|
| `consumer_secret` | `None` | OAuth consumer secret |
|
|
390
408
|
| `http_client` | `None` | Custom `httpx2.Client` or `httpx2.AsyncClient` |
|
|
@@ -427,6 +445,12 @@ A cache built from `cache=True` belongs to the client, and `client.close()` clos
|
|
|
427
445
|
pass in stays yours, like an injected `http_client`: `client.close()` never closes it, so one cache can outlive any of
|
|
428
446
|
the clients sharing it. Call its `close()` yourself once every client using it is done.
|
|
429
447
|
|
|
448
|
+
The built-in caches drop an expired entry when the same request looks it up again, and remove every expired entry at
|
|
449
|
+
least once per 100 stores; the SQLite cache also does when it opens, so `cache.db` does not carry expired rows over
|
|
450
|
+
from earlier runs. Entries still within `cache_ttl` stay, so the cache's size is bounded by the TTL times the rate of
|
|
451
|
+
new responses, not by a fixed count. Deleted rows free pages inside `cache.db` for reuse; the file itself does not
|
|
452
|
+
shrink.
|
|
453
|
+
|
|
430
454
|
The SQLite cache never fails a request. If its database is locked by another process, read-only, full or corrupt,
|
|
431
455
|
it logs a warning on the `discogs_sdk` logger and carries on: a lookup counts as a miss and a store is skipped, so the
|
|
432
456
|
response still reaches you. Using the cache after it has been closed raises `RuntimeError`. The database runs in WAL
|
|
@@ -463,6 +487,71 @@ with client.cache_only():
|
|
|
463
487
|
print(f"Not cached: {exc.method} {exc.url}")
|
|
464
488
|
```
|
|
465
489
|
|
|
490
|
+
#### Custom backends
|
|
491
|
+
|
|
492
|
+
The cache types are exported from `discogs_sdk`. To store responses elsewhere, subclass `ResponseCache` and implement
|
|
493
|
+
four methods: `get(key)` returns a `CacheEntry`, the `(status_code, headers, body)` tuple, or `None` on a miss or an
|
|
494
|
+
expired entry; `set(key, status_code, headers, body)` stores one; `clear()` drops every entry; `close()` releases
|
|
495
|
+
whatever the backend holds. The base constructor takes the `ttl` in seconds, and the backend is the one that enforces
|
|
496
|
+
it. A backend must be thread-safe: so that disk I/O never blocks the event loop, `AsyncDiscogs` may call `get`, `set`
|
|
497
|
+
and `clear` from worker threads, while `clear_cache()` and `close()` run on the calling thread, and concurrent requests
|
|
498
|
+
overlap. The example takes a lock for that:
|
|
499
|
+
|
|
500
|
+
```python
|
|
501
|
+
import threading
|
|
502
|
+
|
|
503
|
+
from discogs_sdk import CacheEntry, Discogs, ResponseCache
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
class DictCache(ResponseCache):
|
|
507
|
+
"""Unbounded dict, no expiry."""
|
|
508
|
+
|
|
509
|
+
def __init__(self) -> None:
|
|
510
|
+
super().__init__(ttl=0)
|
|
511
|
+
self._lock = threading.Lock()
|
|
512
|
+
self._store: dict[str, CacheEntry] = {}
|
|
513
|
+
|
|
514
|
+
def get(self, key: str) -> CacheEntry | None:
|
|
515
|
+
with self._lock:
|
|
516
|
+
return self._store.get(key)
|
|
517
|
+
|
|
518
|
+
def set(
|
|
519
|
+
self, key: str, status_code: int, headers: dict[str, str], body: bytes
|
|
520
|
+
) -> None:
|
|
521
|
+
with self._lock:
|
|
522
|
+
self._store[key] = (status_code, headers, body)
|
|
523
|
+
|
|
524
|
+
def clear(self) -> None:
|
|
525
|
+
with self._lock:
|
|
526
|
+
self._store.clear()
|
|
527
|
+
|
|
528
|
+
def close(self) -> None:
|
|
529
|
+
pass
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
client = Discogs(cache=DictCache())
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
`MemoryCache(ttl)` and `SQLiteCache(ttl, cache_dir)` are the backends `cache=True` builds. Create one yourself to pass
|
|
536
|
+
the same instance to several clients, `Discogs` and `AsyncDiscogs` alike. Clients with the same credentials share
|
|
537
|
+
entries; keys carry a non-reversible digest of the credentials, so clients with different ones still never see each
|
|
538
|
+
other's private responses. Close the cache yourself once every client using it is done:
|
|
539
|
+
|
|
540
|
+
```python
|
|
541
|
+
from pathlib import Path
|
|
542
|
+
|
|
543
|
+
from discogs_sdk import Discogs, SQLiteCache
|
|
544
|
+
|
|
545
|
+
shared = SQLiteCache(ttl=3600, cache_dir=Path.home() / ".cache" / "my-app")
|
|
546
|
+
first = Discogs(token="YOUR_TOKEN", cache=shared)
|
|
547
|
+
second = Discogs(token="YOUR_TOKEN", cache=shared)
|
|
548
|
+
print(first.releases.get(352665).title) # fetched from the API
|
|
549
|
+
print(second.releases.get(352665).title) # served from the shared cache
|
|
550
|
+
first.close()
|
|
551
|
+
second.close()
|
|
552
|
+
shared.close() # a client never closes a cache passed in
|
|
553
|
+
```
|
|
554
|
+
|
|
466
555
|
### Observability
|
|
467
556
|
|
|
468
557
|
Every live response carries Discogs' `X-Discogs-Ratelimit`, `X-Discogs-Ratelimit-Used` and
|
|
@@ -472,9 +561,9 @@ leaves the last known value in place. It is `None` until the first live response
|
|
|
472
561
|
|
|
473
562
|
`on_request` receives one `RequestEvent` per logical request, invoked synchronously — after a cache hit, or after the
|
|
474
563
|
final network response and before any error is raised, so the event exists even when the call raises. Intermediate
|
|
475
|
-
retried attempts do not emit; the final event carries `attempts`. A call that ends in `DiscogsConnectionError`
|
|
476
|
-
nothing, since there is no response. Exceptions raised by the callback propagate unchanged;
|
|
477
|
-
block in it, because the async client calls it from the event loop.
|
|
564
|
+
retried attempts do not emit; the final event carries `attempts`. A call that ends in `DiscogsConnectionError` or
|
|
565
|
+
`CacheMissError` emits nothing, since there is no response. Exceptions raised by the callback propagate unchanged;
|
|
566
|
+
keep it cheap and never block in it, because the async client calls it from the event loop.
|
|
478
567
|
|
|
479
568
|
| Field | Meaning |
|
|
480
569
|
|---|---|
|
|
@@ -529,6 +618,12 @@ with ThreadPoolExecutor() as pool:
|
|
|
529
618
|
print(future.result()) # The Downward Spiral, fetched from the API
|
|
530
619
|
```
|
|
531
620
|
|
|
621
|
+
An unresolved `AsyncDiscogs` proxy awaited from several tasks at once sends one request and hands every task the same
|
|
622
|
+
model (or the same exception; a failure is not kept, so the next await tries again). That request runs in the context
|
|
623
|
+
of the task that awaited first, so its `no_cache()` or `cache_only()` scope, or the lack of one, applies to all of them.
|
|
624
|
+
Enter the scope before the first await, or call `get()` again inside it for a proxy of your own. Cancelling one waiting
|
|
625
|
+
task leaves the request and the other tasks alone.
|
|
626
|
+
|
|
532
627
|
A page returned by `.list()` or `search()` is a single-pass iterator for one consumer. Several threads or tasks
|
|
533
628
|
iterating the same page race on its position and can fetch a page twice and yield its items twice, and a page that
|
|
534
629
|
is exhausted yields nothing on a second pass. Call `.list()` or `search()` again for each consumer and each pass.
|
|
@@ -538,8 +633,9 @@ completion order rather than start order, and with several threads the callback
|
|
|
538
633
|
`client.ratelimit` is the value from whichever live response completed last, not necessarily the one with the lowest
|
|
539
634
|
`remaining`: under concurrency it is a hint for pacing, not a global count.
|
|
540
635
|
|
|
541
|
-
The cache that `cache=True` builds locks internally. A custom `ResponseCache`
|
|
542
|
-
|
|
636
|
+
The cache that `cache=True` builds locks internally. A custom `ResponseCache` needs its own locking whenever several
|
|
637
|
+
threads share it, and with `AsyncDiscogs` that is always the case: the async client may call the cache from worker
|
|
638
|
+
threads so that disk I/O never blocks the event loop, and it calls its methods without synchronisation.
|
|
543
639
|
|
|
544
640
|
### Custom HTTP clients
|
|
545
641
|
|
|
@@ -572,7 +668,6 @@ Model fields use clean Python names. Where the Discogs API uses inconsistent or
|
|
|
572
668
|
| `finished_ts` | `finished_at` | `Export`, `Upload` |
|
|
573
669
|
| `from` | `from_user` | `OrderMessage` |
|
|
574
670
|
| `list_id` | `id` | `List_` |
|
|
575
|
-
| `listing_id` | `id` | `Listing` |
|
|
576
671
|
| `modified_ts` | `modified_at` | `List_` |
|
|
577
672
|
| `namevariations` | `name_variations` | `Artist` |
|
|
578
673
|
| `qty` | `quantity` | `Format` |
|
|
@@ -132,7 +132,9 @@ label = client.labels.get(647)
|
|
|
132
132
|
|
|
133
133
|
These lazy resources are read-only views: assigning to one of their attributes raises `AttributeError`, since the
|
|
134
134
|
value would never reach Discogs. Where the API accepts writes, they go through a resource method such as
|
|
135
|
-
`release.rating.update()` or `user.wantlist.update()`.
|
|
135
|
+
`release.rating.update()` or `user.wantlist.update()`. Those methods take the fields Discogs documents as typed
|
|
136
|
+
keyword parameters: an optional field you omit, or pass as `None`, is not sent, so an update leaves it unchanged, and a
|
|
137
|
+
misspelled name raises `TypeError` before any request is made.
|
|
136
138
|
|
|
137
139
|
Each identifier you pass (username, order id, release id and so on) is sent as a
|
|
138
140
|
single, percent-encoded path segment, so a `/`, `?` or `#` in it cannot reach a
|
|
@@ -221,13 +223,14 @@ for want in user.wantlist.list():
|
|
|
221
223
|
```python
|
|
222
224
|
# Listings
|
|
223
225
|
listing = client.marketplace.listings.get(123456789)
|
|
224
|
-
new
|
|
226
|
+
# The response identifies the new listing; it is not a full Listing.
|
|
227
|
+
created = client.marketplace.listings.create(
|
|
225
228
|
release_id=352665,
|
|
226
229
|
condition="Very Good Plus (VG+)",
|
|
227
230
|
price=25.00,
|
|
228
231
|
)
|
|
229
|
-
client.marketplace.listings.update(
|
|
230
|
-
client.marketplace.listings.delete(
|
|
232
|
+
client.marketplace.listings.update(created.listing_id, price=22.50)
|
|
233
|
+
client.marketplace.listings.delete(created.listing_id)
|
|
231
234
|
|
|
232
235
|
# Orders
|
|
233
236
|
for order in client.marketplace.orders.list(status="Payment Received"):
|
|
@@ -245,8 +248,8 @@ from discogs_sdk import NotFoundError, RateLimitError, AuthenticationError
|
|
|
245
248
|
try:
|
|
246
249
|
release = client.releases.get(999999999)
|
|
247
250
|
_ = release.title
|
|
248
|
-
except NotFoundError:
|
|
249
|
-
print("Not found")
|
|
251
|
+
except NotFoundError as exc:
|
|
252
|
+
print(f"Not found: {exc.method} {exc.url}")
|
|
250
253
|
except RateLimitError as exc:
|
|
251
254
|
print(f"Rate limited, retry after {exc.retry_after}s")
|
|
252
255
|
if exc.ratelimit: # the 429's own X-Discogs-Ratelimit* headers, when present
|
|
@@ -255,6 +258,13 @@ except AuthenticationError:
|
|
|
255
258
|
print("Bad credentials")
|
|
256
259
|
```
|
|
257
260
|
|
|
261
|
+
Every `DiscogsAPIError` names the request that failed: `exc.method` (upper-case) and
|
|
262
|
+
`exc.url` (fully resolved, query string included, as in `RequestEvent.url`), so an
|
|
263
|
+
error raised while iterating a listing points at the page that failed. `exc.ratelimit`
|
|
264
|
+
holds the `RateLimit` from the failing response's `X-Discogs-Ratelimit*` headers for
|
|
265
|
+
any status, or `None` when they are missing. All three are `None` on an exception you
|
|
266
|
+
construct yourself without them.
|
|
267
|
+
|
|
258
268
|
The full exception hierarchy:
|
|
259
269
|
|
|
260
270
|
```
|
|
@@ -276,10 +286,18 @@ raises `DiscogsConnectionError`, and a successful response missing either
|
|
|
276
286
|
`oauth_token` or `oauth_token_secret` raises `DiscogsAPIError` naming any
|
|
277
287
|
`oauth_problem`. They never retry: the access-token exchange is sent at most once.
|
|
278
288
|
|
|
289
|
+
`client.exports.request()` and `client.uploads.create()`, `change()` and `delete()`
|
|
290
|
+
return the new job's id, read from the `Location` header of the response, for
|
|
291
|
+
`exports.get()`, `exports.download()` and `uploads.get()`. A successful response
|
|
292
|
+
whose `Location` is missing or does not end in an integer raises `DiscogsAPIError`
|
|
293
|
+
with that 2xx status: Discogs accepted the request, so the job probably exists. Find
|
|
294
|
+
it with `exports.list()` or `uploads.list()` instead of submitting again.
|
|
295
|
+
|
|
279
296
|
`str(exc)` on a `DiscogsAPIError` is a short summary, `"<status>: <message>"`. The
|
|
280
297
|
message is the body's `message` when that is a non-empty string, otherwise the body
|
|
281
|
-
itself, cut to 500 characters so a gateway error page does not flood logs
|
|
282
|
-
|
|
298
|
+
itself, cut to 500 characters so a gateway error page does not flood logs; the errors
|
|
299
|
+
above that the SDK raises on a 2xx describe the problem instead. The full payload
|
|
300
|
+
stays in `exc.response_body`.
|
|
283
301
|
|
|
284
302
|
Every SDK exception survives `pickle`, `copy.copy` and `copy.deepcopy` with its
|
|
285
303
|
attributes (`status_code`, `response_body`, `retry_after`, `ratelimit`, `method`,
|
|
@@ -354,7 +372,7 @@ The [`examples/`](examples/) directory has runnable scripts for every feature:
|
|
|
354
372
|
| `base_url` | `https://api.discogs.com` | API base URL; pagination `next` links are rebased onto it, and a link to any origin other than it or `https://api.discogs.com` raises `DiscogsError` |
|
|
355
373
|
| `cache_dir` | `None` | Directory for SQLite cache; in-memory when omitted. Used only with `cache=True` |
|
|
356
374
|
| `cache_ttl` | `3600.0` | Cache time-to-live in seconds. Used only with `cache=True` |
|
|
357
|
-
| `cache` | `False` | `True` builds the built-in backend from `cache_dir` and `cache_ttl`; or pass a
|
|
375
|
+
| `cache` | `False` | `True` builds the built-in backend from `cache_dir` and `cache_ttl`; or pass a `ResponseCache` instance (see [Custom backends](#custom-backends)), which carries its own TTL and storage and is never closed by the client |
|
|
358
376
|
| `consumer_key` | `None` | OAuth consumer key |
|
|
359
377
|
| `consumer_secret` | `None` | OAuth consumer secret |
|
|
360
378
|
| `http_client` | `None` | Custom `httpx2.Client` or `httpx2.AsyncClient` |
|
|
@@ -397,6 +415,12 @@ A cache built from `cache=True` belongs to the client, and `client.close()` clos
|
|
|
397
415
|
pass in stays yours, like an injected `http_client`: `client.close()` never closes it, so one cache can outlive any of
|
|
398
416
|
the clients sharing it. Call its `close()` yourself once every client using it is done.
|
|
399
417
|
|
|
418
|
+
The built-in caches drop an expired entry when the same request looks it up again, and remove every expired entry at
|
|
419
|
+
least once per 100 stores; the SQLite cache also does when it opens, so `cache.db` does not carry expired rows over
|
|
420
|
+
from earlier runs. Entries still within `cache_ttl` stay, so the cache's size is bounded by the TTL times the rate of
|
|
421
|
+
new responses, not by a fixed count. Deleted rows free pages inside `cache.db` for reuse; the file itself does not
|
|
422
|
+
shrink.
|
|
423
|
+
|
|
400
424
|
The SQLite cache never fails a request. If its database is locked by another process, read-only, full or corrupt,
|
|
401
425
|
it logs a warning on the `discogs_sdk` logger and carries on: a lookup counts as a miss and a store is skipped, so the
|
|
402
426
|
response still reaches you. Using the cache after it has been closed raises `RuntimeError`. The database runs in WAL
|
|
@@ -433,6 +457,71 @@ with client.cache_only():
|
|
|
433
457
|
print(f"Not cached: {exc.method} {exc.url}")
|
|
434
458
|
```
|
|
435
459
|
|
|
460
|
+
#### Custom backends
|
|
461
|
+
|
|
462
|
+
The cache types are exported from `discogs_sdk`. To store responses elsewhere, subclass `ResponseCache` and implement
|
|
463
|
+
four methods: `get(key)` returns a `CacheEntry`, the `(status_code, headers, body)` tuple, or `None` on a miss or an
|
|
464
|
+
expired entry; `set(key, status_code, headers, body)` stores one; `clear()` drops every entry; `close()` releases
|
|
465
|
+
whatever the backend holds. The base constructor takes the `ttl` in seconds, and the backend is the one that enforces
|
|
466
|
+
it. A backend must be thread-safe: so that disk I/O never blocks the event loop, `AsyncDiscogs` may call `get`, `set`
|
|
467
|
+
and `clear` from worker threads, while `clear_cache()` and `close()` run on the calling thread, and concurrent requests
|
|
468
|
+
overlap. The example takes a lock for that:
|
|
469
|
+
|
|
470
|
+
```python
|
|
471
|
+
import threading
|
|
472
|
+
|
|
473
|
+
from discogs_sdk import CacheEntry, Discogs, ResponseCache
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
class DictCache(ResponseCache):
|
|
477
|
+
"""Unbounded dict, no expiry."""
|
|
478
|
+
|
|
479
|
+
def __init__(self) -> None:
|
|
480
|
+
super().__init__(ttl=0)
|
|
481
|
+
self._lock = threading.Lock()
|
|
482
|
+
self._store: dict[str, CacheEntry] = {}
|
|
483
|
+
|
|
484
|
+
def get(self, key: str) -> CacheEntry | None:
|
|
485
|
+
with self._lock:
|
|
486
|
+
return self._store.get(key)
|
|
487
|
+
|
|
488
|
+
def set(
|
|
489
|
+
self, key: str, status_code: int, headers: dict[str, str], body: bytes
|
|
490
|
+
) -> None:
|
|
491
|
+
with self._lock:
|
|
492
|
+
self._store[key] = (status_code, headers, body)
|
|
493
|
+
|
|
494
|
+
def clear(self) -> None:
|
|
495
|
+
with self._lock:
|
|
496
|
+
self._store.clear()
|
|
497
|
+
|
|
498
|
+
def close(self) -> None:
|
|
499
|
+
pass
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
client = Discogs(cache=DictCache())
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
`MemoryCache(ttl)` and `SQLiteCache(ttl, cache_dir)` are the backends `cache=True` builds. Create one yourself to pass
|
|
506
|
+
the same instance to several clients, `Discogs` and `AsyncDiscogs` alike. Clients with the same credentials share
|
|
507
|
+
entries; keys carry a non-reversible digest of the credentials, so clients with different ones still never see each
|
|
508
|
+
other's private responses. Close the cache yourself once every client using it is done:
|
|
509
|
+
|
|
510
|
+
```python
|
|
511
|
+
from pathlib import Path
|
|
512
|
+
|
|
513
|
+
from discogs_sdk import Discogs, SQLiteCache
|
|
514
|
+
|
|
515
|
+
shared = SQLiteCache(ttl=3600, cache_dir=Path.home() / ".cache" / "my-app")
|
|
516
|
+
first = Discogs(token="YOUR_TOKEN", cache=shared)
|
|
517
|
+
second = Discogs(token="YOUR_TOKEN", cache=shared)
|
|
518
|
+
print(first.releases.get(352665).title) # fetched from the API
|
|
519
|
+
print(second.releases.get(352665).title) # served from the shared cache
|
|
520
|
+
first.close()
|
|
521
|
+
second.close()
|
|
522
|
+
shared.close() # a client never closes a cache passed in
|
|
523
|
+
```
|
|
524
|
+
|
|
436
525
|
### Observability
|
|
437
526
|
|
|
438
527
|
Every live response carries Discogs' `X-Discogs-Ratelimit`, `X-Discogs-Ratelimit-Used` and
|
|
@@ -442,9 +531,9 @@ leaves the last known value in place. It is `None` until the first live response
|
|
|
442
531
|
|
|
443
532
|
`on_request` receives one `RequestEvent` per logical request, invoked synchronously — after a cache hit, or after the
|
|
444
533
|
final network response and before any error is raised, so the event exists even when the call raises. Intermediate
|
|
445
|
-
retried attempts do not emit; the final event carries `attempts`. A call that ends in `DiscogsConnectionError`
|
|
446
|
-
nothing, since there is no response. Exceptions raised by the callback propagate unchanged;
|
|
447
|
-
block in it, because the async client calls it from the event loop.
|
|
534
|
+
retried attempts do not emit; the final event carries `attempts`. A call that ends in `DiscogsConnectionError` or
|
|
535
|
+
`CacheMissError` emits nothing, since there is no response. Exceptions raised by the callback propagate unchanged;
|
|
536
|
+
keep it cheap and never block in it, because the async client calls it from the event loop.
|
|
448
537
|
|
|
449
538
|
| Field | Meaning |
|
|
450
539
|
|---|---|
|
|
@@ -499,6 +588,12 @@ with ThreadPoolExecutor() as pool:
|
|
|
499
588
|
print(future.result()) # The Downward Spiral, fetched from the API
|
|
500
589
|
```
|
|
501
590
|
|
|
591
|
+
An unresolved `AsyncDiscogs` proxy awaited from several tasks at once sends one request and hands every task the same
|
|
592
|
+
model (or the same exception; a failure is not kept, so the next await tries again). That request runs in the context
|
|
593
|
+
of the task that awaited first, so its `no_cache()` or `cache_only()` scope, or the lack of one, applies to all of them.
|
|
594
|
+
Enter the scope before the first await, or call `get()` again inside it for a proxy of your own. Cancelling one waiting
|
|
595
|
+
task leaves the request and the other tasks alone.
|
|
596
|
+
|
|
502
597
|
A page returned by `.list()` or `search()` is a single-pass iterator for one consumer. Several threads or tasks
|
|
503
598
|
iterating the same page race on its position and can fetch a page twice and yield its items twice, and a page that
|
|
504
599
|
is exhausted yields nothing on a second pass. Call `.list()` or `search()` again for each consumer and each pass.
|
|
@@ -508,8 +603,9 @@ completion order rather than start order, and with several threads the callback
|
|
|
508
603
|
`client.ratelimit` is the value from whichever live response completed last, not necessarily the one with the lowest
|
|
509
604
|
`remaining`: under concurrency it is a hint for pacing, not a global count.
|
|
510
605
|
|
|
511
|
-
The cache that `cache=True` builds locks internally. A custom `ResponseCache`
|
|
512
|
-
|
|
606
|
+
The cache that `cache=True` builds locks internally. A custom `ResponseCache` needs its own locking whenever several
|
|
607
|
+
threads share it, and with `AsyncDiscogs` that is always the case: the async client may call the cache from worker
|
|
608
|
+
threads so that disk I/O never blocks the event loop, and it calls its methods without synchronisation.
|
|
513
609
|
|
|
514
610
|
### Custom HTTP clients
|
|
515
611
|
|
|
@@ -542,7 +638,6 @@ Model fields use clean Python names. Where the Discogs API uses inconsistent or
|
|
|
542
638
|
| `finished_ts` | `finished_at` | `Export`, `Upload` |
|
|
543
639
|
| `from` | `from_user` | `OrderMessage` |
|
|
544
640
|
| `list_id` | `id` | `List_` |
|
|
545
|
-
| `listing_id` | `id` | `Listing` |
|
|
546
641
|
| `modified_ts` | `modified_at` | `List_` |
|
|
547
642
|
| `namevariations` | `name_variations` | `Artist` |
|
|
548
643
|
| `qty` | `quantity` | `Format` |
|
|
@@ -4,7 +4,7 @@ requires = ["uv-build>=0.10.3,<0.14"]
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "discogs-sdk"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.0"
|
|
8
8
|
description = "Modern Python client for the Discogs API"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
keywords = [
|
|
@@ -85,7 +85,6 @@ line-length = 88
|
|
|
85
85
|
"tests/test_model_aliases.py" = ["B009"]
|
|
86
86
|
|
|
87
87
|
[tool.deptry.per_rule_ignores]
|
|
88
|
-
DEP001 = ["tomllib"]
|
|
89
88
|
DEP002 = ["tzdata"]
|
|
90
89
|
|
|
91
90
|
[tool.pyproject-fmt]
|
|
@@ -121,11 +120,10 @@ ignore_bodies_if_inherits_from = [
|
|
|
121
120
|
ignore_names = [
|
|
122
121
|
"_cacheable",
|
|
123
122
|
"_clean_discogs_env",
|
|
123
|
+
"_require_httpcore2_mocker",
|
|
124
124
|
"_drop_losing_field_names",
|
|
125
125
|
"_keep_raw",
|
|
126
126
|
"fast_sqlite_busy_timeout",
|
|
127
127
|
"model_config",
|
|
128
|
-
"prices",
|
|
129
128
|
"pytestmark",
|
|
130
|
-
"return_value",
|
|
131
129
|
]
|
|
@@ -4,7 +4,7 @@ requires = [ "uv-build>=0.10.3,<0.14" ]
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "discogs-sdk"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.0"
|
|
8
8
|
description = "Modern Python client for the Discogs API"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
keywords = [ "api", "discogs", "music", "python", "sdk" ]
|
|
@@ -81,8 +81,9 @@ dev = [
|
|
|
81
81
|
# 3.15 deprecates and marks as slated for removal in 3.16
|
|
82
82
|
# (`iscoroutinefunction` in 0.24, `AbstractEventLoopPolicy` in 1.0-1.3).
|
|
83
83
|
# pytest-httpx2 is respx's httpx2 companion (same author). Importing its plugin
|
|
84
|
-
# registers respx's "httpcore2" mocker, which is what `using="httpcore2"` in
|
|
85
|
-
#
|
|
84
|
+
# registers respx's "httpcore2" mocker, which is what `using="httpcore2"` in
|
|
85
|
+
# `mock_router` (tests/conftest.py) selects; respx's built-in mockers only
|
|
86
|
+
# target httpx/httpcore.
|
|
86
87
|
test = [
|
|
87
88
|
"pytest>=8.3",
|
|
88
89
|
"pytest-asyncio>=1.4",
|
|
@@ -113,7 +114,6 @@ lint.per-file-ignores."src/discogs_sdk/_async/_client.py" = [ "ASYNC251" ]
|
|
|
113
114
|
lint.per-file-ignores."tests/test_model_aliases.py" = [ "B009" ]
|
|
114
115
|
|
|
115
116
|
[tool.deptry]
|
|
116
|
-
per_rule_ignores.DEP001 = [ "tomllib" ]
|
|
117
117
|
per_rule_ignores.DEP002 = [ "tzdata" ]
|
|
118
118
|
|
|
119
119
|
[tool.pyproject-fmt]
|
|
@@ -146,12 +146,11 @@ ignore_bodies_if_inherits_from = [ "SDKModel", "UserSummary" ]
|
|
|
146
146
|
ignore_names = [
|
|
147
147
|
"_cacheable",
|
|
148
148
|
"_clean_discogs_env",
|
|
149
|
+
"_require_httpcore2_mocker",
|
|
149
150
|
# Pydantic calls the validators; nothing else references them.
|
|
150
151
|
"_drop_losing_field_names",
|
|
151
152
|
"_keep_raw",
|
|
152
153
|
"fast_sqlite_busy_timeout",
|
|
153
154
|
"model_config",
|
|
154
|
-
"prices",
|
|
155
155
|
"pytestmark",
|
|
156
|
-
"return_value",
|
|
157
156
|
]
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from discogs_sdk._async._client import AsyncDiscogs
|
|
2
2
|
from discogs_sdk._async._paginator import AsyncPage
|
|
3
3
|
from discogs_sdk._base_client import MediaType
|
|
4
|
+
from discogs_sdk._cache import CacheEntry, MemoryCache, ResponseCache, SQLiteCache
|
|
4
5
|
from discogs_sdk._events import RateLimit, RequestEvent
|
|
5
6
|
from discogs_sdk._exceptions import (
|
|
6
7
|
AuthenticationError,
|
|
@@ -25,7 +26,7 @@ from discogs_sdk.models import (
|
|
|
25
26
|
CollectionInstanceCreated,
|
|
26
27
|
CollectionItem,
|
|
27
28
|
CollectionNote,
|
|
28
|
-
|
|
29
|
+
CollectionValue,
|
|
29
30
|
Community,
|
|
30
31
|
CommunityRating,
|
|
31
32
|
CommunityRatingValue,
|
|
@@ -43,6 +44,7 @@ from discogs_sdk.models import (
|
|
|
43
44
|
LabelRelease,
|
|
44
45
|
List_,
|
|
45
46
|
Listing,
|
|
47
|
+
ListingCreated,
|
|
46
48
|
ListingRelease,
|
|
47
49
|
ListItem,
|
|
48
50
|
ListSummary,
|
|
@@ -59,6 +61,7 @@ from discogs_sdk.models import (
|
|
|
59
61
|
OriginalPrice,
|
|
60
62
|
Price,
|
|
61
63
|
PriceSuggestions,
|
|
64
|
+
RatingInfo,
|
|
62
65
|
Release,
|
|
63
66
|
ReleaseStats,
|
|
64
67
|
SDKModel,
|
|
@@ -92,6 +95,11 @@ __all__ = [
|
|
|
92
95
|
"MediaType",
|
|
93
96
|
"RateLimit",
|
|
94
97
|
"RequestEvent",
|
|
98
|
+
# Caching
|
|
99
|
+
"ResponseCache",
|
|
100
|
+
"CacheEntry",
|
|
101
|
+
"MemoryCache",
|
|
102
|
+
"SQLiteCache",
|
|
95
103
|
# Exceptions
|
|
96
104
|
"DiscogsError",
|
|
97
105
|
"CacheMissError",
|
|
@@ -112,7 +120,7 @@ __all__ = [
|
|
|
112
120
|
"CollectionInstanceCreated",
|
|
113
121
|
"CollectionItem",
|
|
114
122
|
"CollectionNote",
|
|
115
|
-
"
|
|
123
|
+
"CollectionValue",
|
|
116
124
|
"Community",
|
|
117
125
|
"CommunityRating",
|
|
118
126
|
"CommunityRatingValue",
|
|
@@ -132,6 +140,7 @@ __all__ = [
|
|
|
132
140
|
"ListItem",
|
|
133
141
|
"ListSummary",
|
|
134
142
|
"Listing",
|
|
143
|
+
"ListingCreated",
|
|
135
144
|
"ListingRelease",
|
|
136
145
|
"MarketplaceReleaseStats",
|
|
137
146
|
"Master",
|
|
@@ -146,6 +155,7 @@ __all__ = [
|
|
|
146
155
|
"OriginalPrice",
|
|
147
156
|
"Price",
|
|
148
157
|
"PriceSuggestions",
|
|
158
|
+
"RatingInfo",
|
|
149
159
|
"SDKModel",
|
|
150
160
|
"Release",
|
|
151
161
|
"ReleaseStats",
|