Giter VIP home page Giter VIP logo

discogs_client's Introduction

โš ๏ธ DEPRECATED

This repository is no longer maintained. You can still use a REST client like Requests or other third-party Python library to access the Discogs REST API.




Discogs API Client

This is the official Discogs API client for Python. It enables you to query the Discogs database for information on artists, releases, labels, users, Marketplace listings, and more. It also supports OAuth 1.0a authorization, which allows you to change user data such as profile information, collections and wantlists, inventory, and orders.

Build Status Coverage Status

Installation

Install the client from PyPI using your favorite package manager.

$ pip install discogs_client

Quickstart

Instantiating the client object

>>> import discogs_client
>>> d = discogs_client.Client('ExampleApplication/0.1')

Authorization (optional)

There are a couple of different authorization methods you can choose from depending on your requirements.

OAuth authentication

This method will allow your application to make requests on behalf of any user who logs in.

For this, specify your app's consumer key and secret:

>>> d.set_consumer_key('key-here', 'secret-here')
>>> # Or you can do this when you instantiate the Client

Then go through the OAuth 1.0a process. In a web app, we'd specify a callback_url. In this example, we'll use the OOB flow.

>>> d.get_authorize_url()
('request-token', 'request-secret', 'authorize-url-here')

The client will hang on to the access token and secret, but in a web app, you'd want to persist those and pass them into a new Client instance on the next request.

Next, visit the authorize URL, authenticate as a Discogs user, and get the verifier:

>>> d.get_access_token('verifier-here')
('access-token-here', 'access-secret-here')

Now you can make requests on behalf of the user.

>>> me = d.identity()
>>> "I'm {0} ({1}) from {2}.".format(me.name, me.username, me.location)
u"I'm Joe Bloggs (example) from Portland, Oregon."
>>> len(me.wantlist)
3
>>> me.wantlist.add(d.release(5))
>>> len(me.wantlist)
4

User-token authentication

This is one of the simplest ways to authenticate and become able to perform requests requiring authentication, such as search (see below). The downside is that you'll be limited to the information only your user account can see (i.e., no requests on behalf of other users).

For this, you'll need to generate a user-token from your developer settings on the Discogs website.

>>> d = discogs_client.Client('ExampleApplication/0.1', user_token="my_user_token")

Fetching data

Use methods on the client to fetch objects. You can search for objects:

>>> results = d.search('Stockholm By Night', type='release')
>>> results.pages
1
>>> artist = results[0].artists[0]
>>> artist.name
u'Persuader, The'

Or fetch them by ID:

>>> artist.id
1
>>> artist == d.artist(1)
True

You can drill down as far as you like.

>>> releases = d.search('Bit Shifter', type='artist')[0].releases[1].\
...     versions[0].labels[0].releases
>>> len(releases)
134

Artist

Query for an artist using the artist's name:

>>> artist = d.artist(956139)
>>> print artist
<Artist "...">
>>> 'name' in artist.data.keys()
True

Special properties

Get a list of Artists representing this artist's aliases:

>>> artist.aliases
[...]

Get a list of Releases by this artist by page number:

>>> artist.releases.page(1)
[...]

Release

Query for a release using its Discogs ID:

>>> release = d.release(221824)

Special properties

Get the title of this Release:

>>> release.title
u'...'

Get a list of all Artists associated with this Release:

>>> release.artists
[<Artist "...">]

Get the tracklist for this Release:

>>> release.tracklist
[...]

Get the MasterRelease for this Release:

>>> release.master
<MasterRelease "...">

Get a list of all Labels for this Release:

>>> release.labels
[...]

MasterRelease

Query for a master release using its Discogs ID:

>>> master_release = d.master(120735)

Special properties

Get the key Release for this MasterRelease:

>>> master_release.main_release
<Release "...">

Get the title of this MasterRelease:

>>> master_release.title
u'...'
>>> master_release.title == master_release.main_release.title
True

Get a list of Releases representing other versions of this MasterRelease by page number:

>>> master_release.versions.page(1)
[...]

Get the tracklist for this MasterRelease:

>>> master_release.tracklist
[...]

Label

Query for a label using the label's name:

>>> label = d.label(6170)

Special properties

Get a list of Releases from this Label by page number:

>>> label.releases.page(1)
[...]

Get a list of Labels representing sublabels associated with this Label:

>>> label.sublabels
[...]

Get the Label's parent label, if it exists:

>>> label.parent_label
<Label "Warp Records Limited">

Contributing

  1. Fork this repo
  2. Create a feature branch
  3. Open a pull-request

For more information

Check the included documentation, or just spin up a REPL and use dir() on things :)

discogs_client's People

Contributors

brephophagist avatar brunal avatar cburmeister avatar colinmarc avatar koobs avatar leo-dor avatar mbortnyck avatar murdos avatar rodneykeeling avatar sampsyo avatar susansalkeld avatar tenuki avatar vreon avatar wesrog avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

discogs_client's Issues

Unable to set order shipping price

Here is a minimal example to reproduce the error:


client = discogs_client.Client("<user_agent>", user_token="<user_token>")
order = client.order("<order_id>")
order.shipping = 9.9
order.save()

The response is 400: 'Expected mimetype of "application/json".'

This happens because you set headers['Content-Type'] = 'application/x-www-form-urlencoded' in the post request

headers = {
'Accept-Encoding': 'gzip',
'User-Agent': self.user_agent,
}
if data:
headers['Content-Type'] = 'application/x-www-form-urlencoded'
.

URL field not being fetched properly

It seems that URLs are not being fetched properly for artists, releases, videos, etc. when accessing with .url, although it still works with .data['uri']

>>> artist = d.artist(307)
>>> print artist.url
None
>>> print artist.data['uri']
https://www.discogs.com/artist/307-Boards-Of-Canada
>>> release = d.release(24432)
>>> print release.url
None
>>> print release.data['uri']
https://www.discogs.com/Boards-Of-Canada-Geogaddi/release/24432
>>> print release.videos[0].url
None
>>> print release.videos[0].data['uri']
https://www.youtube.com/watch?v=mNd2q_QnJc8

Changing per_page elements to max value?

Hi!

I am afraid of wasting API calls because of rate_limiting.

One of possible solutions is to change per_page elements to maximum value.

How can I do this on app side without changing self._per_page = 50 value in discogs_client/models.py?

Or maybe there are some better workarounds

Thanks!

search option with accents/special markings removed?

When using d.search(album_name, type='release'), sometimes the album_name in the database uses special accented characters. For example, the release "Bรฉla Fleck & the Flecktones - UFO Tofu". The problem is that when trying d.search("Bela Fleck & The Flecktones - UFO Tofu", type='release'), the result list is empty. It would be nice if there could be some option to apply a string transformation in the backend, such as [(https://pypi.python.org/pypi/Unidecode)], which would allow for a slightly fuzzier string match.

I should add that I have no idea how the backend works, so I apologize if this kind of idea would not make any sense.

Getting the Search results quantity

Hello, maybe it's not an issue but a feature request...
I can't find any method to get the total items quantity resulting from a Search, or maybe the total number of pages ?
Thanks for this module and the json switch ;-)

Handle socket, httplib, and json exceptions

Currently, socket.error exceptions raised during API requests are unhandled and passed through to the client. For consistency, the library should probably catch socket.errors and re-raise discogs_client.exceptions.HTTPErrors.

See beetbox/beets#1299 for a traceback arising from an unexpected socket closure.

Checkout fails on Windows due to invalid file names

Git checkout of repository fails....
error: unable to create file discogs_client/tests/res/artists/1/releases?per_page=50&page=1.json (Invalid argument)
error: unable to create file discogs_client/tests/res/artists/1/releases?per_page=50&page=2.json (Invalid argument)
error: unable to create file discogs_client/tests/res/database/search?q=trash80&per_page=50&page=1.json (Invalid argument)
error: unable to create file discogs_client/tests/res/masters/4242/versions?per_page=50&page=1.json (Invalid argument)
error: unable to create file discogs_client/tests/res/users/example/wants?per_page=50&page=1.json (Invalid argument)

PyPi Release?

I noticed the PyPi release is a bit behind your code. I'd love an update when you guys have a chance. Sorry if this is not the place to request, Cheers.

Client' object has no attribute 'Release'

why am I getting this error?

c:\discogs\tl_out.py(12)()
-> release = ds.Release(380484)
(Pdb) n
AttributeError: "'Client' object has no attribute 'Release'"

with this Python code:
import discogs_client as discogs
discogs.user_agent = 'jkkGetTrackLists/0.1'
ds = discogs.Client(discogs.user_agent, user_token="UyRNtkkPucDKrtMluzIRAvNoWzHjsLLRtfYvsKeG")
release = ds.Release(380484)
print(release.title)
for item in release.tracklist:
print(item)

Keven

Exclude appearances

Is there a way to get all actual releases by an artist, meaning to exclude any appearances on compilations etc. Would this be master releases? For example when I go through a specific artist releases I get roughly 200 of them but on the discogs only 14 of them are the artist own releases and rest are just appearances.

Artist Releases (Verbose Info)

Hi,

How can I get verbose info on Artist releases with discogs_client in one shot? Like here with CURL:
https://www.discogs.com/developers/#page:database,header:database-artist-releases

$ curl -s https://api.discogs.com/artists/{artist_id}/releases

{
  "pagination": {
    "per_page": 50,
    "items": 9,
    "page": 1,
    "urls": {},
    "pages": 1
  },
  "releases": [
    {
      "artist": "Nickelback",
      "id": 173765,
      "main_release": 3128432,
      "resource_url": "http://api.discogs.com/masters/173765",
      "role": "Main",
      "thumb": "https://api-img.discogs.com/lb0zp7--FLaRP0LmJ4W6DhfweNc=/fit-in/90x90/filters:strip_icc():format(jpeg):mode_rgb()/discogs-images/R-5557864-1396493975-7618.jpeg.jpg",
      "title": "Curb",
      "type": "master",
      "year": 1996
    },
    {
      "artist": "Nickelback",
      "format": "CD, EP",
      "id": 4299404,
      "label": "Not On Label (Nickelback Self-released)",
      "resource_url": "http://api.discogs.com/releases/4299404",
      "role": "Main",
      "status": "Accepted",
      "thumb": "https://api-img.discogs.com/eFRGD78N7UhtvRjhdLZYXs2QJXk=/fit-in/90x90/filters:strip_icc():format(jpeg):mode_rgb()/discogs-images/R-4299404-1361106117-3632.jpeg.jpg",
      "title": "Hesher",
      "type": "release",
      "year": 1996
    },
    {
      "artist": "Nickelback",
      "id": 173767,
      "main_release": 1905922,
      "resource_url": "http://api.discogs.com/masters/173767",
      "role": "Main",
      "thumb": "https://api-img.discogs.com/12LXbUV44IHjyb6drFZOTQxgCqs=/fit-in/90x90/filters:strip_icc():format(jpeg):mode_rgb()/discogs-images/R-1905922-1251540516.jpeg.jpg",
      "title": "Leader Of Men",
      "type": "master",
      "year": 1999
    }
  ]
}

With discogs_client i only able to get the following info:

>>> artist.releases.page(1)[0:3]
[<Release 738756 'Linear Cryptics'>, <Release 1220080 'Surge'>, <Master 248367 'The Nothings Of The North'>]

Iterating over each release independently is not very convenient and time consuming. Also, API calls are wasted.

Any help is appreciated!

Thanks

requests.get has wrong parameters

With the current git clone (but I think this was also present with the version coming from pypi) I get the following traceback:

>>> r = discogs.Release( 934425 )
>>> t = r.tracklist[9]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/discogs_client-1.1.0-py2.7.egg/discogs_client.py", line 165, in tracklist
    for track in self.data.get('tracklist', []):
  File "/usr/local/lib/python2.7/dist-packages/discogs_client-1.1.0-py2.7.egg/discogs_client.py", line 52, in data
    if self._response.content and self._response.status_code == 200:
  File "/usr/local/lib/python2.7/dist-packages/discogs_client-1.1.0-py2.7.egg/discogs_client.py", line 38, in _response
    self._cached_response = requests.get(self._uri, self._params, self._headers)
TypeError: get() takes exactly 1 argument (3 given)

during the install (python setup.py install) it installed version 0.6.1 of the python-requests library.

I was doing a fork but right now git push doesn't seem to be working, so here is just the trivial patch as plain text:

diff --git a/discogs_client.py b/discogs_client.py
index f52d769..ee2e48d 100644
--- a/discogs_client.py
+++ b/discogs_client.py
@@ -35,7 +35,7 @@ class APIBase(object):
         if not self._cached_response:
             if not self._check_user_agent():
                 raise DiscogsAPIError, 'Invalid or no User-Agent set'
-            self._cached_response = requests.get(self._uri, self._params, self._headers)
+            self._cached_response = requests.get(self._uri, params=self._params, headers=self._headers)
 
         return self._cached_response

Allow search results filtering

Related to #7, it would be nice to have a clean way of filtering results on something like the object type. When all you're interested in is master releases for a certain query, a filter as follows is rather ugly:

releases = [release for release in results if 'master' in release.__class__.__name__.lower()]

The Search object could do this in a cleaner way, for example something along the lines of

search = Search('britney spears baby one more time').filter(type = 'master')

Needless to say, an API like this might allow more advanced filters than just the object type of the result.

Put a new tag on master

Hi,
As mentioned in PR #43 I believe it could be time to push a new tag (e.g. 2.0.3 or 2.1.0) to allow python3 projects using discogs_client to put it in their setup.py

Production Credits

I'm trying to pull the production credits that is available on Discogs via the API.

Below is code used...

Using this code:
ds = dc.Client('my_user_agent/1.0', user_token='TGjmBpvRysxrrrvnorTshtEFFQcNsqfXNBPIIhVd')
release = ds.release('8976417')
track = release.tracklist[0]
print(track.credits[0])

Output is:
<Artist 1280700 'Darren Dodd'>

In this case Darren Dodd was playing Drums on the track but I'm not able to pull that information.

Does anyone know if it's possible?

Please add support for lists

I just saw these were added 16 hours ago, but being able to retrieve all lists for a user or a list in general like the API added would be nice.

Can I do an "Advanced Search" from the API?

So I got the API working but I'm trying to search for specific Artist, Album, and SongTitle. However, I have found many times that using the generic search function on discogs results in a 404 error from their web service! >:( If I use the advanced search and punch in specific artist=, release_title=, and track= I get a result. Is there some way to use this advanced search function in the API?

Or maybe I just don't know how to enter advanced search information into the generic search box. Someone help, please.

Here is an example of my request:
releases_found = discogs.Search("artist:"" + artist + "" track:"" + title + """)

Bad: http://www.discogs.com/search?q=artist%3AWeird+Al+Yankovic+track%3AIt%27s+All+About+the+Pentiums&btn=&type=all

Good: http://www.discogs.com/advanced_search?artist=Weird+Al+Yankovic&country=US&release_title=Running+With+Scissors&track=It's+All+About+The+Pentiums&btn=Search+Releases

Thanks,
-Greg

404s with Python

hello
i have this exception on this code

import discogs_client as discogs
discogs.user_agent = 'AwesomeDiscogsBrowser/0.1 +http://adb.example.com'
discogs.Artist('Aphex Twin').data['realname']
/usr/lib/python2.7/site-packages/discogs_client.pyc in data(self)
55 else:
56 status_code = self._response.status_code
---> 57 raise DiscogsAPIError, '%s %s' % (status_code, httplib.responses[status_code])
58
59 class DiscogsAPIError(BaseException):

DiscogsAPIError: 404 Not Found

thanks!

How to list all releases in each collection's folders?

Hi,

I'm struggling a lot on your API to find out this issue. I didn't find anything about this on your documentation.
Maybe it's because it's a TODO topic in class CollectionItemInstance(PrimaryAPIObject)?
Anyway, let me know if I missed something and congrats for this job!

Release attributes return different values depending on previosly accessed fiels

from discogs_client import Client, Release


client = Client('python')
releases = [i for i in client.search('Flying Horseman') if isinstance(i, Release)]

r = releases[3]
print r.title           # Flying Horseman - City Same City
print r.data['title']   # Flying Horseman - City Same City
print r.master.title    # City Same City
print r.title           # City Same City

This behavior is really strange:
Accessing Release.master.title also changes Release.title.
I can't find a way to get just album name without artist, it works only if I access master first.

Allow specification of fields in Search

The search class is a very helpful thing to find id's of what you're looking for, but I often feel like searching for just a string is a handicap. Allowing the specification of fields would make searching a lot more powerful.

For example:

search = Search('baby one more time', artist = 'britney spears')

The above Search object could return albums that feature a song with the name of the first argument or an album, single, EP or whatever with that name, while keeping the artist limitation (which might be a search in itself) in mind.

Attempting user-token authentication results in an error: 'You must authenticate to access this resource.'

I am trying to follow the quickstart guide in the README but am running into problems trying to use the user token. I don't know why the version says 2.0.2, but this is from the HEAD of master.

>>> import discogs_client
>>> discogs_client.__version__
u'2.0.2'
>>> d = discogs_client.Client('JMoney/0.1', token="...")
>>> results = d.search('Stockholm By Night', type='release')
>>> results.pages
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "discogs_client/models.py", line 336, in pages
    self._load_pagination_info()
  File "discogs_client/models.py", line 297, in _load_pagination_info
    data = self.client._get(self._url_for_page(1))
  File "discogs_client/client.py", line 123, in _get
    return self._request('GET', url)
  File "discogs_client/client.py", line 120, in _request
    raise HTTPError(body['message'], status_code)
discogs_client.exceptions.HTTPError: 401: You must authenticate to access this resource.
>>> 

Not all data is initially fetched

It looks like you've got to call the release object before all of the fields are available:

>>> release = d.release(846665) 
>>> release.data['extraartists'] 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
KeyError: 'extraartists' 
>>> release 
<Release 846665 u'A Whole New World'> 
>>> release.data['extraartists'] 
[{u'join': u'', u'name': u'Nicky Graham', u'anv': u'', u'tracks': u'', u'role': 
u'Producer', u'resource_url': u'http://api.discogs.com/artists/171183', u'id': 1 
71183}] 

Incorrect version in sources

discogs-client installed with pip:

$ pip show discogs-client

---
Metadata-Version: 1.1
Name: discogs-client
Version: 2.2.1
Summary: Official Python API client for Discogs
Home-page: https://github.com/discogs/discogs_client
Author: Discogs
Author-email: [email protected]
License: UNKNOWN
Location: /usr/lib/python3.5/site-packages
Requires: requests, six, oauthlib
Python 3.5.1 (default, Mar  3 2016, 09:29:07) 
[GCC 5.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import discogs_client
>>> discogs_client.__version__
'2.0.2'
$ grep --color -RIi --color version /usr/lib/python3.5/site-packages/discogs_client/*
/usr/lib/python3.5/site-packages/discogs_client/__init__.py:__version_info__ = 2, 0, 2
/usr/lib/python3.5/site-packages/discogs_client/__init__.py:__version__ = '2.0.2'
/usr/lib/python3.5/site-packages/discogs_client/models.py:        if sys.version_info < (3,):
/usr/lib/python3.5/site-packages/discogs_client/models.py:    versions = ObjectCollection('Release')

Unable to Retrieve Data using API

I haven't been able to get this Python API working for either Python 2.7 or Python 3.5. There's a post on the DIscogs forums with more info as well ( https://www.discogs.com/forum/thread/733972?page=1 ), but here's the stack trace:

d = discogs_client.Client('ExampleApplication/0.1', user_token="fusHcGIlCGHeRcHyYreV")
results = d.search('Stockholm By Night', type='release')
print(results[0])

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 377, in _make_request
httplib_response = conn.getresponse(buffering=True)
TypeError: getresponse() got an unexpected keyword argument 'buffering'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 560, in urlopen
body=body, headers=headers)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 379, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.5/http/client.py", line 1197, in getresponse
response.begin()
File "/usr/lib/python3.5/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.5/http/client.py", line 266, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 376, in send
timeout=timeout
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 610, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 247, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/lib/python3/dist-packages/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 560, in urlopen
body=body, headers=headers)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 379, in _make_request
httplib_response = conn.getresponse()
File "/usr/lib/python3.5/http/client.py", line 1197, in getresponse
response.begin()
File "/usr/lib/python3.5/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.5/http/client.py", line 266, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
requests.packages.urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.5/dist-packages/discogs_client/models.py", line 361, in getitem
page = self.page(page_index)
File "/usr/local/lib/python3.5/dist-packages/discogs_client/models.py", line 347, in page
data = self.client._get(self._url_for_page(index))
File "/usr/local/lib/python3.5/dist-packages/discogs_client/client.py", line 123, in _get
return self._request('GET', url)
File "/usr/local/lib/python3.5/dist-packages/discogs_client/client.py", line 110, in _request
content, status_code = self._fetcher.fetch(self, method, url, data=data, headers=headers)
File "/usr/local/lib/python3.5/dist-packages/discogs_client/fetchers.py", line 63, in fetch
data=data, headers=headers)
File "/usr/lib/python3/dist-packages/requests/api.py", line 53, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 426, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

TypeError: __repr__ returned non-string (type bytes)

Here is a minimal example of my attempts to interact with the Discogs API:

from SensitiveInformation.discogs_application_info import provide_discogs_auth, provide_verifier
import discogs_client

discogs_consumer_key, discogs_consumer_secret = provide_discogs_auth()
discogs = discogs_client.Client(user_agent="ThoughfulMachineLearning",
                                consumer_key=discogs_consumer_key,
                          consumer_secret=discogs_consumer_secret)
discogs_auth_url = discogs.get_authorize_url()
discogs.get_access_token(verifier=provide_verifier())
discogs.identity()

The functions provide_discogs_auth and provide_verifier simply return the consumer key & secret and the verifier from user authorization. get_access_token returns the access key and secret as expected.

However, on the last line, when I make an API call, I get:

Out[38]: In[39]: discogs.identity()
Traceback (most recent call last):
Out[39]:   File "/usr/local/lib/python3.4/dist-packages/IPython/core/formatters.py", line 219, in catch_format_error
    r = method(self, *args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/IPython/core/formatters.py", line 690, in __call__
    printer.pretty(obj)
  File "/usr/local/lib/python3.4/dist-packages/IPython/lib/pretty.py", line 407, in pretty
    return _default_pprint(obj, self, cycle)
  File "/usr/local/lib/python3.4/dist-packages/IPython/lib/pretty.py", line 527, in _default_pprint
    _repr_pprint(obj, p, cycle)
  File "/usr/local/lib/python3.4/dist-packages/IPython/lib/pretty.py", line 709, in _repr_pprint
    output = repr(obj)
TypeError: __repr__ returned non-string (type bytes)

Not sure if this is related to IPython or the client library, but would appreciate help either way. Thanks.

How to get just the singles?

Hi guys, sorry if I open an issue for what is actually a question, but I think it's just easier.

How can I retrieve just the singles/EPs for a given artist?

I've tried like:

engine.search('Ricardo Villalobos', type='releases', subtype='singles-eps')

and the URL is formed correctly, but result set fetched is identical.

My guess is that I just have to refer to the tracklist - both the Master and Release entities have this.

Thanks in advance!

Release CatNo

In a curl request for a particular release, I can see release.labels.catno.
However, when using the client, release.labels only return items with the label ID and name, no other fields are provided

Orders count 401s even when authenticated

Despite being authenticated, I get a 401: You must authenticate to access this resource message when running me.orders.count. I can get other protected resources, however.

Non-ASCII searches fail because python-oauth2 is broken

Searching for a non-ASCII term causes this error:

>>> import discogs_client
>>> c = discogs_client.Client('user_agent', 'bogus_key', 'bogus_secret')
>>> c.search(u'caf\xe9'.encode('utf8')).page(1)
Traceback (most recent call last):
[ ... snip ... ]
  File "/usr/local/lib/python2.7/site-packages/oauth2/__init__.py", line 442, in to_url
    urllib.urlencode(query, True), fragment)
  File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1357, in urlencode
    l.append(k + '=' + quote_plus(str(elt)))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-4: ordinal not in range(128)

This is due to a known bug in python-oauth2: joestump/python-oauth2#154. That library, unfortunately, appears to be abandoned: the last commit was in 2011 (c.f. this lament over the sorry state of Python OAuth libraries).

It's worth noting that this was not an issue when sending non-ASCII requests without OAuth authentication because they don't go through the broken library. This has only come up recently because the search API now requires authentication, so we're now these previously-working requests are now hitting this bug.

As unattractive as it seems, I think the only solution may be to move to a more modern OAuth library. Personally, I've had success with rauth.

get_authorize_url throws discogs_client.exceptions.AuthorizationError: 401: Could not get request token. Response: 'Parameter not found: oauth_consumer_key'

The oauth consumer key is not being placed into the POST data.

oauthlib-1.1.2
requests-2.12.5

Testcase from the quickstart documentation:

import discogs_client as dc
consumer_key = '...'
consumer_secret = '...'
ds = dc.Client('my_user_agent/1.0',
        consumer_key=consumer_key,
        consumer_secret=consumer_secret,
        )
auth_url = ds.get_authorize_url()

This results in:

Traceback (most recent call last):
  File "discogs-test.py", line 12, in <module>
    auth_url = ds.get_authorize_url()
  File "/usr/lib64/python2.7/site-packages/discogs_client/client.py", line 63, in get_authorize_url
    raise AuthorizationError('Could not get request token.', status_code, content)
discogs_client.exceptions.AuthorizationError: 401: Could not get request token. Response: 'Parameter not found: oauth_consumer_key'

Enabling httplib & requests debug, the following can be seen:

DEBUG:oauthlib.oauth1.rfc5849:Collected params: [(u'oauth_version', u'1.0'), (u'oauth_consumer_key', xxxxx'), (u'oauth_signature_method', u'HMAC-SHA1'), (u'oauth_nonce', u'42713897882581496191487477323'), (u'oauth_timestamp', u'1487477323'), (u'Content-Type', u'application/x-www-form-urlencoded'), (u'User-Agent', u'beets/1.4.3 +http://beets.io/')]
DEBUG:oauthlib.oauth1.rfc5849:Normalized params: Content-Type=application%2Fx-www-form-urlencoded&User-Agent=beets%2F1.4.3%20%2Bhttp%3A%2F%2Fbeets.io%2F&oauth_consumer_key=xxxx&oauth_nonce=42713897882581496191487477323&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1487477323&oauth_version=1.0
DEBUG:oauthlib.oauth1.rfc5849:Normalized URI: https://api.discogs.com/oauth/request_token
DEBUG:oauthlib.oauth1.rfc5849:Base signing string: POST&https%3A%2F%2Fapi.discogs.com%2Foauth%2Frequest_token&Content-Type%3Dapplication%252Fx-www-form-urlencoded%26User-Agent%3Dbeets%252F1.4.3%2520%252Bhttp%253A%252F%252Fbeets.io%252F%26oauth_consumer_key%xxxx%26oauth_nonce%3D42713897882581496191487477323%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1487477323%26oauth_version%3D1.0
DEBUG:oauthlib.oauth1.rfc5849:Signature: 4+mN1iYQqtw+//7vjlkqStd1wbQ=
DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): api.discogs.com
send: 'POST /oauth/request_token HTTP/1.1\r\nHost: api.discogs.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: beets/1.4.3 +http://beets.io/\r\nContent-Type: application/x-www-form-urlencoded\r\nAuthorization: Basic YW5vbnltb3VzOmNtZGZ0cEBleGFtcGxlLmNvbQ==\r\nContent-Length: 101\r\n\r\n'
send: u'Content-Type=application%2Fx-www-form-urlencoded&User-Agent=beets%2F1.4.3+%2Bhttp%3A%2F%2Fbeets.io%2F'
reply: 'HTTP/1.1 401 UNAUTHORIZED\r\n'
header: Server: nginx
header: Date: Sun, 19 Feb 2017 04:08:43 GMT
header: Content-Type: application/x-www-form-urlencoded
header: Content-Length: 39
header: Access-Control-Allow-Headers: Content-Type, authorization
header: Access-Control-Allow-Methods: GET,PUT,POST,DELETE,PATCH
header: WWW-Authenticate: OAuth realm="http://api.discogs.com"
header: X-Discogs-Media-Type: discogs.v2
header: Access-Control-Allow-Origin: *
header: X-Frame-Options: SAMEORIGIN
header: X-XSS-Protection: 1; mode=block
header: X-Content-Type-Options: nosniff
header: Strict-Transport-Security: max-age=16000000
DEBUG:requests.packages.urllib3.connectionpool:https://api.discogs.com:443 "POST /oauth/request_token HTTP/1.1" 401 39
error: communication with Discogs failed

404 Not found when fetching secondary artist...

When fetching a certain secondary artist, I get a 404 error:

>>> r = discogs.Release( 934425 )
>>> t = r.tracklist[9]
>>> t['extraartists']['Guitar, Bass'][0]['artists'].data['name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/discogs_client.py", line 54, in data
    raise DiscogsAPIError, '%s %s' % (status_code, httplib.responses[status_code])
discogs_client.DiscogsAPIError: 404 Not Found

See the web-page of the release here: http://www.discogs.com/Devin-The-Dude-Waitin-To-Inhale/release/934425 - track 10 is the track of interest. All other artists work fine!

Increase test coverage for network request fetchers

I noticed there aren't any tests for the fetchers which make calls to the api, this can be done by using wsgi_intercept to intercept network requests and then returning statically coded responses much like you do currently with the other fetchers. At Adblock Plus we use wsgi_intercept in couple test suites like here and here. Even though we are using pytest it shouldn't be a problem to do this with unittest/nose and I would be happy to implement the tests and intercepts as well.

Any plans to replace oauth2 with oauthlib?

Many linux distro's are moving towards python3. There doesnt at the moment seem to be a common oauth2 library for python3.

There is however the common oauthlib library - works for both python2 and python3.

Are there any plans to replace the "deprecated" oauth2 libary client with oauthlib instead?

in debian/ubuntu the two packages are python-oauthlib and python3-oauthlib respectively

For me personally, I have had to drop support for discogs for my opensource app because of the forced requirement to move to python3. I would love to reimplement support - but to the question above - any plans to move to something that will work with both python2 & python3?

Ship tests with sdist and hookup setup.py test command

The discogs_client/tests directory is missing in the PyPi sdist. This precludes downstream packagers (and users) from running QA & tests.

While you're there, add test_suite='discogs_client.tests' to setup.py so the 'test' command just works.

Trying to search for all of 'Columbia's' releases

Have configured my user_agent but am getting this error. I was able to get releases for Columbia Records, but there seemed to only be 3,747. I didn't see any pagination options.
When searching for releases for just "Columbia", I get this error:

import discogs_client as discogs
discogs.user_agent = 'my-user-agent-string'
label = discogs.Label('Columbia')
releases = label.releases

Traceback (most recent call last):
File "", line 1, in
File "/Library/Python/2.7/site-packages/discogs_client.py", line 249, in releases
return self.data.get('releases')
File "/Library/Python/2.7/site-packages/discogs_client.py", line 57, in data
raise DiscogsAPIError, '%s %s' % (status_code, httplib.responses[status_code])
discogs_client.DiscogsAPIError: 200 OK

Unnecessary API request

Example:
label = client.label(111)
releases = label.releases.page(0)
print releases[0].title

This does 2 API requests:
GET /labels/111
GET /labels/111/releases?per_page=50&page=0

The first one is unnecessary. Same thing happens with artists.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.