Merge pull request #42 from akx/session

Use Requests sessions for connection pooling
This commit is contained in:
Paul Lamere 2015-01-05 14:52:47 -05:00
commit e2714bbd5e
2 changed files with 45 additions and 14 deletions

View File

@ -38,21 +38,32 @@ class Spotify(object):
print(user)
'''
trace = False
"""enable tracing"""
trace = False # Enable tracing?
_auth = None
def __init__(self, auth=None):
def __init__(self, auth=None, requests_session=True):
'''
creates a spotify object
Create a Spotify API object.
:param auth: An authorization token (optional)
:param requests_session:
A Requests session object or a truthy value to create one.
A falsy value disables sessions.
It should generally be a good idea to keep sessions enabled
for performance reasons (connection pooling).
Parameters:
- auth - the optional authorization token
'''
self.prefix = 'https://api.spotify.com/v1/'
self._auth = auth
if isinstance(requests_session, requests.Session):
self._session = requests_session
else:
if requests_session: # Build a new session.
self._session = requests.Session()
else: # Use the Requests API module as a "session".
from requests import api
self._session = api
def _auth_headers(self):
if self._auth:
return {'Authorization': 'Bearer {0}'.format(self._auth)}
@ -67,12 +78,11 @@ class Spotify(object):
headers['Content-Type'] = 'application/json'
if payload:
r = requests.request(method, url, headers=headers,
data=json.dumps(payload), **args)
else:
r = requests.request(method, url, headers=headers, **args)
args["data"] = json.dumps(payload)
if self.trace:
r = self._session.request(method, url, headers=headers, **args)
if self.trace: # pragma: no cover
print()
print(method, r.url)
if payload:
@ -85,7 +95,7 @@ class Spotify(object):
-1, u'%s:\n %s' % (r.url, r.json()['error']['message']))
if len(r.text) > 0:
results = r.json()
if self.trace:
if self.trace: # pragma: no cover
print('RESP', results)
print()
return results

View File

@ -2,6 +2,7 @@
import spotipy
import unittest
import pprint
from spotipy.client import SpotifyException
class TestSpotipy(unittest.TestCase):
@ -114,6 +115,26 @@ class TestSpotipy(unittest.TestCase):
except spotipy.SpotifyException:
self.assertTrue(True)
def test_unauthenticated_post_fails(self):
with self.assertRaises(SpotifyException) as cm:
self.spotify.user_playlist_create("spotify", "Best hits of the 90s")
self.assertEqual(cm.exception.http_status, 401)
def test_custom_requests_session(self):
from requests import Session
sess = Session()
sess.headers["user-agent"] = "spotipy-test"
with_custom_session = spotipy.Spotify(requests_session=sess)
self.assertTrue(with_custom_session.user(user="akx")["uri"] == "spotify:user:akx")
def test_force_no_requests_session(self):
from requests import Session
with_no_session = spotipy.Spotify(requests_session=False)
self.assertFalse(isinstance(with_no_session._session, Session))
self.assertTrue(with_no_session.user(user="akx")["uri"] == "spotify:user:akx")
'''
Need tests for: