Package musicbrainz2 :: Module webservice :: Class Query

[frames] | no frames]

# Class Query

source code

    object --+
             |
            Query

A simple interface to the MusicBrainz web service.

This is a facade which provides a simple interface to the MusicBrainz web service. It hides all the details like fetching data from a server, parsing the XML and creating an object tree. Using this class, you can request data by ID or search the collection of all resources (artists, releases, or tracks) to retrieve those matching given criteria. This document contains examples to get you started.

# Working with Identifiers

MusicBrainz uses absolute URIs as identifiers. For example, the artist 'Tori Amos' is identified using the following URI:

           http://musicbrainz.org/artist/c0b2500e-0cef-4130-869d-732b23ed9df5

In some situations it is obvious from the context what type of resource an ID refers to. In these cases, abbreviated identifiers may be used, which are just the UUID part of the URI. Thus the ID above may also be written like this:

           c0b2500e-0cef-4130-869d-732b23ed9df5

All methods in this class which require IDs accept both the absolute URI and the abbreviated form (aka the relative URI).

# Creating a Query Object

In most cases, creating a Query object is as simple as this:

    >>> import musicbrainz2.webservice as ws
    >>> q = ws.Query()
    >>>

The instantiated object uses the standard WebService class to access the MusicBrainz web service. If you want to use a different server or you have to pass user name and password because one of your queries requires authentication, you have to create the WebService object yourself and configure it appropriately. This example uses the MusicBrainz test server and also sets authentication data:

    >>> import musicbrainz2.webservice as ws
    >>> service = ws.WebService(host='test.musicbrainz.org',
    ...                             username='whatever', password='secret')
    >>> q = ws.Query(service)
    >>>

# Querying for Individual Resources

If the MusicBrainz ID of a resource is known, then the getArtistById, getReleaseById, or getTrackById method can be used to retrieve it. Example:

    >>> import musicbrainz2.webservice as ws
    >>> q = ws.Query()
    >>> artist = q.getArtistById('c0b2500e-0cef-4130-869d-732b23ed9df5')
    >>> artist.name
    u'Tori Amos'
    >>> artist.sortName
    u'Amos, Tori'
    >>> print artist.type
    http://musicbrainz.org/ns/mmd-1.0#Person
    >>>

This returned just the basic artist data, however. To get more detail about a resource, the `include` parameters may be used which expect an ArtistIncludes, ReleaseIncludes, or TrackIncludes object, depending on the resource type.

To get data about a release which also includes the main artist and all tracks, for example, the following query can be used:

    >>> import musicbrainz2.webservice as ws
    >>> q = ws.Query()
    >>> releaseId = '33dbcf02-25b9-4a35-bdb7-729455f33ad7'
    >>> include = ws.ReleaseIncludes(artist=True, tracks=True)
    >>> release = q.getReleaseById(releaseId, include)
    >>> release.title
    u'Tales of a Librarian'
    >>> release.artist.name
    u'Tori Amos'
    >>> release.tracks[0].title
    u'Precious Things'
    >>>

Note that the query gets more expensive for the server the more data you request, so please be nice.

# Searching in Collections

For each resource type (artist, release, and track), there is one collection which contains all resources of a type. You can search these collections using the getArtists, getReleases, and getTracks methods. The collections are huge, so you have to use filters (ArtistFilter, ReleaseFilter, or TrackFilter) to retrieve only resources matching given criteria.

For example, If you want to search the release collection for releases with a specified DiscID, you would use getReleases and a ReleaseFilter object:

    >>> import musicbrainz2.webservice as ws
    >>> q = ws.Query()
    >>> filter = ws.ReleaseFilter(discId='8jJklE258v6GofIqDIrE.c5ejBE-')
    >>> results = q.getReleases(filter=filter)
    >>> results[0].score
    100
    >>> results[0].release.title
    u'Under the Pink'
    >>>

The query returns a list of results (wsxml.ReleaseResult objects in this case), which are ordered by score, with a higher score indicating a better match. Note that those results don't contain all the data about a resource. If you need more detail, you can then use the getArtistById, getReleaseById, or getTrackById methods to request the resource.

All filters support the `limit` argument to limit the number of results returned. This defaults to 25, but the server won't send more than 100 results to save bandwidth and processing power. Using `limit` and the `offset` parameter, you can page through the results.

# Error Handling

All methods in this class raise a WebServiceError exception in case of errors. Depending on the method, a subclass of WebServiceError may be raised which allows an application to handle errors more precisely. The following example handles connection errors (invalid host name etc.) separately and all other web service errors in a combined catch clause:

    >>> try:
    ...     artist = q.getArtistById('c0b2500e-0cef-4130-869d-732b23ed9df5')
    ... except ws.ConnectionError, e:
    ...     pass # implement your error handling here
    ... except ws.WebServiceError, e:
    ...     pass # catches all other web service errors
    ...
    >>>

Instance Methods

__init__(self, ws=None, wsFactory=<class 'musicbrainz2.webservice.WebService'>, clientId=None) Constructor. | source code

getArtistById(self, id_, include=None) Returns an artist. | source code

getArtists(self, filter) Returns artists matching given criteria. | source code

getLabelById(self, id_, include=None) Returns a model.Label | source code

getLabels(self, filter) | source code

getReleaseById(self, id_, include=None) Returns a release. | source code

getReleases(self, filter) Returns releases matching given criteria. | source code

getReleaseGroupById(self, id_, include=None) Returns a release group. | source code

getReleaseGroups(self, filter) Returns release groups matching the given criteria. | source code

getTrackById(self, id_, include=None) Returns a track. | source code

getTracks(self, filter) Returns tracks matching given criteria. | source code

getUserByName(self, name) Returns information about a MusicBrainz user. | source code

submitPuids(self, tracks2puids) Submit track to PUID mappings. | source code

submitISRCs(self, tracks2isrcs) Submit track to ISRC mappings. | source code

addToUserCollection(self, releases) Add releases to a user's collection. | source code

removeFromUserCollection(self, releases) Remove releases from a user's collection. | source code

getUserCollection(self, offset=0, maxitems=100) Get the releases that are in a user's collection | source code

submitUserTags(self, entityUri, tags) Submit folksonomy tags for an entity. | source code

getUserTags(self, entityUri) Returns a list of folksonomy tags a user has applied to an entity. | source code

submitUserRating(self, entityUri, rating) Submit rating for an entity. | source code

getUserRating(self, entityUri) Return the rating a user has applied to an entity. | source code

submitCDStub(self, cdstub) Submit a CD Stub to the database. | source code

Inherited from `object`: `__delattr__`, `__format__`, `__getattribute__`, `__hash__`, `__new__`, `__reduce__`, `__reduce_ex__`, `__repr__`, `__setattr__`, `__sizeof__`, `__str__`, `__subclasshook__`

Properties
Inherited from `object`: `__class__`

Method Details

### __init__(self, ws=None, wsFactory=<class 'musicbrainz2.webservice.WebService'>, clientId=None)
(Constructor)

source code

Constructor.

The `ws` parameter has to be a subclass of IWebService. If it isn't given, the `wsFactory` parameter is used to create an IWebService subclass.

If the constructor is called without arguments, an instance of WebService is used, preconfigured to use the MusicBrainz server. This should be enough for most users.

If you want to use queries which require authentication you have to pass a WebService instance where user name and password have been set.

The `clientId` parameter is required for data submission. The format is `'application-version'`, where `application` is your application's name and `version` is a version number which may not include a '-' character. Even if you don't plan to submit data, setting this parameter is encouraged because it will set the user agent used to make requests if you don't supply the `ws` parameter.

Parameters:
  - `ws` - a subclass instance of IWebService, or None
  - `wsFactory` - a callable object which creates an object
  - `clientId` - a unicode string containing the application's ID
Overrides: object.__init__

### getArtistById(self, id_, include=None)

source code

Returns an artist.

If no artist with that ID can be found, `include` contains invalid tags or there's a server problem, an exception is raised.

Parameters:
  - `id_` - a string containing the artist's ID
  - `include` - an ArtistIncludes object, or None
Returns:
  an Artist object, or None
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResourceNotFoundError` - artist doesn't exist
  - `ResponseError` - server returned invalid data

### getArtists(self, filter)

source code

Returns artists matching given criteria.

Parameters:
  - `filter` - an ArtistFilter object
Returns:
  a list of musicbrainz2.wsxml.ArtistResult objects
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResponseError` - server returned invalid data

### getLabelById(self, id_, include=None)

source code

Returns a model.Label

If no label with that ID can be found, or there is a server problem, an exception is raised.

Parameters:
  - `id_` - a string containing the label's ID.
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResourceNotFoundError` - release doesn't exist
  - `ResponseError` - server returned invalid data

### getReleaseById(self, id_, include=None)

source code

Returns a release.

If no release with that ID can be found, `include` contains invalid tags or there's a server problem, and exception is raised.

Parameters:
  - `id_` - a string containing the release's ID
  - `include` - a ReleaseIncludes object, or None
Returns:
  a Release object, or None
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResourceNotFoundError` - release doesn't exist
  - `ResponseError` - server returned invalid data

### getReleases(self, filter)

source code

Returns releases matching given criteria.

Parameters:
  - `filter` - a ReleaseFilter object
Returns:
  a list of musicbrainz2.wsxml.ReleaseResult objects
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResponseError` - server returned invalid data

### getReleaseGroupById(self, id_, include=None)

source code

Returns a release group.

If no release group with that ID can be found, `include` contains invalid tags, or there's a server problem, an exception is raised.

Parameters:
  - `id_` - a string containing the release group's ID
  - `include` - a ReleaseGroupIncludes object, or None
Returns:
  a ReleaseGroup object, or None
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResourceNotFoundError` - release doesn't exist
  - `ResponseError` - server returned invalid data

### getReleaseGroups(self, filter)

source code

Returns release groups matching the given criteria.

Parameters:
  - `filter` - a ReleaseGroupFilter object
Returns:
  a list of musicbrainz2.wsxml.ReleaseGroupResult objects
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResponseError` - server returned invalid data

### getTrackById(self, id_, include=None)

source code

Returns a track.

If no track with that ID can be found, `include` contains invalid tags or there's a server problem, an exception is raised.

Parameters:
  - `id_` - a string containing the track's ID
  - `include` - a TrackIncludes object, or None
Returns:
  a Track object, or None
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResourceNotFoundError` - track doesn't exist
  - `ResponseError` - server returned invalid data

### getTracks(self, filter)

source code

Returns tracks matching given criteria.

Parameters:
  - `filter` - a TrackFilter object
Returns:
  a list of musicbrainz2.wsxml.TrackResult objects
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `ResponseError` - server returned invalid data

### getUserByName(self, name)

source code

Returns information about a MusicBrainz user.

You can only request user data if you know the user name and password for that account. If username and/or password are incorrect, an AuthenticationError is raised.

See the example in Query on how to supply user name and password.

Parameters:
  - `name` - a unicode string containing the user's name
Returns:
  a User object
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or include tags
  - `AuthenticationError` - invalid user name and/or password
  - `ResourceNotFoundError` - track doesn't exist
  - `ResponseError` - server returned invalid data

### submitPuids(self, tracks2puids)

source code

Submit track to PUID mappings.

The `tracks2puids` parameter has to be a dictionary, with the keys being MusicBrainz track IDs (either as absolute URIs or in their 36 character ASCII representation) and the values being PUIDs (ASCII, 36 characters).

Note that this method only works if a valid user name and password have been set. See the example in Query on how to supply authentication data.

Parameters:
  - `tracks2puids` - a dictionary mapping track IDs to PUIDs
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid track or PUIDs
  - `AuthenticationError` - invalid user name and/or password

### submitISRCs(self, tracks2isrcs)

source code

Submit track to ISRC mappings.

The `tracks2isrcs` parameter has to be a dictionary, with the keys being MusicBrainz track IDs (either as absolute URIs or in their 36 character ASCII representation) and the values being ISRCs (ASCII, 12 characters).

Note that this method only works if a valid user name and password have been set. See the example in Query on how to supply authentication data.

Parameters:
  - `tracks2isrcs` - a dictionary mapping track IDs to ISRCs
Raises:
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid track or ISRCs
  - `AuthenticationError` - invalid user name and/or password

### addToUserCollection(self, releases)

source code

Add releases to a user's collection.

The releases parameter must be a list. It can contain either Release objects or a string representing a MusicBrainz release ID (either as absolute URIs or in their 36 character ASCII representation).

Adding a release that is already in the collection has no effect.

Parameters:
  - `releases` - a list of releases to add to the user collection
Raises:
  - `ConnectionError` - couldn't connect to server
  - `AuthenticationError` - invalid user name and/or password

### removeFromUserCollection(self, releases)

source code

Remove releases from a user's collection.

The releases parameter must be a list. It can contain either Release objects or a string representing a MusicBrainz release ID (either as absolute URIs or in their 36 character ASCII representation).

Removing a release that is not in the collection has no effect.

Parameters:
  - `releases` - a list of releases to remove from the user collection
Raises:
  - `ConnectionError` - couldn't connect to server
  - `AuthenticationError` - invalid user name and/or password

### getUserCollection(self, offset=0, maxitems=100)

source code

Get the releases that are in a user's collection

A maximum of 100 items will be returned for any one call to this method. To fetch more than 100 items, use the offset parameter.

Parameters:
  - `offset` - the offset to start fetching results from
  - `maxitems` - the upper limit on items to return
Returns:
  a list of musicbrainz2.wsxml.ReleaseResult objects
Raises:
  - `ConnectionError` - couldn't connect to server
  - `AuthenticationError` - invalid user name and/or password

### submitUserTags(self, entityUri, tags)

source code

Submit folksonomy tags for an entity.

Note that all previously existing tags from the authenticated user are replaced with the ones given to this method. Other users' tags are not affected.

Parameters:
  - `entityUri` - a string containing an absolute MB ID
  - `tags` - A list of either Tag objects or strings
Raises:
  - `ValueError` - invalid entityUri
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID, entity or tags
  - `AuthenticationError` - invalid user name and/or password

### getUserTags(self, entityUri)

source code

Returns a list of folksonomy tags a user has applied to an entity.

The given parameter has to be a fully qualified MusicBrainz ID, as returned by other library functions.

Note that this method only works if a valid user name and password have been set. Only the tags the authenticated user applied to the entity will be returned. If username and/or password are incorrect, an AuthenticationError is raised.

This method will return a list of Tag objects.

Parameters:
  - `entityUri` - a string containing an absolute MB ID
Raises:
  - `ValueError` - invalid entityUri
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or entity
  - `AuthenticationError` - invalid user name and/or password

### submitUserRating(self, entityUri, rating)

source code

Submit rating for an entity.

Note that all previously existing rating from the authenticated user are replaced with the one given to this method. Other users' ratings are not affected.

Parameters:
  - `entityUri` - a string containing an absolute MB ID
  - `rating` - A Rating object or integer
Raises:
  - `ValueError` - invalid entityUri
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID, entity or tags
  - `AuthenticationError` - invalid user name and/or password

### getUserRating(self, entityUri)

source code

Return the rating a user has applied to an entity.

The given parameter has to be a fully qualified MusicBrainz ID, as returned by other library functions.

Note that this method only works if a valid user name and password have been set. Only the rating the authenticated user applied to the entity will be returned. If username and/or password are incorrect, an AuthenticationError is raised.

This method will return a Rating object.

Parameters:
  - `entityUri` - a string containing an absolute MB ID
Raises:
  - `ValueError` - invalid entityUri
  - `ConnectionError` - couldn't connect to server
  - `RequestError` - invalid ID or entity
  - `AuthenticationError` - invalid user name and/or password

### submitCDStub(self, cdstub)

source code

Submit a CD Stub to the database.

The number of tracks added to the CD Stub must match the TOC and DiscID otherwise the submission wil fail. The submission will also fail if the Disc ID is already in the MusicBrainz database.

This method will only work if no user name and password are set.

Parameters:
  - `cdstub` - a CDStub object to submit
Raises:
  - `RequestError` - Missmatching TOC/Track information or the the CD Stub already exists or the Disc ID already exists