Added direct_post and direct_get to api object. Useful for sending direct calls to post and get requests without using the path builder

This commit is contained in:
Manuel Cortez 2019-05-20 11:17:12 -05:00
parent c6b15c7f7b
commit 4c264da3e0
2 changed files with 25 additions and 3 deletions

View File

@ -40,16 +40,26 @@ class Session(object):
self.token = result["token"]
self.http.headers.update(Authorization="Bearer "+self.token)
def build_url(self, method):
""" build the URL that will be later passed to the request methods. """
if method.startswith("http:") or method.startswith("https:"):
return method
parts = ["instance_endpoint", "API_PREFIX", "API_VERSION"]
method = "".join([getattr(self, i) for i in parts if i not in method])+method
return method
def post(self, method, **params):
""" Helper for all post methods. This should not be used directly. """
response = self.http.post(self.instance_endpoint+self.API_PREFIX+self.API_VERSION+method, data=params)
url = self.build_url(method)
response = self.http.post(url, data=params)
if response.ok == False:
raise APIError("Error {error_code}: {text}".format(error_code=response.status_code, text=response.text))
return response.json()
def get(self, method, **params):
""" Helper for all GET methods. This should not be used directly. """
response = self.http.get(self.instance_endpoint+self.API_PREFIX+self.API_VERSION+method, params=params)
url = self.build_url(method)
response = self.http.get(url, params=params)
if response.ok == False:
raise APIError("Error {error_code}: {text}".format(error_code=response.status_code, text=response.text))
return response.json()
@ -93,4 +103,10 @@ class API(object):
# check if the method is valid.
if method.startswith(self._session.API_PREFIX) == False:
raise ValueError("the method passed seems to be an invalid URL.")
return self._session.instance_endpoint+method
return self._session.instance_endpoint+method
def direct_get(self, method, **kwargs):
return self._session.get(method, **kwargs)
def direct_post(self, method, **kwargs):
return self._session.post(method, **kwargs)

View File

@ -56,6 +56,12 @@ class testApi(unittest.TestCase):
track["listen_url"] = url
self.assertRaises(ValueError, api.full_url, track["listen_url"])
def test_full_urls_support(self):
""" Testing support for passing full URLS instead of having to build those by the API wrapper. """
api = self.session.get_api()
tracks = api.tracks.get(page_size=1)
url = tracks["next"]
next_tracks = api.direct_get(url)
if __name__ == "__main__":
unittest.main()