diff --git a/TestDailymotion.py b/TestDailymotion.py index f0e242b..7df7eab 100644 --- a/TestDailymotion.py +++ b/TestDailymotion.py @@ -5,20 +5,25 @@ import time import os + class TestA(unittest.TestCase): @classmethod def setUpClass(self): - self.api_base_url = config.BASE_URL or 'http://api.dailymotion.com' - self.api_key = config.CLIENT_ID - self.api_secret = config.CLIENT_SECRET - self.username = config.USERNAME - self.password = config.PASSWORD - self.scope = ['manage_videos', 'manage_playlists', 'userinfo'] - self.redirect_uri = config.REDIRECT_URI - self.oauth_authorize_endpoint_url = config.OAUTH_AUTHORIZE_URL or 'https://api.dailymotion.com/oauth/authorize' - self.oauth_token_endpoint_url = config.OAUTH_TOKEN_URL or 'https://api.dailymotion.com/oauth/token' - self.session_file_directory = './data' + self.api_base_url = config.BASE_URL or 'http://api.dailymotion.com' + self.api_key = config.CLIENT_ID + self.api_secret = config.CLIENT_SECRET + self.username = config.USERNAME + self.password = config.PASSWORD + self.scope = ['manage_videos', 'manage_playlists', 'userinfo'] + self.redirect_uri = config.REDIRECT_URI + self.oauth_authorize_endpoint_url = ( + config.OAUTH_AUTHORIZE_URL or + 'https://api.dailymotion.com/oauth/authorize') + self.oauth_token_endpoint_url = ( + config.OAUTH_TOKEN_URL or + 'https://api.dailymotion.com/oauth/token') + self.session_file_directory = './data' if not os.path.exists(self.session_file_directory): os.makedirs(self.session_file_directory) @@ -31,7 +36,9 @@ def test_init(self): d = dailymotion.Dailymotion() self.assertEqual(d.api_base_url, 'https://api.dailymotion.com') - d = dailymotion.Dailymotion(api_base_url='http://api.stage.dailymotion.com', timeout=10, debug=True) + d = dailymotion.Dailymotion( + api_base_url='http://api.stage.dailymotion.com', timeout=10, + debug=True) self.assertEqual(d.api_base_url, 'http://api.stage.dailymotion.com') self.assertEqual(d.timeout, 10) self.assertEqual(d.debug, True) @@ -46,62 +53,103 @@ def test_get(self): def test_set_grant_type(self): d = dailymotion.Dailymotion() - self.assertRaises(dailymotion.DailymotionClientError, d.set_grant_type, 'password', api_secret=self.api_secret, scope=self.scope, - info={'username': self.username, 'password': self.password}) - self.assertRaises(dailymotion.DailymotionClientError, d.set_grant_type, 'password', api_secret=self.api_secret, scope=self.scope) - self.assertRaises(dailymotion.DailymotionClientError, d.set_grant_type, 'password', api_secret=self.api_secret, scope=None) + self.assertRaises(dailymotion.DailymotionClientError, d.set_grant_type, + 'password', api_secret=self.api_secret, + scope=self.scope, info={ + 'username': self.username, + 'password': self.password + }) + self.assertRaises(dailymotion.DailymotionClientError, d.set_grant_type, + 'password', api_secret=self.api_secret, + scope=self.scope) + self.assertRaises(dailymotion.DailymotionClientError, d.set_grant_type, + 'password', api_secret=self.api_secret, scope=None) def test_get_authorization_url(self): - d = dailymotion.Dailymotion(api_base_url=self.api_base_url, oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url) - d.set_grant_type('authorization', api_key=self.api_key, api_secret=self.api_secret, scope=self.scope, info={'redirect_uri' : self.redirect_uri}) - authorization_url = d.get_authorization_url(redirect_uri=self.redirect_uri, scope=self.scope) - self.assertEqual(re.match('https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&%?#-]{1,300})?',authorization_url) == None, False) + d = dailymotion.Dailymotion( + api_base_url=self.api_base_url, + oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url) + d.set_grant_type('authorization', api_key=self.api_key, + api_secret=self.api_secret, scope=self.scope, + info={'redirect_uri': self.redirect_uri}) + authorization_url = d.get_authorization_url( + redirect_uri=self.redirect_uri, scope=self.scope) + self.assertEqual(re.match( + 'https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})' + '(?:/[\w&%?#-]{1,300})?', + authorization_url) is None, False) def test_get_access_token(self): - d = dailymotion.Dailymotion(api_base_url=self.api_base_url, - oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, - oauth_token_endpoint_url=self.oauth_token_endpoint_url) - d.set_grant_type('password', api_key=self.api_key, api_secret=self.api_secret, scope=self.scope, info={'username': self.username, 'password': self.password}) + d = dailymotion.Dailymotion( + api_base_url=self.api_base_url, + oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, + oauth_token_endpoint_url=self.oauth_token_endpoint_url) + d.set_grant_type('password', api_key=self.api_key, + api_secret=self.api_secret, scope=self.scope, + info={ + 'username': self.username, + 'password': self.password + }) access_token = d.get_access_token() - self.assertEqual(isinstance (access_token, str) or isinstance(access_token, unicode), True) + self.assertEqual(isinstance(access_token, str) or + isinstance(access_token, unicode), True) d.logout() def test_set_access_token(self): d = dailymotion.Dailymotion() - d.set_grant_type('password', api_key=self.api_key, api_secret=self.api_secret, scope=self.scope, info={'username': self.username, 'password': self.password}) + d.set_grant_type('password', api_key=self.api_key, + api_secret=self.api_secret, scope=self.scope, + info={ + 'username': self.username, + 'password': self.password + }) d.set_access_token(d.get_access_token()) response = d.get('/me/?fields=fullname') - self.assertEqual(isinstance (response.get('fullname'), str) or isinstance(response.get('fullname'), unicode), True) + self.assertEqual(isinstance(response.get('fullname'), str) or + isinstance(response.get('fullname'), unicode), True) d.logout() def test_auth_call(self): - d = dailymotion.Dailymotion(api_base_url=self.api_base_url, - oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, - oauth_token_endpoint_url=self.oauth_token_endpoint_url, - session_store_enabled=True) - - d.set_grant_type('password', api_key=self.api_key, api_secret=self.api_secret, scope=self.scope, info={'username': self.username, 'password': self.password}) + d = dailymotion.Dailymotion( + api_base_url=self.api_base_url, + oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, + oauth_token_endpoint_url=self.oauth_token_endpoint_url, + session_store_enabled=True) + + d.set_grant_type('password', api_key=self.api_key, + api_secret=self.api_secret, scope=self.scope, + info={ + 'username': self.username, + 'password': self.password + }) response = d.get('/me/?fields=fullname') - self.assertEqual(isinstance (response.get('fullname'), str) or isinstance(response.get('fullname'), unicode), True) + self.assertEqual(isinstance(response.get('fullname'), str) or + isinstance(response.get('fullname'), unicode), True) d.logout() def test_upload(self): - d = dailymotion.Dailymotion(api_base_url=self.api_base_url, - oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, - oauth_token_endpoint_url=self.oauth_token_endpoint_url, - session_store_enabled=True) - - d.set_grant_type('password', api_key=self.api_key, api_secret=self.api_secret, scope=self.scope, info={'username': self.username, 'password': self.password}) + d = dailymotion.Dailymotion( + api_base_url=self.api_base_url, + oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, + oauth_token_endpoint_url=self.oauth_token_endpoint_url, + session_store_enabled=True) + + d.set_grant_type('password', api_key=self.api_key, + api_secret=self.api_secret, scope=self.scope, + info={ + 'username': self.username, + 'password': self.password + }) url = d.upload('./examples/video.mp4') - self.assertEqual(re.match('https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&%?#-]{1,300})?',url) == None, False) - d.post('/videos', {'url' : url, - 'title' : 'my_test_upload_%s' % time.strftime("%c"), - 'published' : 'true', - 'channel' : 'news' - }) + self.assertEqual(re.match( + 'https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})' + '(?:/[\w&%?#-]{1,300})?', url) is None, False) + d.post('/videos', {'url': url, + 'title': 'my_test_upload_%s' % time.strftime("%c"), + 'published': 'true', + 'channel': 'news'}) d.logout() - def test_session_store_option(self): d = dailymotion.Dailymotion(session_store_enabled=False) self.assertFalse(d._session_store_enabled) @@ -113,29 +161,45 @@ def test_session_store_option(self): self.assertEqual(d.DEFAULT_SESSION_STORE, d._session_store_enabled) def test_in_memory_session(self): - d = dailymotion.Dailymotion(api_base_url=self.api_base_url, - oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, - oauth_token_endpoint_url=self.oauth_token_endpoint_url, - session_store_enabled=True) - d.set_grant_type('password', api_key=self.api_key, api_secret=self.api_secret, scope=self.scope, info={'username': self.username, 'password': self.password}) + d = dailymotion.Dailymotion( + api_base_url=self.api_base_url, + oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, + oauth_token_endpoint_url=self.oauth_token_endpoint_url, + session_store_enabled=True) + d.set_grant_type('password', api_key=self.api_key, + api_secret=self.api_secret, scope=self.scope, + info={ + 'username': self.username, + 'password': self.password + }) access_token = d.get_access_token() - self.assertEqual(isinstance (access_token, str) or isinstance(access_token, unicode), True) + self.assertEqual(isinstance(access_token, str) or + isinstance(access_token, unicode), True) second_access_token = d.get_access_token() - self.assertEqual(isinstance (second_access_token, str) or isinstance(second_access_token, unicode), True) + self.assertEqual(isinstance(second_access_token, str) or + isinstance(second_access_token, unicode), True) self.assertEqual(second_access_token, access_token) d.logout() def test_file_storage_session(self): fs = dailymotion.FileSessionStore(self.session_file_directory) - d = dailymotion.Dailymotion(api_base_url=self.api_base_url, - oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, - oauth_token_endpoint_url=self.oauth_token_endpoint_url, - session_store_enabled=True, - session_store=fs) - d.set_grant_type('password', api_key=self.api_key, api_secret=self.api_secret, scope=self.scope, info={'username': self.username, 'password': self.password}) + d = dailymotion.Dailymotion( + api_base_url=self.api_base_url, + oauth_authorize_endpoint_url=self.oauth_authorize_endpoint_url, + oauth_token_endpoint_url=self.oauth_token_endpoint_url, + session_store_enabled=True, + session_store=fs) + d.set_grant_type('password', api_key=self.api_key, + api_secret=self.api_secret, scope=self.scope, + info={ + 'username': self.username, + 'password': self.password + }) access_token = d.get_access_token() - self.assertEqual(isinstance (access_token, str) or isinstance(access_token, unicode), True) + self.assertEqual(isinstance(access_token, str) or + isinstance(access_token, unicode), True) second_access_token = d.get_access_token() - self.assertEqual(isinstance (second_access_token, str) or isinstance(second_access_token, unicode), True) + self.assertEqual(isinstance(second_access_token, str) or + isinstance(second_access_token, unicode), True) self.assertEqual(second_access_token, access_token) d.logout() diff --git a/dailymotion.py b/dailymotion.py index 6958945..61b1fc6 100755 --- a/dailymotion.py +++ b/dailymotion.py @@ -17,14 +17,6 @@ except ImportError: # Python 2 from urllib import urlencode -try: - from urllib.parse import parse_qsl -except ImportError: # Python 2 - try: - from urlparse import parse_qsl - except ImportError: # Python < 2.6 - from cgi import parse_qsl - class DailymotionClientError(Exception): def __init__(self, message, error_type=None): @@ -35,20 +27,37 @@ def __init__(self, message, error_type=None): self.message = '%s: %s' % (error_type, message) super(DailymotionClientError, self).__init__(self.message) -class DailymotionApiError(DailymotionClientError): pass -class DailymotionAuthError(DailymotionClientError): pass -class DailymotionTokenExpired(DailymotionClientError): pass -class DailymotionUploadTransportError(DailymotionClientError): pass -class DailymotionUploadInvalidResponse(DailymotionClientError): pass -class DailymotionUploadError(DailymotionClientError): pass +class DailymotionApiError(DailymotionClientError): + pass + + +class DailymotionAuthError(DailymotionClientError): + pass + + +class DailymotionTokenExpired(DailymotionClientError): + pass + + +class DailymotionUploadTransportError(DailymotionClientError): + pass + + +class DailymotionUploadInvalidResponse(DailymotionClientError): + pass + + +class DailymotionUploadError(DailymotionClientError): + pass + class SessionStore(object): def __init__(self): self._sessions = defaultdict(dict) - self._user = 'default' + self._user = 'default' def set_user(self, user=None): self._user = user if user else 'default' @@ -139,46 +148,61 @@ def current(self): class Dailymotion(object): - DEFAULT_DEBUG = False - DEFAULT_TIMEOUT = 5 - DEFAULT_API_BASE_URL = 'https://api.dailymotion.com' - DEFAULT_AUTHORIZE_URL = 'https://www.dailymotion.com/oauth/authorize' - DEFAULT_TOKEN_URL = 'https://api.dailymotion.com/oauth/token' - DEFAULT_SESSION_STORE = True - - def __init__(self, api_base_url=None, debug=None, timeout=None, oauth_authorize_endpoint_url=None, oauth_token_endpoint_url=None, session_store_enabled=None, session_store=None): - - self.api_base_url = api_base_url or self.DEFAULT_API_BASE_URL - self.debug = debug or self.DEFAULT_DEBUG - self.timeout = timeout or self.DEFAULT_TIMEOUT - self.oauth_authorize_endpoint_url = oauth_authorize_endpoint_url or self.DEFAULT_AUTHORIZE_URL - self.oauth_token_endpoint_url = oauth_token_endpoint_url or self.DEFAULT_TOKEN_URL - self._grant_type = None - self._grant_info = {} - self._headers = {'Accept' : 'application/json', - 'User-Agent' : 'Dailymotion-Python/%s (Python %s)' % (__version__, __python_version__)} - self._session_store_enabled = self.DEFAULT_SESSION_STORE if session_store_enabled is None else session_store_enabled - self._session_store = SessionStore() if session_store is None else session_store - - - def set_grant_type(self, grant_type = 'client_credentials', api_key=None, api_secret=None, scope=None, info=None): + DEFAULT_DEBUG = False + DEFAULT_TIMEOUT = 5 + DEFAULT_API_BASE_URL = 'https://api.dailymotion.com' + DEFAULT_AUTHORIZE_URL = 'https://www.dailymotion.com/oauth/authorize' + DEFAULT_TOKEN_URL = 'https://api.dailymotion.com/oauth/token' + DEFAULT_SESSION_STORE = True + + def __init__( + self, api_base_url=None, debug=None, timeout=None, + oauth_authorize_endpoint_url=None, oauth_token_endpoint_url=None, + session_store_enabled=None, session_store=None): + + self.api_base_url = api_base_url or self.DEFAULT_API_BASE_URL + self.debug = debug or self.DEFAULT_DEBUG + self.timeout = timeout or self.DEFAULT_TIMEOUT + self.oauth_authorize_endpoint_url = (oauth_authorize_endpoint_url or + self.DEFAULT_AUTHORIZE_URL) + self.oauth_token_endpoint_url = (oauth_token_endpoint_url or + self.DEFAULT_TOKEN_URL) + self._grant_type = None + self._grant_info = {} + self._headers = {'Accept': 'application/json', + 'User-Agent': 'Dailymotion-Python/%s (Python %s)' % + (__version__, __python_version__)} + self._session_store_enabled = (self.DEFAULT_SESSION_STORE + if session_store_enabled is None + else session_store_enabled) + self._session_store = (SessionStore() if session_store is None + else session_store) + + def set_grant_type(self, grant_type='client_credentials', api_key=None, + api_secret=None, scope=None, info=None): """ Grant types: - token: - An authorization is requested to the end-user by redirecting it to an authorization page hosted - on Dailymotion. Once authorized, a refresh token is requested by the API client to the token - server and stored in the end-user's cookie (or other storage technique implemented by subclasses). - The refresh token is then used to request time limited access token to the token server. + An authorization is requested to the end-user by redirecting it to + an authorization page hosted on Dailymotion. Once authorized, a + refresh token is requested by the API client to the token server + and stored in the end-user's cookie (or other storage technique + implemented by subclasses). + The refresh token is then used to request time limited access token + to the token server. - none / client_credentials: - This grant type is a 2 legs authentication: it doesn't allow to act on behalf of another user. - With this grant type, all API requests will be performed with the user identity of the API key owner. + This grant type is a 2 legs authentication: it doesn't allow to act + on behalf of another user. + With this grant type, all API requests will be performed with the + user identity of the API key owner. - password: - This grant type allows to authenticate end-user by directly providing its credentials. - This profile is highly discouraged for web-server workflows. If used, the username and password - MUST NOT be stored by the client. + This grant type allows to authenticate end-user by directly + providing its credentials. + This profile is highly discouraged for web-server workflows. If + used, the username and password MUST NOT be stored by the client. """ self.access_token = None @@ -194,29 +218,36 @@ def set_grant_type(self, grant_type = 'client_credentials', api_key=None, api_se else: info = {} - if self._session_store_enabled and isinstance(info, dict) and info.get('username') is not None: + if (self._session_store_enabled and isinstance(info, dict) and + info.get('username') is not None): self._session_store.set_user(info.get('username')) if grant_type in ('authorization', 'token'): grant_type = 'authorization' if 'redirect_uri' not in info: - raise DailymotionClientError('Missing redirect_uri in grant info for token grant type.') + raise DailymotionClientError('Missing redirect_uri in grant ' + 'info for token grant type.') elif grant_type in ('client_credentials', 'none'): grant_type = 'client_credentials' elif grant_type == 'password': if 'username' not in info or 'password' not in info: - raise DailymotionClientError('Missing username or password in grant info for password grant type.') + raise DailymotionClientError('Missing username or password in ' + 'grant info for password grant ' + 'type.') self._grant_type = grant_type if scope: if not isinstance(scope, (list, tuple)): - raise DailymotionClientError('Invalid scope type: must be a list of valid scopes') + raise DailymotionClientError('Invalid scope type: must be a ' + 'list of valid scopes') self._grant_info['scope'] = scope - def get_authorization_url(self, redirect_uri=None, scope=None, display='page'): + def get_authorization_url(self, redirect_uri=None, scope=None, + display='page'): if self._grant_type != 'authorization': - raise DailymotionClientError('This method can only be used with TOKEN grant type.') + raise DailymotionClientError('This method can only be used with ' + 'TOKEN grant type.') qs = { 'response_type': 'code', @@ -225,30 +256,35 @@ def get_authorization_url(self, redirect_uri=None, scope=None, display='page'): 'display': display, } if scope and type(scope) in (list, tuple): - qs['scope'] = ' '.join(scope) + qs['scope'] = ' '.join(scope) return '%s?%s' % (self.oauth_authorize_endpoint_url, urlencode(qs)) def oauth_token_request(self, params): try: - result = self.request(self.oauth_token_endpoint_url, 'POST', params) + result = self.request(self.oauth_token_endpoint_url, 'POST', + params) except DailymotionApiError as e: raise DailymotionAuthError(str(e)) if 'error' in result: - raise DailymotionAuthError(result.get('error_description','')) + raise DailymotionAuthError(result.get('error_description', '')) if 'access_token' not in result: - raise DailymotionAuthError("Invalid token server response : ", str(result)) + raise DailymotionAuthError("Invalid token server response : ", + str(result)) result = { 'access_token': result['access_token'], - 'expires': int(time.time() + int(result['expires_in']) * 0.85), # refresh at 85% of expiration time for safety - 'refresh_token': result['refresh_token'] if 'refresh_token' in result else None, + # refresh at 85% of expiration time for safety + 'expires': int(time.time() + int(result['expires_in']) * 0.85), + 'refresh_token': (result['refresh_token'] + if 'refresh_token' in result + else None), 'scope': result['scope'] if 'scope' in result else [], } - if self._session_store_enabled and self._session_store != None: + if self._session_store_enabled and self._session_store is not None: self._session_store.set(result) return result @@ -266,7 +302,8 @@ def get_access_token(self, force_refresh=False, request_args=None): return access_token if self._session_store_enabled and access_token is not None: - if access_token and not force_refresh and time.time() < self._session_store.get_value('expires', 0): + if (access_token and not force_refresh and + time.time() < self._session_store.get_value('expires', 0)): return access_token refresh_token = self._session_store.get_value('refresh_token') @@ -276,7 +313,10 @@ def get_access_token(self, force_refresh=False, request_args=None): 'grant_type': 'refresh_token', 'client_id': self._grant_info['key'], 'client_secret': self._grant_info['secret'], - 'scope': ' '.join(self._grant_info['scope']) if 'scope' in self._grant_info and self._grant_info['scope'] else '', + 'scope': (' '.join(self._grant_info['scope']) + if 'scope' in self._grant_info and + self._grant_info['scope'] + else ''), 'refresh_token': refresh_token, } response = self.oauth_token_request(params) @@ -289,7 +329,10 @@ def get_access_token(self, force_refresh=False, request_args=None): 'client_id': self._grant_info['key'], 'client_secret': self._grant_info['secret'], 'redirect_uri': self._grant_info['redirect_uri'], - 'scope': ' '.join(self._grant_info['scope']) if 'scope' in self._grant_info and self._grant_info['scope'] else '', + 'scope': (' '.join(self._grant_info['scope']) + if 'scope' in self._grant_info and + self._grant_info['scope'] + else ''), 'code': request_args['code'], } @@ -305,7 +348,10 @@ def get_access_token(self, force_refresh=False, request_args=None): 'client_id': self._grant_info['key'], 'username': self._grant_info['username'], 'client_secret': self._grant_info['secret'], - 'scope': ' '.join(self._grant_info['scope']) if 'scope' in self._grant_info and self._grant_info['scope'] else '', + 'scope': (' '.join(self._grant_info['scope']) + if 'scope' in self._grant_info and + self._grant_info['scope'] + else ''), } if self._grant_type == 'password': params['password'] = self._grant_info['password'] @@ -320,7 +366,7 @@ def logout(self): def get(self, endpoint, params=None): return self.call(endpoint, params=params) - def post(self, endpoint, params=None, files=None): + def post(self, endpoint, params=None): return self.call(endpoint, method='POST', params=params) def delete(self, endpoint, params=None): @@ -339,9 +385,10 @@ def call(self, endpoint, method='GET', params=None, files=None): return self.request(endpoint, method, params, files) - def upload(self, file_path, progress=None): + def upload(self, file_path): if not os.path.exists(file_path): - raise IOError("[Errno 2] No such file or directory: '%s'" % file_path) + raise IOError("[Errno 2] No such file or directory: '%s'" % + file_path) if sys.version[0] == 2 and isinstance(file_path, unicode): file_path = file_path.encode('utf8') @@ -350,19 +397,23 @@ def upload(self, file_path, progress=None): result = self.get('/file/upload') - m = MultipartEncoder(fields={'file': (os.path.basename(file_path), open(file_path, 'rb'))}) + m = MultipartEncoder(fields={'file': (os.path.basename(file_path), + open(file_path, 'rb'))}) headers = { - 'User-Agent': 'Dailymotion-Python/%s (Python %s)' % (__version__, __python_version__), + 'User-Agent': 'Dailymotion-Python/%s (Python %s)' % + (__version__, __python_version__), 'Content-Type': m.content_type } - r = requests.post(result['upload_url'], data=m, headers=headers, timeout=self.timeout) + r = requests.post(result['upload_url'], data=m, headers=headers, + timeout=self.timeout) try: response = json.loads(r.text) - except ValueError as e: - raise DailymotionUploadInvalidResponse('Invalid API server response.\n%s' % response) + except ValueError: + raise DailymotionUploadInvalidResponse('Invalid API server ' + 'response.\n%s' % r.text) if 'error' in response: raise DailymotionUploadError(response['error']) @@ -375,18 +426,21 @@ def request(self, endpoint, method='GET', params=None, files=None): url = endpoint else: if endpoint.find('/') != 0: - raise DailymotionClientError('Endpoint must start with / (eg:/me/video)') + raise DailymotionClientError('Endpoint must start with / ' + '(eg:/me/video)') url = '%s%s' % (self.api_base_url, endpoint) method = method.lower() - if not method in ('get', 'post', 'delete'): - raise DailymotionClientError('Method must be of GET, POST or DELETE') + if method not in ('get', 'post', 'delete'): + raise DailymotionClientError('Method must be of GET, POST or ' + 'DELETE') func = getattr(requests, method) try: if method == 'get': - response = func(url, params=params, headers=self._headers, timeout=self.timeout) + response = func(url, params=params, headers=self._headers, + timeout=self.timeout) else: response = func(url, data=params, @@ -395,39 +449,46 @@ def request(self, endpoint, method='GET', params=None, files=None): timeout=self.timeout) except requests.exceptions.ConnectionError: - raise DailymotionClientError('Network problem (DNS failure, refused connection...).') + raise DailymotionClientError('Network problem (DNS failure, ' + 'refused connection...).') except requests.exceptions.HTTPError: raise DailymotionClientError('Invalid HTTP response') except requests.exceptions.Timeout: - raise DailymotionApiError('The request times out, current timeout is = %s' % self.timeout) + raise DailymotionApiError('The request times out, current timeout ' + 'is = %s' % self.timeout) except requests.exceptions.TooManyRedirects: - raise DailymotionApiError('The request exceeds the configured number of maximum redirections') + raise DailymotionApiError('The request exceeds the configured ' + 'number of maximum redirections') except requests.exceptions.RequestException: raise DailymotionClientError('An unknown error occurred.') try: - content = response.json if isinstance(response.json, dict) else response.json() + content = (response.json if isinstance(response.json, dict) + else response.json()) except ValueError: - raise DailymotionApiError('Unable to parse response, invalid JSON.') - - - if response.status_code != 200: - if content.get('error') is not None: - if response.status_code in (400, 401, 403): - authenticate_header = response.headers.get('www-authenticate') - if authenticate_header: - m = re.match('.*error="(.*?)"(?:, error_description="(.*?)")?', authenticate_header) - if m: - error = m.group(1) - msg = m.group(2) - if error == 'expired_token': - raise DailymotionTokenExpired(msg, error_type=error) - raise DailymotionAuthError(msg, error_type='auth_error') - - error = content['error'] - error_type = error.get('type', '') - error_message = error.get('message', '') - - raise DailymotionApiError(error_message, error_type=error_type) + raise DailymotionApiError('Unable to parse response, invalid ' + 'JSON.') + + if (response.status_code != 200 and + content.get('error') is not None): + if response.status_code in (400, 401, 403): + authenticate_header = response.headers.get('www-authenticate') + if authenticate_header: + m = re.match( + '.*error="(.*?)"(?:, error_description="(.*?)")?', + authenticate_header) + if m: + error = m.group(1) + msg = m.group(2) + if error == 'expired_token': + raise DailymotionTokenExpired(msg, + error_type=error) + raise DailymotionAuthError(msg, error_type='auth_error') + + error = content['error'] + error_type = error.get('type', '') + error_message = error.get('message', '') + + raise DailymotionApiError(error_message, error_type=error_type) return content diff --git a/setup.py b/setup.py index 0ee47f7..7c1d23c 100644 --- a/setup.py +++ b/setup.py @@ -1,11 +1,11 @@ -from setuptools import setup, find_packages -import os, sys +from setuptools import setup setup(name='dailymotion', version='0.2.2', description='Dailymotion API SDK', long_description='Dailymotion API SDK', - download_url='https://github.com/dailymotion/dailymotion-sdk-python/archive/0.2.2.tar.gz', + download_url=('https://github.com/dailymotion/dailymotion-sdk-python/' + 'archive/0.2.2.tar.gz'), classifiers=[ "Programming Language :: Python", "Development Status :: 5 - Production/Stable", @@ -22,9 +22,8 @@ license='Apache License, Version 2.0', include_package_data=True, zip_safe=False, - py_modules = ['dailymotion',], + py_modules=['dailymotion'], install_requires=[ 'requests', 'requests_toolbelt' - ], -) + ])