discogs-sdk 0.5.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.7.0/PKG-INFO +741 -0
- discogs_sdk-0.7.0/README.md +711 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/pyproject.toml +15 -7
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/pyproject.toml.orig +31 -22
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/__init__.py +12 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_client.py +195 -100
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_lazy.py +74 -3
- discogs_sdk-0.7.0/src/discogs_sdk/_async/_oauth.py +135 -0
- discogs_sdk-0.7.0/src/discogs_sdk/_async/_paginator.py +224 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/_resource.py +14 -3
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/artists.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/collection.py +55 -20
- discogs_sdk-0.7.0/src/discogs_sdk/_async/resources/exports.py +57 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/labels.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/lists.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/marketplace.py +117 -19
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/masters.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/releases.py +29 -11
- discogs_sdk-0.7.0/src/discogs_sdk/_async/resources/uploads.py +70 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/users.py +8 -10
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/wantlist.py +22 -9
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_base_client.py +300 -79
- discogs_sdk-0.7.0/src/discogs_sdk/_cache.py +365 -0
- discogs_sdk-0.7.0/src/discogs_sdk/_exceptions.py +176 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_client.py +139 -50
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_lazy.py +38 -2
- discogs_sdk-0.7.0/src/discogs_sdk/_sync/_oauth.py +134 -0
- discogs_sdk-0.7.0/src/discogs_sdk/_sync/_paginator.py +212 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/_resource.py +7 -2
- discogs_sdk-0.7.0/src/discogs_sdk/_sync/resources/__init__.py +2 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/artists.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/collection.py +41 -20
- discogs_sdk-0.7.0/src/discogs_sdk/_sync/resources/exports.py +56 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/labels.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/lists.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/marketplace.py +117 -19
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/masters.py +3 -2
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/releases.py +28 -13
- discogs_sdk-0.7.0/src/discogs_sdk/_sync/resources/uploads.py +71 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/users.py +8 -10
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/wantlist.py +18 -9
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/__init__.py +6 -2
- discogs_sdk-0.7.0/src/discogs_sdk/models/_common.py +301 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/_lazy_fields.py +44 -31
- discogs_sdk-0.7.0/src/discogs_sdk/models/_timestamp.py +65 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/collection.py +9 -2
- discogs_sdk-0.7.0/src/discogs_sdk/models/export.py +24 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/list_.py +18 -4
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/marketplace.py +34 -8
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/release.py +9 -2
- discogs_sdk-0.7.0/src/discogs_sdk/models/upload.py +26 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/user.py +9 -1
- discogs_sdk-0.7.0/src/discogs_sdk/py.typed +0 -0
- discogs_sdk-0.5.0/PKG-INFO +0 -426
- discogs_sdk-0.5.0/README.md +0 -397
- discogs_sdk-0.5.0/src/discogs_sdk/_async/_oauth.py +0 -91
- discogs_sdk-0.5.0/src/discogs_sdk/_async/_paginator.py +0 -155
- discogs_sdk-0.5.0/src/discogs_sdk/_async/resources/__init__.py +0 -75
- discogs_sdk-0.5.0/src/discogs_sdk/_async/resources/exports.py +0 -36
- discogs_sdk-0.5.0/src/discogs_sdk/_async/resources/uploads.py +0 -39
- discogs_sdk-0.5.0/src/discogs_sdk/_cache.py +0 -142
- discogs_sdk-0.5.0/src/discogs_sdk/_exceptions.py +0 -83
- discogs_sdk-0.5.0/src/discogs_sdk/_sync/_oauth.py +0 -92
- discogs_sdk-0.5.0/src/discogs_sdk/_sync/_paginator.py +0 -146
- discogs_sdk-0.5.0/src/discogs_sdk/_sync/resources/__init__.py +0 -78
- discogs_sdk-0.5.0/src/discogs_sdk/_sync/resources/exports.py +0 -37
- discogs_sdk-0.5.0/src/discogs_sdk/_sync/resources/uploads.py +0 -40
- discogs_sdk-0.5.0/src/discogs_sdk/models/_common.py +0 -201
- discogs_sdk-0.5.0/src/discogs_sdk/models/export.py +0 -15
- discogs_sdk-0.5.0/src/discogs_sdk/models/upload.py +0 -16
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/LICENSE.txt +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/__init__.py +0 -0
- /discogs_sdk-0.5.0/src/discogs_sdk/py.typed → /discogs_sdk-0.7.0/src/discogs_sdk/_async/resources/__init__.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_async/resources/search.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_events.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_oauth_types.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/__init__.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/_sync/resources/search.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/artist.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/label.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/master.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/search.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/models/wantlist.py +0 -0
- {discogs_sdk-0.5.0 → discogs_sdk-0.7.0}/src/discogs_sdk/oauth.py +0 -0
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: discogs-sdk
|
|
3
|
+
Version: 0.7.0
|
|
4
|
+
Summary: Modern Python client for the Discogs API
|
|
5
|
+
Keywords: api,discogs,music,python,sdk
|
|
6
|
+
Author: Jean-Marc Fontaine
|
|
7
|
+
Author-email: Jean-Marc Fontaine <jm@jmfontaine.net>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE.txt
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Dist: httpx2>=2.12
|
|
21
|
+
Requires-Dist: pydantic>=2.12
|
|
22
|
+
Requires-Dist: pydantic>=2.14 ; python_full_version == '3.15.*'
|
|
23
|
+
Requires-Dist: typing-extensions>=4
|
|
24
|
+
Requires-Dist: tzdata>=2024.1
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Project-URL: Homepage, https://github.com/jmfontaine/discogs-sdk
|
|
27
|
+
Project-URL: Issues, https://github.com/jmfontaine/discogs-sdk/issues
|
|
28
|
+
Project-URL: Repository, https://github.com/jmfontaine/discogs-sdk
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# discogs-sdk
|
|
32
|
+
|
|
33
|
+
<p align="center">
|
|
34
|
+
<a href="https://pypi.org/project/discogs-sdk/"><img src="https://img.shields.io/pypi/v/discogs-sdk.svg" alt="PyPI version"></a>
|
|
35
|
+
<a href="https://pypi.org/project/discogs-sdk/"><img src="https://img.shields.io/pypi/pyversions/discogs-sdk.svg" alt="Python versions"></a>
|
|
36
|
+
<a href="https://github.com/jmfontaine/discogs-sdk/actions"><img src="https://github.com/jmfontaine/discogs-sdk/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
37
|
+
<a href="https://pypi.org/project/discogs-sdk/"><img src="https://img.shields.io/pypi/dm/discogs-sdk.svg" alt="PyPI downloads"></a>
|
|
38
|
+
<a href="https://github.com/jmfontaine/discogs-sdk/blob/main/LICENSE.txt"><img src="https://img.shields.io/pypi/l/discogs-sdk.svg" alt="License"></a>
|
|
39
|
+
</p>
|
|
40
|
+
|
|
41
|
+
discogs-sdk is a modern Python client for the [Discogs API](https://www.discogs.com/developers) covering every documented v2 endpoint, with a fluent chainable syntax and built-in response caching.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from discogs_sdk import Discogs
|
|
45
|
+
|
|
46
|
+
with Discogs() as client:
|
|
47
|
+
release = client.releases.get(352665)
|
|
48
|
+
print(f"{release.title} ({release.year})")
|
|
49
|
+
|
|
50
|
+
for result in client.search(query="Nine Inch Nails", type="artist"):
|
|
51
|
+
print(result.title)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install discogs-sdk
|
|
58
|
+
# or
|
|
59
|
+
uv add discogs-sdk
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Requires Python 3.10+.
|
|
63
|
+
|
|
64
|
+
## Features
|
|
65
|
+
|
|
66
|
+
- **Complete Endpoint Coverage** — Every route in the Discogs API v2 documentation
|
|
67
|
+
- **Fluent API** — Chain sub-resources naturally: `client.releases.get(id).rating.get()`
|
|
68
|
+
- **Lazy Loading** — No HTTP calls until you actually need the data
|
|
69
|
+
- **Effortless Pagination** — Browse results without managing pages or offsets
|
|
70
|
+
- **Rate Limit Aware** — Bounded retries with `Retry-After` support, the live budget on `client.ratelimit`, and a structured event per request
|
|
71
|
+
- **Built-in Caching** — Optional TTL-based caching reduces API calls
|
|
72
|
+
- **Flexible Auth** — Supports personal tokens, consumer key/secret, or full OAuth 1.0a
|
|
73
|
+
- **Type Safe** — Get autocomplete and IDE support
|
|
74
|
+
- **Async & Sync** — Full support for both synchronous and asynchronous workflows
|
|
75
|
+
|
|
76
|
+
### How it compares
|
|
77
|
+
|
|
78
|
+
The established alternative is [python3-discogs-client](https://github.com/joalla/discogs_client). Both load data
|
|
79
|
+
lazily, paginate automatically, support OAuth 1.0a and back off on HTTP 429, so the differences that matter are:
|
|
80
|
+
|
|
81
|
+
| | discogs-sdk | python3-discogs-client |
|
|
82
|
+
|---|---|---|
|
|
83
|
+
| Documented v2 API coverage | Complete | Partial † |
|
|
84
|
+
| Sync and async | Both | Sync only |
|
|
85
|
+
| Responses | Typed Pydantic models | Untyped attributes |
|
|
86
|
+
| Response cache | In-memory or SQLite | None |
|
|
87
|
+
|
|
88
|
+
† No inventory export or upload, release ratings or have/want stats, collection fields, folder creation,
|
|
89
|
+
contributions or submissions.
|
|
90
|
+
|
|
91
|
+
## Quick start
|
|
92
|
+
|
|
93
|
+
### Authentication
|
|
94
|
+
|
|
95
|
+
Set your personal access token from [your Discogs developer settings](https://www.discogs.com/settings/developers) as an environment variable:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
export DISCOGS_TOKEN="your-token-here"
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from discogs_sdk import Discogs
|
|
103
|
+
|
|
104
|
+
client = Discogs() # reads DISCOGS_TOKEN from environment
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
You can also pass credentials explicitly:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
client = Discogs(token="your-token-here")
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The SDK supports three auth modes: personal token, consumer key/secret, and OAuth 1.0a. Exactly one mode is selected
|
|
114
|
+
when the client is constructed, and only that mode's credentials are used. The precedence is:
|
|
115
|
+
|
|
116
|
+
1. An explicit `token` selects personal-token auth and overrides every environment credential.
|
|
117
|
+
2. Explicit OAuth access-token credentials select OAuth; any missing half may come from the matching `DISCOGS_*`
|
|
118
|
+
variable, but an unrelated environment token never takes over.
|
|
119
|
+
3. Explicit `consumer_key`/`consumer_secret` select consumer auth, without borrowing environment access tokens.
|
|
120
|
+
4. With no auth arguments, the environment resolves the mode: `DISCOGS_TOKEN`, then a complete OAuth set, then
|
|
121
|
+
`DISCOGS_CONSUMER_KEY`/`DISCOGS_CONSUMER_SECRET`, then unauthenticated.
|
|
122
|
+
|
|
123
|
+
An explicitly selected but incomplete credential set raises `ValueError` rather than quietly falling back to a
|
|
124
|
+
different account or mode. See [`examples/authentication.py`](examples/authentication.py) for the full OAuth flow.
|
|
125
|
+
|
|
126
|
+
> [!TIP]
|
|
127
|
+
> Use a `.env` file with [python-dotenv](https://pypi.org/project/python-dotenv/) or
|
|
128
|
+
> [direnv](https://direnv.net/) to avoid exporting tokens manually in every shell.
|
|
129
|
+
|
|
130
|
+
> [!NOTE]
|
|
131
|
+
> Discogs allows 60 requests/minute authenticated and 25/minute unauthenticated, measured as a moving average over
|
|
132
|
+
> the last 60 seconds. The SDK does not pace your requests: it retries a rate-limited **read** a bounded number of
|
|
133
|
+
> times (`max_retries`, default 3), honouring `Retry-After` (seconds or an HTTP-date) up to 60 seconds. A longer
|
|
134
|
+
> `Retry-After` is not slept through: the error is raised immediately, `RateLimitError.retry_after` carries the raw
|
|
135
|
+
> value, and you decide whether to wait. Sustained traffic above the limit still needs pacing on your side, and you can
|
|
136
|
+
> still receive `RateLimitError` once the retries are exhausted.
|
|
137
|
+
|
|
138
|
+
> [!WARNING]
|
|
139
|
+
> Mutations are not replayed. A `POST`, `PUT` or `DELETE` is retried only when the failure proves the request never
|
|
140
|
+
> reached the server, such as a refused connection. After a read timeout, a dropped connection or a 5xx the change may
|
|
141
|
+
> already have been committed, so the SDK raises instead of sending it again — the remote outcome is genuinely unknown
|
|
142
|
+
> and only you can decide how to reconcile it.
|
|
143
|
+
|
|
144
|
+
Every transport failure surfaces as `DiscogsConnectionError`, chained to the underlying `httpx2` error
|
|
145
|
+
(`exc.__cause__`). Reads retry the transient ones: network errors, timeouts, and a keep-alive connection the server
|
|
146
|
+
closed (`RemoteProtocolError`). Failures that would repeat identically — `LocalProtocolError`, `UnsupportedProtocol`,
|
|
147
|
+
`ProxyError`, `DecodingError`, `TooManyRedirects` — are raised at once for every method.
|
|
148
|
+
|
|
149
|
+
### Fetching resources
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
# Releases, artists, masters, labels
|
|
153
|
+
release = client.releases.get(352665)
|
|
154
|
+
print(release.title) # lazy — HTTP fires here → "The Downward Spiral"
|
|
155
|
+
|
|
156
|
+
artist = client.artists.get(3857)
|
|
157
|
+
print(artist.name) # "Nine Inch Nails"
|
|
158
|
+
|
|
159
|
+
master = client.masters.get(3719)
|
|
160
|
+
label = client.labels.get(647)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
These lazy resources are read-only views: assigning to one of their attributes raises `AttributeError`, since the
|
|
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()`. 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.
|
|
168
|
+
|
|
169
|
+
Each identifier you pass (username, order id, release id and so on) is sent as a
|
|
170
|
+
single, percent-encoded path segment, so a `/`, `?` or `#` in it cannot reach a
|
|
171
|
+
different endpoint. `"."` and `".."` raise `ValueError` before any request is made.
|
|
172
|
+
|
|
173
|
+
### Search
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
for result in client.search(query="Pretty Hate Machine", type="release", year="1989"):
|
|
177
|
+
print(f"[{result.type}] {result.title}")
|
|
178
|
+
# [release] Nine Inch Nails - Pretty Hate Machine
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Sub-resources
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
# Community rating
|
|
185
|
+
rating = client.releases.get(352665).rating.get()
|
|
186
|
+
print(f"Average: {rating.rating.average}") # Average: 4.49
|
|
187
|
+
|
|
188
|
+
# Artist releases with sorting
|
|
189
|
+
for rel in client.artists.get(3857).releases.list(sort="year", sort_order="desc"):
|
|
190
|
+
print(f"{rel.title} ({rel.year})")
|
|
191
|
+
|
|
192
|
+
# Master versions with filters
|
|
193
|
+
for v in client.masters.get(3719).versions.list(format="Vinyl", country="US"):
|
|
194
|
+
print(f"{v.title} [{v.format}]")
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Async usage
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
import asyncio
|
|
201
|
+
from discogs_sdk import AsyncDiscogs
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
async def main():
|
|
205
|
+
async with AsyncDiscogs() as client: # reads DISCOGS_TOKEN from environment
|
|
206
|
+
# Must await lazy resources in async mode
|
|
207
|
+
release = await client.releases.get(352665)
|
|
208
|
+
print(release.title)
|
|
209
|
+
|
|
210
|
+
# Async iteration for paginated results
|
|
211
|
+
async for result in client.search(query="Nine Inch Nails"):
|
|
212
|
+
print(result.title)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
asyncio.run(main())
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### Collection
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
user = client.users.get("your_username")
|
|
222
|
+
|
|
223
|
+
# Folders
|
|
224
|
+
folders = user.collection.folders.list()
|
|
225
|
+
user.collection.folders.create(name="Industrial")
|
|
226
|
+
|
|
227
|
+
# Browse folder contents
|
|
228
|
+
for item in user.collection.folders.get(0).releases.list(sort="added"):
|
|
229
|
+
print(item.basic_information.title)
|
|
230
|
+
|
|
231
|
+
# Add a release. The response identifies the copy you just created, which is
|
|
232
|
+
# how you tell it apart from copies of the same release you already own.
|
|
233
|
+
created = user.collection.folders.get(1).releases.create(release_id=352665)
|
|
234
|
+
|
|
235
|
+
# Deep chaining: folder -> release -> instance -> fields
|
|
236
|
+
instances = user.collection.folders.get(1).releases.get(352665).instances
|
|
237
|
+
instances.get(created.instance_id).fields.update(field_id=1, value="Signed copy")
|
|
238
|
+
|
|
239
|
+
# Collection value
|
|
240
|
+
value = user.collection.value.get()
|
|
241
|
+
print(f"Median: {value.median}, Maximum: {value.maximum}")
|
|
242
|
+
|
|
243
|
+
# Wantlist — the add takes only the release id; Discogs drops notes and ratings
|
|
244
|
+
# sent to it, so they go in the update call
|
|
245
|
+
user.wantlist.create(release_id=352665)
|
|
246
|
+
user.wantlist.update(352665, notes="Original pressing", rating=4)
|
|
247
|
+
for want in user.wantlist.list():
|
|
248
|
+
print(want.basic_information.title)
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### Marketplace
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
# Listings
|
|
255
|
+
listing = client.marketplace.listings.get(123456789)
|
|
256
|
+
# The response identifies the new listing; it is not a full Listing.
|
|
257
|
+
created = client.marketplace.listings.create(
|
|
258
|
+
release_id=352665,
|
|
259
|
+
condition="Very Good Plus (VG+)",
|
|
260
|
+
price=25.00,
|
|
261
|
+
)
|
|
262
|
+
client.marketplace.listings.update(created.listing_id, price=22.50)
|
|
263
|
+
client.marketplace.listings.delete(created.listing_id)
|
|
264
|
+
|
|
265
|
+
# Orders
|
|
266
|
+
for order in client.marketplace.orders.list(status="Payment Received"):
|
|
267
|
+
print(f"Order {order.id}: {order.status}")
|
|
268
|
+
|
|
269
|
+
# Fee lookup
|
|
270
|
+
fee = client.marketplace.fee.get(price=25.00, currency="USD")
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### Error handling
|
|
274
|
+
|
|
275
|
+
```python
|
|
276
|
+
from discogs_sdk import NotFoundError, RateLimitError, AuthenticationError
|
|
277
|
+
|
|
278
|
+
try:
|
|
279
|
+
release = client.releases.get(999999999)
|
|
280
|
+
_ = release.title
|
|
281
|
+
except NotFoundError as exc:
|
|
282
|
+
print(f"Not found: {exc.method} {exc.url}")
|
|
283
|
+
except RateLimitError as exc:
|
|
284
|
+
print(f"Rate limited, retry after {exc.retry_after}s")
|
|
285
|
+
if exc.ratelimit: # the 429's own X-Discogs-Ratelimit* headers, when present
|
|
286
|
+
print(f"{exc.ratelimit.used}/{exc.ratelimit.limit} used this window")
|
|
287
|
+
except AuthenticationError:
|
|
288
|
+
print("Bad credentials")
|
|
289
|
+
```
|
|
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
|
+
|
|
298
|
+
The full exception hierarchy:
|
|
299
|
+
|
|
300
|
+
```
|
|
301
|
+
DiscogsError
|
|
302
|
+
├── DiscogsConnectionError
|
|
303
|
+
├── CacheMissError
|
|
304
|
+
└── DiscogsAPIError
|
|
305
|
+
├── AuthenticationError (401)
|
|
306
|
+
├── ForbiddenError (403)
|
|
307
|
+
├── NotFoundError (404)
|
|
308
|
+
├── ValidationError (422)
|
|
309
|
+
└── RateLimitError (429)
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
The OAuth helpers in `discogs_sdk.oauth` (`get_request_token`, `get_access_token`
|
|
313
|
+
and their `async_` variants) raise from the same hierarchy: an error status maps as
|
|
314
|
+
above (401 → `AuthenticationError`, 400 → `DiscogsAPIError`, …), a transport failure
|
|
315
|
+
raises `DiscogsConnectionError`, and a successful response missing either
|
|
316
|
+
`oauth_token` or `oauth_token_secret` raises `DiscogsAPIError` naming any
|
|
317
|
+
`oauth_problem`. They never retry: the access-token exchange is sent at most once.
|
|
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
|
+
|
|
326
|
+
`str(exc)` on a `DiscogsAPIError` is a short summary, `"<status>: <message>"`. The
|
|
327
|
+
message is the body's `message` when that is a non-empty string, otherwise the body
|
|
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`.
|
|
331
|
+
|
|
332
|
+
Every SDK exception survives `pickle`, `copy.copy` and `copy.deepcopy` with its
|
|
333
|
+
attributes (`status_code`, `response_body`, `retry_after`, `ratelimit`, `method`,
|
|
334
|
+
`url`) and any notes, so an error raised in a `ProcessPoolExecutor` or
|
|
335
|
+
`multiprocessing` worker reaches the parent as the same class. As with any pickled
|
|
336
|
+
exception, `__cause__`, `__context__` and the traceback are not carried over.
|
|
337
|
+
|
|
338
|
+
A paginated iterator (`.list()`, `search()`) that raises keeps its place. Whether the
|
|
339
|
+
request for a page fails, the page's envelope has the wrong shape, or one of its items
|
|
340
|
+
fails validation (Pydantic's `ValidationError`), `page`, the totals and the URLs stay as
|
|
341
|
+
they were before that page, and the next `next()` or `anext()` requests the same page
|
|
342
|
+
again. Items already yielded are not repeated, and none are skipped.
|
|
343
|
+
|
|
344
|
+
A wrong shape raises `DiscogsError` naming the endpoint, the key and the JSON type
|
|
345
|
+
received, for example `GET /users/trent_reznor/submissions: "submissions" is null,
|
|
346
|
+
expected an object`. That covers a body that is not an object, a `pagination` or a
|
|
347
|
+
non-empty `pagination.urls` that is not an object, and an items key that is not an
|
|
348
|
+
array (or, for nested items, not an object on the way). An absent items key is an
|
|
349
|
+
empty page.
|
|
350
|
+
|
|
351
|
+
#### Exceptions outside `DiscogsError`
|
|
352
|
+
|
|
353
|
+
Apart from the `ValueError`s that reject invalid arguments, such as incomplete
|
|
354
|
+
credentials, the SDK lets three exceptions through on purpose, and
|
|
355
|
+
`except DiscogsError` catches none of them:
|
|
356
|
+
|
|
357
|
+
- `json.JSONDecodeError` (a `ValueError`) when a 2xx response that the SDK reads as
|
|
358
|
+
JSON has a body that is not JSON; a body that is not even UTF-8 raises
|
|
359
|
+
`UnicodeDecodeError`, also a `ValueError`. Error statuses are mapped before the
|
|
360
|
+
endpoint parses the body, and a success is not an API error, so the SDK raises the
|
|
361
|
+
parse failure instead of a fallback value.
|
|
362
|
+
- `pydantic.ValidationError` (a `ValueError`) when a 2xx JSON body does not fit the
|
|
363
|
+
model, such as a release whose `id` is not a number. The response was a success,
|
|
364
|
+
so this is a parsing failure rather than an API error. Only a list page's envelope
|
|
365
|
+
is checked by the SDK itself, as described above; its items go to Pydantic like
|
|
366
|
+
any other model.
|
|
367
|
+
- `FileNotFoundError` (an `OSError`) from `client.uploads.create()`, `change()` or
|
|
368
|
+
`delete()` when `file` names a path that does not exist. The file is read before
|
|
369
|
+
any request is sent, so there is no response to map.
|
|
370
|
+
|
|
371
|
+
Transport failures are not among them: they surface as `DiscogsConnectionError`, as
|
|
372
|
+
described under [Authentication](#authentication).
|
|
373
|
+
|
|
374
|
+
Two unrelated classes are named `ValidationError`. `discogs_sdk.ValidationError` is
|
|
375
|
+
the HTTP 422 `DiscogsAPIError` above and is not a `ValueError`;
|
|
376
|
+
`pydantic.ValidationError` is the model parsing failure. Imported under the same
|
|
377
|
+
name, one silently shadows the other, so alias them:
|
|
378
|
+
|
|
379
|
+
```python
|
|
380
|
+
from discogs_sdk import ValidationError as ApiValidationError
|
|
381
|
+
from pydantic import ValidationError as ModelValidationError
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
## Examples
|
|
385
|
+
|
|
386
|
+
The [`examples/`](examples/) directory has runnable scripts for every feature:
|
|
387
|
+
|
|
388
|
+
- [`quickstart.py`](examples/quickstart.py) — first requests, lazy loading, search
|
|
389
|
+
- [`authentication.py`](examples/authentication.py) — all auth modes including OAuth 1.0a
|
|
390
|
+
- [`database.py`](examples/database.py) — releases, artists, masters, labels, search
|
|
391
|
+
- [`marketplace.py`](examples/marketplace.py) — listings, orders, fees, inventory
|
|
392
|
+
- [`collection.py`](examples/collection.py) — folders, instances, fields, wantlist
|
|
393
|
+
- [`async_usage.py`](examples/async_usage.py) — async client with await and async for
|
|
394
|
+
- [`advanced.py`](examples/advanced.py) — error handling, caching, custom HTTP clients, exports
|
|
395
|
+
|
|
396
|
+
## Configuration
|
|
397
|
+
|
|
398
|
+
| Parameter | Default | Description |
|
|
399
|
+
|---|---|---|
|
|
400
|
+
| `access_token_secret` | `None` | OAuth access token secret |
|
|
401
|
+
| `access_token` | `None` | OAuth access token |
|
|
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` |
|
|
403
|
+
| `cache_dir` | `None` | Directory for SQLite cache; in-memory when omitted. Used only with `cache=True` |
|
|
404
|
+
| `cache_ttl` | `3600.0` | Cache time-to-live in seconds. Used only with `cache=True` |
|
|
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 |
|
|
406
|
+
| `consumer_key` | `None` | OAuth consumer key |
|
|
407
|
+
| `consumer_secret` | `None` | OAuth consumer secret |
|
|
408
|
+
| `http_client` | `None` | Custom `httpx2.Client` or `httpx2.AsyncClient` |
|
|
409
|
+
| `max_retries` | `3` | Max retries, `>= 0` (`0` disables retries, a negative value raises `ValueError`); reads retry on 429/5xx, network errors, timeouts and dropped connections, mutations only on pre-send failures. A `Retry-After` above 60s raises immediately instead |
|
|
410
|
+
| `media_type` | `"discogs"` | Format of text fields: `"discogs"` (Discogs markup), `"html"` or `"plaintext"`; sent in the `Accept` header, and cached responses are kept apart per value |
|
|
411
|
+
| `on_request` | `None` | Callback receiving a `RequestEvent` per request |
|
|
412
|
+
| `timeout` | `30.0` | Request timeout in seconds for the HTTP client the SDK creates; an injected `http_client` keeps its own (see [Custom HTTP clients](#custom-http-clients)) |
|
|
413
|
+
| `token` | `None` | Personal access token |
|
|
414
|
+
| `user_agent` | `discogs-sdk/<version> +https://github.com/jmfontaine/discogs-sdk` | `User-Agent` header; a non-empty value replaces the default entirely |
|
|
415
|
+
|
|
416
|
+
With `cache=False`, the default, `cache_dir` and `cache_ttl` are ignored and no cache or directory is created; a
|
|
417
|
+
`ResponseCache` instance ignores them too. `cache_ttl=0` is accepted and expires every entry at once, so each read
|
|
418
|
+
refetches: it is not a way to say "no limit".
|
|
419
|
+
|
|
420
|
+
See [Authentication](#authentication) for how a credential mode is selected.
|
|
421
|
+
|
|
422
|
+
### Caching
|
|
423
|
+
|
|
424
|
+
Only successful `GET`/`HEAD` responses are cached, and a `GET` body that is not valid JSON (a gateway's HTML page, an
|
|
425
|
+
empty body) never is, so a bad response fails once instead of on every read; inventory export downloads, which are CSV,
|
|
426
|
+
are cached as they are. A body that is valid JSON but the wrong shape for its model is still cached until it expires.
|
|
427
|
+
Entries are keyed by method, fully resolved URL, the effective `Accept` representation, and a non-reversible digest of
|
|
428
|
+
the selected mode's credentials, so two clients sharing one cache — or one SQLite directory — never serve each other's
|
|
429
|
+
private responses, and unauthenticated traffic gets its own namespace. No token or secret is stored in a key.
|
|
430
|
+
|
|
431
|
+
Job status reads, `client.exports.get(id)` and `client.uploads.get(id)`, are never cached: each one reaches the API and
|
|
432
|
+
stores nothing, so a polling loop sees the job finish. A resolved proxy keeps its data, though, so poll with a new
|
|
433
|
+
`get()` call each time. Inside `cache_only()` these reads raise `CacheMissError`. `exports.list()`, `uploads.list()`
|
|
434
|
+
and `exports.download()` are cached as usual.
|
|
435
|
+
|
|
436
|
+
A successful write (`POST`, `PUT` or `DELETE` with a 2xx answer) clears the whole response cache, so no entry cached
|
|
437
|
+
before the write is served after it: not the written URL, not a list page, not a related folder or count. The rule
|
|
438
|
+
holds inside `no_cache()` too, and a cache shared between clients is cleared for all of them; entries are refetched on
|
|
439
|
+
demand, which costs requests. A failed write leaves the cache alone, and a cache that fails to clear is logged without
|
|
440
|
+
failing the write. Proxies and pages already resolved keep their in-memory data, so fetch a new proxy or iterate again
|
|
441
|
+
to see the change. Discogs itself may take a while to show a write, and a refetch made in that window caches what it
|
|
442
|
+
returned.
|
|
443
|
+
|
|
444
|
+
A cache built from `cache=True` belongs to the client, and `client.close()` closes it. A `ResponseCache` instance you
|
|
445
|
+
pass in stays yours, like an injected `http_client`: `client.close()` never closes it, so one cache can outlive any of
|
|
446
|
+
the clients sharing it. Call its `close()` yourself once every client using it is done.
|
|
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
|
+
|
|
454
|
+
The SQLite cache never fails a request. If its database is locked by another process, read-only, full or corrupt,
|
|
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
|
|
456
|
+
response still reaches you. Using the cache after it has been closed raises `RuntimeError`. The database runs in WAL
|
|
457
|
+
mode, so `cache.db-wal` and `cache.db-shm` may appear next to `cache.db`.
|
|
458
|
+
|
|
459
|
+
The SQLite database holds the full bodies of your private responses (identity, orders with buyer addresses,
|
|
460
|
+
collection), so put `cache_dir` somewhere only you can read, such as `~/.cache/my-app`, never a shared path like
|
|
461
|
+
`/tmp`. A directory the cache creates is private (`0o700`) and `cache.db` is `0o600`; on POSIX, an existing `cache.db`
|
|
462
|
+
that is a symlink or belongs to another user raises `PermissionError`. Entries keep only the `Content-Type`, `ETag` and
|
|
463
|
+
`Last-Modified` response headers.
|
|
464
|
+
|
|
465
|
+
`client.no_cache()` bypasses the cache for the current execution context. Scopes nest, the previous state is
|
|
466
|
+
restored even when the block raises, and each context carries its own scope, so leaving it in one thread or task
|
|
467
|
+
never affects another (a pool worker, or a task created before the block, does not see it; see
|
|
468
|
+
[Concurrency](#concurrency)):
|
|
469
|
+
|
|
470
|
+
```python
|
|
471
|
+
with client.no_cache():
|
|
472
|
+
fresh = client.releases.get(352665).title # always hits the API
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
`client.cache_only()` is the mirror image: inside the scope a request the cache cannot serve — a miss, an expired
|
|
476
|
+
entry, a non-`GET`, a job status read, a disabled cache, an injected `http_client` without SDK credentials or an
|
|
477
|
+
enclosing `no_cache()` — raises `CacheMissError` before any network I/O. It nests and restores exactly like
|
|
478
|
+
`no_cache()`, so you can try everything for free first:
|
|
479
|
+
|
|
480
|
+
```python
|
|
481
|
+
from discogs_sdk import CacheMissError
|
|
482
|
+
|
|
483
|
+
with client.cache_only():
|
|
484
|
+
try:
|
|
485
|
+
title = client.releases.get(352665).title # never hits the API
|
|
486
|
+
except CacheMissError as exc:
|
|
487
|
+
print(f"Not cached: {exc.method} {exc.url}")
|
|
488
|
+
```
|
|
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
|
+
|
|
555
|
+
### Observability
|
|
556
|
+
|
|
557
|
+
Every live response carries Discogs' `X-Discogs-Ratelimit`, `X-Discogs-Ratelimit-Used` and
|
|
558
|
+
`X-Discogs-Ratelimit-Remaining` headers. `client.ratelimit` holds them as a `RateLimit(limit, used, remaining)`
|
|
559
|
+
parsed from the most recent **network** response: a cache hit never touches it, and a response without the headers
|
|
560
|
+
leaves the last known value in place. It is `None` until the first live response.
|
|
561
|
+
|
|
562
|
+
`on_request` receives one `RequestEvent` per logical request, invoked synchronously — after a cache hit, or after the
|
|
563
|
+
final network response and before any error is raised, so the event exists even when the call raises. Intermediate
|
|
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.
|
|
567
|
+
|
|
568
|
+
| Field | Meaning |
|
|
569
|
+
|---|---|
|
|
570
|
+
| `method` | Upper-case HTTP method |
|
|
571
|
+
| `url` | Fully resolved URL, query string included |
|
|
572
|
+
| `status_code` | Status of the response that ended the call |
|
|
573
|
+
| `source` | `"network"` or `"cache"` |
|
|
574
|
+
| `elapsed_ms` | Final network attempt, or the cache lookup |
|
|
575
|
+
| `attempts` | Network attempts (`1` = no retry); `0` on a cache hit |
|
|
576
|
+
| `stored` | Whether this call wrote the response to the cache |
|
|
577
|
+
| `ratelimit` | `RateLimit` from the response; always `None` on a cache hit |
|
|
578
|
+
|
|
579
|
+
A minimal pacing loop:
|
|
580
|
+
|
|
581
|
+
```python
|
|
582
|
+
import time
|
|
583
|
+
|
|
584
|
+
client = Discogs(
|
|
585
|
+
token="...", on_request=lambda e: print(e.source, e.status_code, e.elapsed_ms)
|
|
586
|
+
)
|
|
587
|
+
title = client.releases.get(352665).title # lazy — the GET fires here
|
|
588
|
+
if client.ratelimit and client.ratelimit.remaining < 10:
|
|
589
|
+
time.sleep(60)
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
### Concurrency
|
|
593
|
+
|
|
594
|
+
One client may be shared by several threads (`Discogs`) or tasks (`AsyncDiscogs`). A few things are tied to a
|
|
595
|
+
context or an object rather than to the client.
|
|
596
|
+
|
|
597
|
+
`no_cache()` and `cache_only()` apply to the current execution context only. A task copies its context when it is
|
|
598
|
+
created, so a task created before the block does not see the scope. A pool worker runs in its own context, so
|
|
599
|
+
`with client.no_cache(): pool.map(...)` still serves the workers from the cache; on a free-threaded 3.14+ build, where
|
|
600
|
+
a new thread starts with a copy of its creator's context, a worker spawned inside the block keeps the scope for its
|
|
601
|
+
lifetime instead. Either way, enter the scope inside the worker, or run the work in a copy of the context taken inside
|
|
602
|
+
the scope. Take a new copy for each call: one `Context` cannot run in two threads at once, and sharing it raises
|
|
603
|
+
`RuntimeError`.
|
|
604
|
+
|
|
605
|
+
```python
|
|
606
|
+
import contextvars
|
|
607
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def title(release_id):
|
|
611
|
+
return client.releases.get(release_id).title
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
with ThreadPoolExecutor() as pool:
|
|
615
|
+
with client.no_cache():
|
|
616
|
+
# copy_context() runs here, inside the scope
|
|
617
|
+
future = pool.submit(contextvars.copy_context().run, title, 352665)
|
|
618
|
+
print(future.result()) # The Downward Spiral, fetched from the API
|
|
619
|
+
```
|
|
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
|
+
|
|
627
|
+
A page returned by `.list()` or `search()` is a single-pass iterator for one consumer. Several threads or tasks
|
|
628
|
+
iterating the same page race on its position and can fetch a page twice and yield its items twice, and a page that
|
|
629
|
+
is exhausted yields nothing on a second pass. Call `.list()` or `search()` again for each consumer and each pass.
|
|
630
|
+
|
|
631
|
+
`on_request` runs on the thread or task that made the request, once that request completes, so events arrive in
|
|
632
|
+
completion order rather than start order, and with several threads the callback can run in several of them at once.
|
|
633
|
+
`client.ratelimit` is the value from whichever live response completed last, not necessarily the one with the lowest
|
|
634
|
+
`remaining`: under concurrency it is a hint for pacing, not a global count.
|
|
635
|
+
|
|
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.
|
|
639
|
+
|
|
640
|
+
### Custom HTTP clients
|
|
641
|
+
|
|
642
|
+
An injected `http_client` must be an `httpx2` client — the SDK is built on [httpx2](https://github.com/pydantic/httpx2),
|
|
643
|
+
Pydantic's maintained continuation of httpx. It owns its transport configuration and its lifecycle: `client.close()`
|
|
644
|
+
never closes it. SDK credentials, User-Agent and media type are still applied per request, so they describe the request
|
|
645
|
+
without mutating your client's defaults, and its own `httpx2.Auth` cannot replace credentials you gave the SDK.
|
|
646
|
+
|
|
647
|
+
An injected client's timeout is part of that transport configuration. The `timeout` argument only configures a client
|
|
648
|
+
the SDK creates, so `Discogs(http_client=httpx2.Client(timeout=99.0), timeout=1.0)` sends every request with the
|
|
649
|
+
injected client's 99-second timeout, even though `client.timeout` reports `1.0`. To control the timeout of an injected
|
|
650
|
+
client, set it on that client.
|
|
651
|
+
|
|
652
|
+
When the SDK has no credentials of its own, your client's authentication is preserved and its responses are never
|
|
653
|
+
cached, even with `cache=True`, because the SDK cannot tell whose account they belong to. Inside `cache_only()` every
|
|
654
|
+
request from such a client therefore raises `CacheMissError`.
|
|
655
|
+
|
|
656
|
+
## Field naming
|
|
657
|
+
|
|
658
|
+
Model fields use clean Python names. Where the Discogs API uses inconsistent or cryptic keys, the SDK provides a readable alias while still accepting the raw API name during deserialization:
|
|
659
|
+
|
|
660
|
+
| API field | Python attribute | Models |
|
|
661
|
+
|---|---|---|
|
|
662
|
+
| `anv` | `name_variation` | `ArtistCredit` |
|
|
663
|
+
| `catno` | `catalog_number` | `LabelCredit`, `Company`, `LabelRelease`, `MasterVersion`, `SearchResult` |
|
|
664
|
+
| `created_ts` | `created_at` | `Export`, `Upload`, `List_` |
|
|
665
|
+
| `curr_abbr` | `currency_code` | `OriginalPrice`, `User` |
|
|
666
|
+
| `curr_id` | `currency_id` | `OriginalPrice` |
|
|
667
|
+
| `extraartists` | `extra_artists` | `Release`, `Track` |
|
|
668
|
+
| `finished_ts` | `finished_at` | `Export`, `Upload` |
|
|
669
|
+
| `from` | `from_user` | `OrderMessage` |
|
|
670
|
+
| `list_id` | `id` | `List_` |
|
|
671
|
+
| `modified_ts` | `modified_at` | `List_` |
|
|
672
|
+
| `namevariations` | `name_variations` | `Artist` |
|
|
673
|
+
| `qty` | `quantity` | `Format` |
|
|
674
|
+
| `sublabels` | `sub_labels` | `Label` |
|
|
675
|
+
| `uri150` | `uri_150` | `Image` |
|
|
676
|
+
|
|
677
|
+
The Python name is the typed attribute. API names still resolve as attributes at runtime, but only dynamically: a type
|
|
678
|
+
checker treats them like any misspelled attribute, so read them through `getattr` where one is in play:
|
|
679
|
+
|
|
680
|
+
```python
|
|
681
|
+
release = client.releases.get(352665) # The Downward Spiral
|
|
682
|
+
print(release.extra_artists) # Python name, typed
|
|
683
|
+
print(getattr(release, "extraartists")) # API name, runtime only — same value
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
An API name that is a Python keyword, such as `from`, is reachable only through `getattr(message, "from")`.
|
|
687
|
+
|
|
688
|
+
An API name resolves to the same normalized value as the Python name, so `getattr(export, "created_ts")` is a
|
|
689
|
+
`datetime` too. To read what Discogs sent, use [`raw`](#original-api-values).
|
|
690
|
+
|
|
691
|
+
## Timestamps
|
|
692
|
+
|
|
693
|
+
Discogs sends timestamps as strings in several shapes:
|
|
694
|
+
|
|
695
|
+
| Shape | Example | Where |
|
|
696
|
+
|---|---|---|
|
|
697
|
+
| ISO 8601 with an offset | `2005-01-03T23:17:26-08:00` | most fields |
|
|
698
|
+
| A space instead of `T` | `2011-08-30 14:21:45-07:00` | `User.registered` |
|
|
699
|
+
| No offset | `2026-10-11T07:07:34` | `Export` and `Upload` (`created_at`, `finished_at`) |
|
|
700
|
+
|
|
701
|
+
The SDK parses every one of them into a timezone-aware `datetime`, so you can compare and sort values from any
|
|
702
|
+
endpoint. This covers `Release` (`date_added`, `date_changed`), `CollectionItem.date_added`, `ListSummary`
|
|
703
|
+
(`date_added`, `date_changed`), `List_` (`created_at`, `modified_at`), `User.registered`, `Listing.posted`, `Order`
|
|
704
|
+
(`created`, `last_activity`), `OrderMessage.timestamp`, `Export` and `Upload` (`created_at`, `finished_at`).
|
|
705
|
+
|
|
706
|
+
- An offset that Discogs sends stays as sent.
|
|
707
|
+
- A value without an offset is read as `America/Los_Angeles` time and gets the fixed offset in force then (`-08:00` or
|
|
708
|
+
`-07:00`), the same kind of `tzinfo` as a value that arrives with one. Discogs does not document its zone; this is an
|
|
709
|
+
assumption. An export requested at 14:07:34 UTC reported `07:07:34`, and the offsets Discogs does send switch between
|
|
710
|
+
`-08:00` and `-07:00` with daylight saving. In the hour repeated when daylight saving ends, the SDK picks the first
|
|
711
|
+
occurrence.
|
|
712
|
+
- An empty string becomes `None`.
|
|
713
|
+
- A value the SDK cannot parse becomes `None`, and the SDK logs a warning on the `discogs_sdk` logger. The model still
|
|
714
|
+
loads, and `raw` keeps the string.
|
|
715
|
+
|
|
716
|
+
`model_dump(mode="json")` writes ISO 8601 with an explicit offset, and `model_validate` reads it back unchanged.
|
|
717
|
+
|
|
718
|
+
## Original API values
|
|
719
|
+
|
|
720
|
+
Every model keeps the mapping it was validated from in `raw`. Use it to read a value as Discogs sent it, before
|
|
721
|
+
renaming or parsing:
|
|
722
|
+
|
|
723
|
+
```python
|
|
724
|
+
release = client.releases.get(352665) # The Downward Spiral
|
|
725
|
+
print(release.date_added) # datetime(2005, 1, 3, 23, 17, 26, tzinfo=...)
|
|
726
|
+
print(release.raw["date_added"]) # '2005-01-03T23:17:26-08:00'
|
|
727
|
+
print(release.extra_artists[0].raw) # a nested model holds its own part of the payload
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
`raw` is the decoded response itself, not a copy; its type is a read-only `Mapping`, but code holding the same dict can
|
|
731
|
+
still change it, and later reads see the change. Holding a model keeps the whole payload in memory. `model_dump()` and
|
|
732
|
+
`==` ignore `raw`. A model you build with keyword arguments or with `model_validate(model.model_dump())` reports that
|
|
733
|
+
input instead of an API response.
|
|
734
|
+
|
|
735
|
+
## Contributing
|
|
736
|
+
|
|
737
|
+
Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
|
|
738
|
+
|
|
739
|
+
## License
|
|
740
|
+
|
|
741
|
+
discogs-sdk is licensed under the [Apache License 2.0](LICENSE.txt).
|