discogs_client package

discogs_client.client module

class discogs_client.client.Client(user_agent, consumer_key=None, consumer_secret=None, token=None, secret=None, user_token=None)

Bases: object

An interface to the Discogs API.

_base_url = 'https://api.discogs.com'
_request_token_url = 'https://api.discogs.com/oauth/request_token'
_authorize_url = 'https://www.discogs.com/oauth/authorize'
_access_token_url = 'https://api.discogs.com/oauth/access_token'
set_consumer_key(consumer_key, consumer_secret)
set_token(token, secret)
get_authorize_url(callback_url=None)

Returns a tuple of (<access_token>, <access_secret>, <authorize_url>). Send a Discogs user to the authorize URL to get the verifier for the access token.

get_access_token(verifier)

Uses the verifier to exchange a request token for an access token.

_check_user_agent()
_request(method, url, data=None)
_get(url)
_delete(url)
_post(url, data)
_patch(url, data)
_put(url, data)
search(*query, **fields)

Search the Discogs database. Returns a paginated list of objects (Artists, Releases, Masters, and Labels). The keyword arguments to this function are serialized into the request’s query string.

artist(id)

Fetch an Artist by ID.

release(id)

Fetch a Release by ID.

master(id)

Fetch a Master by ID.

label(id)

Fetch a Label by ID.

list(id)

Fetch a List by ID.

user(username)

Fetch a User by username.

listing(id)

Fetch a Marketplace Listing by ID.

order(id)

Fetch an Order by ID.

fee_for(price, currency='USD')

Calculate the fee for selling an item on the Marketplace.

identity()

Return a User object representing the OAuth-authorized user.

property backoff_enabled: bool
property connection_timeout

Return current client connection timeout

property read_timeout

Return current client read timeout

set_timeout(connect: int | float = 5, read: int | float = 10) None

Set request timeout parameters

Parameters:
  • connect ((Union[int, float], optional)) – Time in seconds after which connect will timeout. Defaults to 5.

  • read ((Union[int, float], optional)) – Time in seconds after which request will timeout. Defaults to 10.

discogs_client.exceptions module

exception discogs_client.exceptions.DiscogsAPIError

Bases: Exception

Root Exception class for Discogs API errors.

exception discogs_client.exceptions.TooManyAttemptsError

Bases: DiscogsAPIError

Exception class for when the ratelimit for the API is hit too many times consecutively and backing off has not helped.

exception discogs_client.exceptions.ConfigurationError(msg)

Bases: DiscogsAPIError

Exception class for problems with the configuration of this client.

exception discogs_client.exceptions.HTTPError(message, code)

Bases: DiscogsAPIError

Exception class for HTTP errors.

exception discogs_client.exceptions.AuthorizationError(message, code, response)

Bases: HTTPError

The server rejected the client’s credentials.

discogs_client.fetchers module

class discogs_client.fetchers.Fetcher

Bases: object

Base class for Fetchers, which wrap and normalize the APIs of various HTTP libraries.

(It’s a slightly leaky abstraction designed to make testing easier.)

backoff_enabled = True
connect_timeout: float | int | None = None
read_timeout: float | int | None = None
fetch(client, method, url, data=None, headers=None, json=True)

Fetch the given request

Parameters:
  • client (object) – Instantiated discogs_client.client.Client object.

  • method (str) – HTTP method.

  • url (str) – API endpoint URL.

  • data (dict, optional) – data to be sent in the request’s body, by default None.

  • headers (dict, optional) – HTTP headers, by default None.

  • json_format (bool, optional) – If True, an object passed with the “data” arg will be converted into a JSON string, by default True.

Returns:

  • content (bytes) – as returned by Python “Requests”

  • status_code (int) – as returned by Python “Requests”

Raises:

NotImplementedError – Is raised if a child class doesn’t implement a fetch method.

request(method, url, data, headers, params=None)
class discogs_client.fetchers.LoggingDelegator(fetcher)

Bases: object

Wraps a fetcher and logs all requests.

property last_request
fetch(client, method, url, data=None, headers=None, json=True)

Appends passed “fetcher” to a requests list and returns result of fetcher.fetch method

class discogs_client.fetchers.RequestsFetcher

Bases: Fetcher

Fetches via HTTP from the Discogs API (unauthenticated)

fetch(client, method, url, data=None, headers=None, json=True)
Parameters:
  • client (object) – Unused in this subclass.

  • method (str) – HTTP method.

  • url (str) – API endpoint URL.

  • data (dict, optional) – data to be sent in the request’s body, by default None.

  • headers (dict, optional) – HTTP headers, by default None.

  • json_format (bool, optional) – Unused in this subclass, by default True.

Returns:

  • content (bytes) – as returned by Python “Requests”

  • status_code (int) – as returned by Python “Requests”

class discogs_client.fetchers.UserTokenRequestsFetcher(user_token)

Bases: Fetcher

Fetches via HTTP from the Discogs API using User-token authentication

fetch(client, method, url, data=None, headers=None, json_format=True)

Fetch the given request on the user’s behalf

Parameters:
  • client (object) – Unused in this subclass.

  • method (str) – HTTP method.

  • url (str) – API endpoint URL.

  • data (dict, optional) – data to be sent in the request’s body, by default None.

  • headers (dict, optional) – HTTP headers, by default None.

  • json_format (bool, optional) – If True, an object passed with the “data” arg will be converted into a JSON string, by default True.

Returns:

  • content (bytes) – as returned by Python “Requests”

  • status_code (int) – as returned by Python “Requests”

class discogs_client.fetchers.OAuth2Fetcher(consumer_key, consumer_secret, token=None, secret=None)

Bases: Fetcher

Fetches via HTTP + OAuth 1.0a from the Discogs API.

store_token_from_qs(query_string)
forget_token()
store_token(token, secret)
set_verifier(verifier)
fetch(client, method, url, data=None, headers=None, json_format=True)

Fetch the given request on the user’s behalf

Parameters:
  • client (object) – Unused in this subclass.

  • method (str) – HTTP method.

  • url (str) – API endpoint URL.

  • data (dict, optional) – Data to be sent in the request’s body, by default None.

  • headers (dict, optional) – HTTP headers, by default None.

  • json_format (bool, optional) – If True, an object passed with the “data” arg will be converted into a JSON string, by default True.

Returns:

  • content (bytes) – as returned by Python “Requests”

  • status_code (int) – as returned by Python “Requests”

class discogs_client.fetchers.FilesystemFetcher(base_path)

Bases: Fetcher

Fetches from a directory of files.

default_response = ('{"message": "Resource not found."}', 404)
path_with_params = re.compile('(?P<dir>(\\w+/)+)(?P<query>\\w+)\\?(?P<params>.*)')
fetch(client, method, url, data=None, headers=None, json=True)

Fetch the given request

Parameters:
  • client (object) – Instantiated discogs_client.client.Client object.

  • method (str) – Unused in this subclass (this fetcher supports GET only).

  • url (str) – API endpoint URL.

  • data (dict, optional) – Unused in this subclass (this fetcher supports GET only).

  • headers (dict, optional) – Unused in this subclass.

  • json_format (bool, optional) –

Returns:

  • content (bytes)

  • status_code (int)

check_alternate_params(base_name, json)

parse_qs() result is non-deterministic - a different file might be requested, making the tests fail randomly, depending on the order of parameters in the query. This fixes it by checking for matching file names with a different permutations of the parameters.

class discogs_client.fetchers.MemoryFetcher(responses)

Bases: Fetcher

Fetches from a dict of URL -> (content, status_code).

default_response = ('{"message": "Resource not found."}', 404)
fetch(client, method, url, data=None, headers=None, json=True)

Fetch the given request

Parameters:
  • client (object) – Unused in this subclass.

  • method (str) – Unused in this subclass (this fetcher supports GET only).

  • url (str) – API endpoint URL.

  • data (dict, optional) – Unused in this subclass (this fetcher supports GET only).

  • headers (dict, optional) – Unused in this subclass.

  • json_format (bool, optional) – Unused in this subclass

Returns:

  • content (bytes)

  • status_code (int)

discogs_client.models module

class discogs_client.models.SimpleFieldDescriptor(name, writable=False, transform=None)

Bases: object

An attribute that determines its value using the object’s fetch() method.

If transform is a callable, the value will be passed through transform when read. Useful for strings that should be ints, parsing timestamps, etc.

Shorthand for:

@property def foo(self):

return self.fetch(‘foo’)

class discogs_client.models.ObjectFieldDescriptor(name, class_name, optional=False, as_id=False)

Bases: object

An attribute that determines its value using the object’s fetch() method, and passes the resulting value through an APIObject.

If optional = True, the value will be None (rather than an APIObject instance) if the key is missing from the response.

If as_id = True, the value is treated as an ID for the new APIObject rather than a partial dict of the APIObject.

Shorthand for:

@property def baz(self):

return BazClass(self.client, self.fetch(‘baz’))

class discogs_client.models.ListFieldDescriptor(name, class_name)

Bases: object

An attribute that determines its value using the object’s fetch() method, and passes each item in the resulting list through an APIObject.

Shorthand for:

@property def bar(self):

return [BarClass(self.client, d) for d in self.fetch(‘bar’, [])]

class discogs_client.models.ObjectCollectionDescriptor(name, class_name, url_key=None, list_class=None)

Bases: object

An attribute that determines its value by fetching a URL to a paginated list of related objects, and passes each item in the resulting list through an APIObject.

Shorthand for:

@property def frozzes(self):

return PaginatedList(self.client, self.fetch(‘frozzes_url’), ‘frozzes’, FrozClass)

class discogs_client.models.Field(*args, **kwargs)

Bases: object

A placeholder for a descriptor. Is transformed into a descriptor by the APIObjectMeta metaclass when the APIObject classes are created.

_descriptor_class = None
to_descriptor(attr_name)
class discogs_client.models.SimpleField(*args, **kwargs)

Bases: Field

A field that just returns the value of a given JSON key.

_descriptor_class

alias of SimpleFieldDescriptor

class discogs_client.models.ListField(*args, **kwargs)

Bases: Field

A field that returns a list of APIObjects.

_descriptor_class

alias of ListFieldDescriptor

class discogs_client.models.ObjectField(*args, **kwargs)

Bases: Field

A field that returns a single APIObject.

_descriptor_class

alias of ObjectFieldDescriptor

class discogs_client.models.ObjectCollection(*args, **kwargs)

Bases: Field

A field that returns a paginated list of APIObjects.

_descriptor_class

alias of ObjectCollectionDescriptor

class discogs_client.models.APIObjectMeta(name, bases, namespace)

Bases: type

class discogs_client.models.APIObject

Bases: object

class discogs_client.models.PrimaryAPIObject(client, dict_)

Bases: APIObject

A first-order API object that has a canonical endpoint of its own.

refresh()
save()
delete()
fetch(key, default=None)
class discogs_client.models.SecondaryAPIObject(client, dict_)

Bases: APIObject

An object that wraps parts of a response and doesn’t have its own endpoint.

fetch(key, default=None)
class discogs_client.models.BasePaginatedResponse(client, url)

Bases: object

Base class for lists of objects spread across many URLs.

property per_page
_invalidate()
_load_pagination_info()
_url_for_page(page)
sort(key, order='asc')
filter(**kwargs)
property pages
property count
page(index)
_transform(item)
class discogs_client.models.PaginatedList(client, url, key, class_)

Bases: BasePaginatedResponse

A paginated list of objects of a particular class.

_transform(item)
class discogs_client.models.Wantlist(client, url, key, class_)

Bases: PaginatedList

add(release, notes=None, notes_public=None, rating=None)
remove(release)
class discogs_client.models.Inventory(client, url, key, class_)

Bases: PaginatedList

add_listing(release, condition, price, status, sleeve_condition=None, comments=None, allow_offers=None, external_id=None, location=None, weight=None, format_quantity=None)
class discogs_client.models.OrderMessagesList(client, url, key, class_)

Bases: PaginatedList

add(message=None, status=None, email_buyer=True, email_seller=False)
class discogs_client.models.MixedPaginatedList(client, url, key)

Bases: BasePaginatedResponse

A paginated list of objects identified by their type parameter.

_transform(item)
class discogs_client.models.Artist(client, dict_)

Bases: PrimaryAPIObject

An object describing an artist

id
name
real_name
images
profile
data_quality
name_variations
url
urls
aliases
members
groups
join

This attribute is only populated when an Artist object is requested via the artists list of a Release object, and if it is a multi-artist release. Usually only the first Artist object in the artists list contains a keyword such as “And”, “Feat”, “Vs”, or similar. This keyword could be used to combine artists together into a single string, for example: “DJ ABC Feat MC Z”. Also check out the artists_sort attribute of a Release object.

role

This attribute is only present when an Artist object is part of a credits list of a Release object.

property releases
class discogs_client.models.Release(client, dict_)

Bases: PrimaryAPIObject

An object describing a Discogs release.

id
title
year
thumb
data_quality
status
genres
images
country
notes
formats
styles
url
videos
tracklist
artists

A list of Artist objects. Even though a release could be by one artist only, this will always be a list.

artists_sort

On multi-artist releases this attribute provides a string containing artists combinend together with a keyword such as “And”, “Feat”, “Vs”, or similar, for example “DJ ABC Feat MC Z”. Also check out at the join attribute of an Artist object.

credits
labels

A list of Label objects. Even though a release could have been published on one label only, this will always be a list.

companies
community
property master
property marketplace_stats
property price_suggestions
class discogs_client.models.MarketplaceStats(client, dict_)

Bases: PrimaryAPIObject

num_for_sale
blocked_from_sale
lowest_price
class discogs_client.models.PriceSuggestions(client, dict_)

Bases: PrimaryAPIObject

very_good
good_plus
near_mint
good
very_good_plus
mint
fair
poor
class discogs_client.models.Master(client, dict_)

Bases: PrimaryAPIObject

id
title
data_quality
styles
year
genres
images
url
videos
tracklist
main_release
versions
class discogs_client.models.Label(client, dict_)

Bases: PrimaryAPIObject

id
name
profile
urls
images
contact_info
data_quality
url
sublabels
parent_label
releases
catno

The “catalog number” attribute is only populated when a Label object is fetched via a Release object, otherwise it is None.

class discogs_client.models.User(client, dict_)

Bases: PrimaryAPIObject

id
username
releases_contributed
num_collection
num_wantlist
num_lists
rank
rating_avg
url
name
profile
location
home_page
registered
inventory
wantlist
property orders
property lists
property collection_folders
collection_items(release)

Fetch collection items by release, accepts Release object or release id

Parameters:

release (Release or int) –

Returns:

PaginatedList of CollectionItemInstance objects

Return type:

PaginatedList

property collection_value
class discogs_client.models.WantlistItem(client, dict_)

Bases: PrimaryAPIObject

id
rating
notes
notes_public
release
class discogs_client.models.CollectionItemInstance(client, dict_)

Bases: PrimaryAPIObject

id
instance_id
rating
folder_id
notes
date_added
release
class discogs_client.models.CollectionValue(client, dict_)

Bases: PrimaryAPIObject

maximum
median
minimum
class discogs_client.models.CollectionFolder(client, dict_)

Bases: PrimaryAPIObject

id
name
count
property releases
add_release(release)
remove_release(instance)
class discogs_client.models.List(client, dict_)

Bases: PrimaryAPIObject

id
name
description
public
url
date_changed
date_added
items
class discogs_client.models.Listing(client, dict_)

Bases: PrimaryAPIObject

id
status
allow_offers
condition
sleeve_condition
ships_from
comments
audio
url
release
seller
posted
weight
location
format_quantity
external_id
property price
class discogs_client.models.Order(client, dict_)

Bases: PrimaryAPIObject

id
next_status
shipping_address
additional_instructions
url
status
fee
buyer
seller
created
last_activity
messages
items
property shipping
class discogs_client.models.OrderMessage(client, dict_)

Bases: SecondaryAPIObject

subject
message
to
order
timestamp
class discogs_client.models.Track(client, dict_)

Bases: SecondaryAPIObject

duration
position
title
artists

FIXME could an artist in this list contain the “join” field as well?

credits
class discogs_client.models.Price(client, dict_)

Bases: SecondaryAPIObject

currency
value
class discogs_client.models.Video(client, dict_)

Bases: SecondaryAPIObject

duration
embed
title
description
url
class discogs_client.models.ListItem(client, dict_)

Bases: SecondaryAPIObject

id
comment
display_title
type
image_url
url
class discogs_client.models.CommunityDetails(client, dict_)

Bases: SecondaryAPIObject

An object that wraps the “community” data found in a Release object.

status
data_quality
want
have
rating
contributors
submitter
class discogs_client.models.Rating(client, dict_)

Bases: SecondaryAPIObject

An object that wraps the “community.rating” data found in a Release object.

count
average

discogs_client.utils module

discogs_client.utils.parse_timestamp(timestamp: str) datetime

Convert an ISO 8601 timestamp into a datetime.

discogs_client.utils.update_qs(url, params)

A not-very-intelligent function to glom parameters onto a query string.

discogs_client.utils.omit_none(dict_)

Removes any key from a dict that has a value of None.

discogs_client.utils.jitter(delay: int) float
discogs_client.utils.get_backoff_duration(exponent: int) float
discogs_client.utils.backoff(f)

Wraps the request method of the Fetcher class to provide exponential backoff if rate limit is hit.

class discogs_client.utils.Condition(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Conditions for media and sleeve

MINT = 'Mint (M)'
NEAR_MINT = 'Near Mint (NM or M-)'
VERY_GOOD_PLUS = 'Very Good Plus (VG+)'
VERY_GOOD = 'Very Good (VG)'
GOOD_PLUS = 'Good Plus (G+)'
GOOD = 'Good (G)'
FAIR = 'Fair (F)'
POOR = 'Poor (P)'
GENERIC = 'Generic'
NOT_GRADED = 'Not Graded'
NO_COVER = 'No Cover'
class discogs_client.utils.Status(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

Status for a listing

FOR_SALE = 'For Sale'
DRAFT = 'Draft'
EXPIRED = 'Expired'
class discogs_client.utils.Sort(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

By = <enum 'By'>
Order = <enum 'Order'>