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

feat: add regional and edge support #520

Merged
merged 8 commits into from
May 12, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ token = "YYYYYYYYYYYYYYYYYY"
client = Client(account, token)
```

Alternately, a `Client` constructor without these parameters will
Alternatively, a `Client` constructor without these parameters will
look for `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` variables inside the
current environment.

Expand All @@ -82,6 +82,28 @@ from twilio.rest import Client
client = Client()
```

### Specify Region and/or Edge

```python
from twilio.rest import Client

client = Client(region='au1', edge='sydney')
```
A `Client` constructor without these parameters will also look for `TWILIO_REGION` and `TWILIO_EDGE` variables inside the current environment.

Alternatively, you may specify the edge and/or region after constructing the Twilio client:

```python
from twilio.rest import Client

client = Client()
client.region = 'au1'
client.edge = 'sydney'
```


This will result in the `hostname` transforming from `api.twilio.com` to `api.sydney.au1.twilio.com`.

### Make a Call

```python
Expand Down
53 changes: 53 additions & 0 deletions tests/unit/rest/test_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import unittest

from twilio.rest import (
Client,
TwilioClient,
TwilioRestClient,
TwilioIpMessagingClient,
Expand Down Expand Up @@ -44,3 +46,54 @@ def test_obsolete_exception_twiliotaskrouterclient(self):
def test_obsolete_exception_twiliotrunkingclient(self):
self.assertRaises(ObsoleteException, TwilioTrunkingClient,
"Expected raised ObsoleteException")


class TestRegionEdgeClients(unittest.TestCase):
def setUp(self):
self.client = Client('username', 'password')

def test_set_client_edge_default_region(self):
self.client.edge = 'edge'
self.assertEqual(self.client.get_hostname('https://api.twilio.com'),
'https://api.edge.us1.twilio.com')

def test_set_client_region(self):
self.client.region = 'region'
self.assertEqual(self.client.get_hostname('https://api.twilio.com'),
'https://api.region.twilio.com')

def test_set_uri_region(self):
self.assertEqual(self.client.get_hostname('https://api.region.twilio.com'),
'https://api.region.twilio.com')

def test_set_client_edge_region(self):
self.client.edge = 'edge'
self.client.region = 'region'
self.assertEqual(self.client.get_hostname('https://api.twilio.com'),
'https://api.edge.region.twilio.com')

def test_set_client_edge_uri_region(self):
self.client.edge = 'edge'
self.assertEqual(self.client.get_hostname('https://api.region.twilio.com'),
'https://api.edge.region.twilio.com')

def test_set_client_region_uri_edge_region(self):
self.client.region = 'region'
self.assertEqual(self.client.get_hostname('https://api.edge.uriRegion.twilio.com'),
'https://api.edge.region.twilio.com')

def test_set_client_edge_uri_edge_region(self):
self.client.edge = 'edge'
self.assertEqual(self.client.get_hostname('https://api.uriEdge.region.twilio.com'),
'https://api.edge.region.twilio.com')

def test_set_uri_edge_region(self):
self.assertEqual(self.client.get_hostname('https://api.edge.region.twilio.com'),
'https://api.edge.region.twilio.com')

def test_periods_in_query(self):
self.client.region = 'region'
self.client.edge = 'edge'
self.assertEqual(self.client.get_hostname('https://api.twilio.com/path/to/something.json?foo=12.34'),
'https://api.edge.region.twilio.com/path/to/something.json?foo=12.34')

52 changes: 44 additions & 8 deletions twilio/rest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,28 @@
from twilio import __version__
from twilio.base.exceptions import TwilioException
from twilio.base.obsolete import obsolete_client
from twilio.compat import (
urlparse,
urlunparse,
)
from twilio.http.http_client import TwilioHttpClient


class Client(object):
""" A client for accessing the Twilio API. """

def __init__(self, username=None, password=None, account_sid=None, region=None,
http_client=None, environment=None):
http_client=None, environment=None, edge=None):
"""
Initializes the Twilio Client

:param str username: Username to authenticate with
:param str password: Password to authenticate with
:param str account_sid: Account Sid, defaults to Username
:param str region: Twilio Region to make requests to
:param str region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided
:param HttpClient http_client: HttpClient, defaults to TwilioHttpClient
:param dict environment: Environment to look for auth details, defaults to os.environ
:param str edge: Twilio Edge to make requests to, defaults to None

:returns: Twilio Client
:rtype: twilio.rest.Client
Expand All @@ -40,7 +45,9 @@ def __init__(self, username=None, password=None, account_sid=None, region=None,
""" :type : str """
self.account_sid = account_sid or self.username
""" :type : str """
self.region = region
self.edge = edge or environment.get('TWILIO_EDGE')
""" :type : str """
self.region = region or environment.get('TWILIO_REGION')
""" :type : str """

if not self.username or not self.password:
Expand Down Expand Up @@ -116,11 +123,8 @@ def request(self, method, uri, params=None, data=None, headers=None, auth=None,
if 'Accept' not in headers:
headers['Accept'] = 'application/json'

if self.region:
head, tail = uri.split('.', 1)

if not tail.startswith(self.region):
uri = '.'.join([head, self.region, tail])
if self.region or self.edge:
uri = self.get_hostname(uri)

return self.http_client.request(
method,
Expand All @@ -133,6 +137,38 @@ def request(self, method, uri, params=None, data=None, headers=None, auth=None,
allow_redirects=allow_redirects
)

def get_hostname(self, uri):
"""
Determines the proper hostname given edge and region preferences
via client configuration or uri.

:param str uri: Fully qualified url

:returns: The final uri used to make the request
:rtype: str
"""
parsed_url = urlparse(uri)
eshanholtz marked this conversation as resolved.
Show resolved Hide resolved
pieces = parsed_url.netloc.split('.')
prefix = pieces[0]
suffix = '.'.join(pieces[-2:])
region = None
edge = None
if len(pieces) == 4:
# https://product.region.twilio.com
eshanholtz marked this conversation as resolved.
Show resolved Hide resolved
region = pieces[1]
elif len(pieces) == 5:
# https://product.edge.region.twilio.com
edge = pieces[1]
region = pieces[2]

edge = self.edge or edge
region = self.region or region or (edge and 'us1')

parsed_url = parsed_url._replace(
netloc='.'.join([part for part in [prefix, edge, region, suffix] if part])
)
return urlunparse(parsed_url)

@property
def accounts(self):
"""
Expand Down