FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Added support for slash. Created "to_dict" property in response object and exception class. by mrlucascardoso · Pull Request #19 · sendgrid/python-http-client · GitHub

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
24 changes: 20 additions & 4 deletions python_http_client/client.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,22 @@ def headers(self):
"""
return self._headers

@property
def to_dict(self):
"""
:return: dict of response from the API
"""
return json.loads(self.body.decode('utf-8'))


class Client(object):
"""Quickly and easily access any REST or REST-like API."""
def __init__(self,
host,
request_headers=None,
version=None,
url_path=None):
url_path=None,
append_slash=False):
"""
:param host: Base URL for the api. (e.g. https://api.sendgrid.com)
:type host: string
Expand All @@ -76,6 +84,8 @@ def __init__(self,
self._url_path = url_path or []
# These are the supported HTTP verbs
self.methods = ['delete', 'get', 'patch', 'post', 'put']
# APPEND SLASH set
self.append_slash = append_slash

def _build_versioned_url(self, url):
"""Subclass this function for your own needs.
Expand All @@ -99,6 +109,11 @@ def _build_url(self, query_params):
while count < len(self._url_path):
url += '/{0}'.format(self._url_path[count])
count += 1

# add slash
if self.append_slash:
url += '/'

if query_params:
url_values = urlencode(sorted(query_params.items()), True)
url = '{0}?{1}'.format(url, url_values)
Expand All @@ -121,11 +136,12 @@ def _build_client(self, name=None):
:type name: string
:return: A Client object
"""
url_path = self._url_path+[name] if name else self._url_path
url_path = self._url_path + [name] if name else self._url_path
return Client(host=self.host,
version=self._version,
request_headers=self.request_headers,
url_path=url_path)
url_path=url_path,
append_slash=self.append_slash)

def _make_request(self, opener, request):
"""Make the API call and return the response. This is separated into
Expand Down Expand Up @@ -188,7 +204,7 @@ def http_request(*_, **kwargs):
"""
if 'request_headers' in kwargs:
self._update_headers(kwargs['request_headers'])
if not 'request_body' in kwargs:
if 'request_body' not in kwargs:
data = None
else:
# Don't serialize to a JSON formatted str if we don't have a JSON Content-Type
Expand Down
48 changes: 36 additions & 12 deletions python_http_client/exceptions.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import json


class HTTPError(Exception):
''' Base of all other errors'''
def __init__(self, error):
Expand All @@ -6,55 +9,76 @@ def __init__(self, error):
self.body = error.read()
self.headers = error.hdrs

@property
def to_dict(self):
"""
:return: dict of response erro from the API
"""
return json.loads(self.body.decode('utf-8'))


class BadRequestsError(HTTPError):
pass


class UnauthorizedError(HTTPError):
pass


class ForbiddenError(HTTPError):
pass


class NotFoundError(HTTPError):
pass


class MethodNotAllowedError(HTTPError):
pass


class PayloadTooLargeError(HTTPError):
pass


class UnsupportedMediaTypeError(HTTPError):
pass


class TooManyRequestsError(HTTPError):
pass


class InternalServerError(HTTPError):
pass


class ServiceUnavailableError(HTTPError):
pass


class GatewayTimeoutError(HTTPError):
pass

err_dict = { 400 : BadRequestsError,
401 : UnauthorizedError,
403 : ForbiddenError,
404 : NotFoundError,
405 : MethodNotAllowedError,
413 : PayloadTooLargeError,
415 : UnsupportedMediaTypeError,
429 : TooManyRequestsError,
500 : InternalServerError,
503 : ServiceUnavailableError,
504 : GatewayTimeoutError

err_dict = {
400: BadRequestsError,
401: UnauthorizedError,
403: ForbiddenError,
404: NotFoundError,
405: MethodNotAllowedError,
413: PayloadTooLargeError,
415: UnsupportedMediaTypeError,
429: TooManyRequestsError,
500: InternalServerError,
503: ServiceUnavailableError,
504: GatewayTimeoutError
}


def handle_error(error):
try:
exc = err_dict[error.code](error)
except KeyError as e:
except KeyError:
return HTTPError(error)
return exc

Back | FazBrowse Home | New Git URL