Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added proxy support to client. Added example-file for proxy usage. #88

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
47 changes: 47 additions & 0 deletions examples/message_create_proxy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env python

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

import messagebird

ACCESS_KEY = 'test_gshuPaZoeEG6ovbc8M79w0QyM'

proxies = {
'http': 'http://my.example.proxy:8765',
'https': 'http://my.secure.example.proxy:9876'
}

try:
# Create a MessageBird client with the specified ACCESS_KEY.
client = messagebird.Client(ACCESS_KEY, proxies=proxies)

# Send a new message.
msg = client.message_create('FromMe', '31612345678', 'Hello World', { 'reference' : 'Foobar' })

# Print the object information.
print('\nThe following information was returned as a Message object:\n')
print(' id : %s' % msg.id)
print(' href : %s' % msg.href)
print(' direction : %s' % msg.direction)
print(' type : %s' % msg.type)
print(' originator : %s' % msg.originator)
print(' body : %s' % msg.body)
print(' reference : %s' % msg.reference)
print(' validity : %s' % msg.validity)
print(' gateway : %s' % msg.gateway)
print(' typeDetails : %s' % msg.typeDetails)
print(' datacoding : %s' % msg.datacoding)
print(' mclass : %s' % msg.mclass)
print(' scheduledDatetime : %s' % msg.scheduledDatetime)
print(' createdDatetime : %s' % msg.createdDatetime)
print(' recipients : %s\n' % msg.recipients)
print()

except messagebird.client.ErrorException as e:
print('\nAn error occured while requesting a Message object:\n')

for error in e.errors:
print(' code : %d' % error.code)
print(' description : %s' % error.description)
print(' parameter : %s\n' % error.parameter)
21 changes: 15 additions & 6 deletions messagebird/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,24 +63,33 @@ def __init__(self, errorMessage):


class Client(object):
def __init__(self, access_key, http_client=None):
def __init__(self, access_key, http_client=None, **kwargs):
self.access_key = access_key
self.http_client = http_client

if 'http_client' in kwargs:
self.http_client = kwargs['http_client']
else:
self.http_client = http_client

if 'proxies' in kwargs:
self.proxies = kwargs['proxies']
else:
self.proxies = {}

def _get_http_client(self, type=REST_TYPE):
if self.http_client:
return self.http_client

if type == CONVERSATION_TYPE:
return HttpClient(CONVERSATION_API_ROOT, self.access_key, USER_AGENT)
return HttpClient(CONVERSATION_API_ROOT, self.access_key, USER_AGENT, proxies=self.proxies)

if type == VOICE_TYPE:
return HttpClient(VOICE_API_ROOT, self.access_key, USER_AGENT)
return HttpClient(VOICE_API_ROOT, self.access_key, USER_AGENT, proxies=self.proxies)

if type == NUMBER_TYPE:
return HttpClient(NUMBER_API_ROOT, self.access_key, USER_AGENT)
return HttpClient(NUMBER_API_ROOT, self.access_key, USER_AGENT, proxies=self.proxies)

return HttpClient(ENDPOINT, self.access_key, USER_AGENT)
return HttpClient(ENDPOINT, self.access_key, USER_AGENT, proxies=self.proxies)

def request(self, path, method='GET', params=None, type=REST_TYPE):
"""Builds a request, gets a response and decodes it."""
Expand Down
21 changes: 15 additions & 6 deletions messagebird/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,27 @@ class ResponseFormat(Enum):
class HttpClient:
"""Used for sending simple HTTP requests."""

def __init__(self, endpoint, access_key, user_agent):
def __init__(self, endpoint, access_key, user_agent, **kwargs):
self.__supported_status_codes = [200, 201, 204, 401, 404, 405, 422]

self.endpoint = endpoint
self.access_key = access_key
self.user_agent = user_agent

if 'proxies' in kwargs:
self.proxies = kwargs['proxies']
else:
self.proxies = {}

def request(self, path, method='GET', params=None, format=ResponseFormat.text):
"""Builds a request and gets a response."""
if params is None:
params = {}
url = urljoin(self.endpoint, path)

if self.proxies is not dict:
self.proxies = {}

headers = {
'Accept': 'application/json',
'Authorization': 'AccessKey ' + self.access_key,
Expand All @@ -34,11 +43,11 @@ def request(self, path, method='GET', params=None, format=ResponseFormat.text):
}

method_switcher = {
'DELETE': lambda: requests.delete(url, verify=True, headers=headers, data=json_serialize(params)),
'GET': lambda: requests.get(url, verify=True, headers=headers, params=params),
'PATCH': lambda: requests.patch(url, verify=True, headers=headers, data=json_serialize(params)),
'POST': lambda: requests.post(url, verify=True, headers=headers, data=json_serialize(params)),
'PUT': lambda: requests.put(url, verify=True, headers=headers, data=json_serialize(params))
'DELETE': lambda: requests.delete(url, verify=True, proxies=self.proxies, headers=headers, data=json_serialize(params)),
'GET': lambda: requests.get(url, verify=True, proxies=self.proxies, headers=headers, params=params),
'PATCH': lambda: requests.patch(url, verify=True, proxies=self.proxies, headers=headers, data=json_serialize(params)),
'POST': lambda: requests.post(url, verify=True, proxies=self.proxies, headers=headers, data=json_serialize(params)),
'PUT': lambda: requests.put(url, verify=True, proxies=self.proxies, headers=headers, data=json_serialize(params))
}
if method not in method_switcher:
raise ValueError(str(method) + ' is not a supported HTTP method')
Expand Down