8000 Bring code up to PEP8 compliance · ftobia/twilio-python@7cc88e4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7cc88e4

Browse files
committed
Bring code up to PEP8 compliance
1 parent 9a445a0 commit 7cc88e4

19 files changed

+69
-53
lines changed

.travis.yml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,8 @@ python:
77
install:
88
- pip install . --use-mirrors
99
- pip install -r requirements.txt --use-mirrors
10-
script: nosetests
10+
- pip install -r tests/requirements.txt --use-mirrors
11+
script:
12+
- flake8 --ignore=F401 twilio
13+
- flake8 --ignore=E501 tests
14+
- nosetests

tests/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ unittest2
66
coverage
77
nosexcover
88
six
9+
flake8

tests/test_conferences.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,3 @@ def test_list_before(self):
4646
self.resource.list(created_before=date(2011, 1, 1))
4747
self.params["DateCreated<"] = "2011-01-01"
4848
self.resource.get_instances.assert_called_with(self.params)
49-
50-
51-

tests/test_twiml.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -174,13 +174,6 @@ def testRecordTranscribeCallback(self):
174174
r = self.strip(r)
175175
self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Record transcribeCallback="example.com" /></Response>')
176176

177-
def testRecordMaxlengthFinishTimeout(self):
178-
"""should record with an maxlength, finishonkey, and timeout"""
179-
r = Response()
180-
r.addRecord(timeout=4,finishOnKey="#", maxLength=30)
181-
r = self.strip(r)
182-
self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Record finishOnKey="#" maxLength="30" timeout="4" /></Response>')
183-
184177
def testRecordAddAttribute(self):
185178
"""add attribute"""
186179
r = twiml.Record(foo="bar")

twilio/jwt/__init__.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import hashlib
88
import hmac
99
from six import text_type, b
10+
11+
1012
# default text to binary representation conversion
1113
def binary(txt):
1214
return txt.encode('utf-8')
@@ -15,52 +17,62 @@ def binary(txt):
1517
import json
1618
except ImportError:
1719
import simplejson as json
18-
20+
21+
1922
__all__ = ['encode', 'decode', 'DecodeError']
2023

21-
class DecodeError(Exception): pass
24+
25+
class DecodeError(Exception):
26+
pass
2227

2328
signing_methods = {
2429
'HS256': lambda msg, key: hmac.new(key, msg, hashlib.sha256).digest(),
2530
'HS384': lambda msg, key: hmac.new(key, msg, hashlib.sha384).digest(),
2631
'HS512': lambda msg, key: hmac.new(key, msg, hashlib.sha512).digest(),
2732
}
2833

34+
2935
def base64url_decode(input):
3036
input += b('=') * (4 - (len(input) % 4))
3137
return base64.urlsafe_b64decode(input)
3238

39+
3340
def base64url_encode(input):
3441
return base64.urlsafe_b64encode(input).decode('utf-8').replace('=', '')
3542

43+
3644
def encode(payload, key, algorithm='HS256'):
3745
segments = []
3846
header = {"typ": "JWT", "alg": algorithm}
3947
segments.append(base64url_encode(binary(json.dumps(header))))
4048
segments.append(base64url_encode(binary(json.dumps(payload))))
41-
signing_input = '.'.join(segments)
49+
sign_input = '.'.join(segments)
4250
try:
43-
signature = signing_methods[algorithm](binary(signing_input), binary(key))
51+
signature = signing_methods[algorithm](binary(sign_input), binary(key))
4452
except KeyError:
4553
raise NotImplementedError("Algorithm not supported")
4654
segments.append(base64url_encode(signature))
4755
return '.'.join(segments)
4856

57+
4958
def decode(jwt, key='', verify=True):
5059
try:
5160
signing_input, crypto_segment = jwt.rsplit('.', 1)
5261
header_segment, payload_segment = signing_input.split('.', 1)
5362
except ValueError:
5463
raise DecodeError("Not enough segments")
5564
try:
56-
header = json.loads(base64url_decode(binary(header_segment)).decode('utf-8'))
57-
payload = json.loads(base64url_decode(binary(payload_segment)).decode('utf-8'))
65+
header_raw = base64url_decode(binary(header_segment)).decode('utf-8')
66+
payload_raw = base64url_decode(binary(payload_segment)).decode('utf-8')
67+
header = json.loads(header_raw)
68+
payload = json.loads(payload_raw)
5869
signature = base64url_decode(binary(crypto_segment))
5970
except (ValueError, TypeError):
6071
raise DecodeError("Invalid segment encoding")
6172
if verify:
6273
try:
63-
if not signature == signing_methods[header['alg']](binary(signing_input), binary(key)):
74+
method = signing_methods[header['alg']]
75+
if not signature == method(binary(signing_input), binary(key)):
6476
raise DecodeError("Signature verification failed")
6577
except KeyError:
6678
raise DecodeError("Algorithm not supported")

twilio/rest/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def request(self, path, method=None, vars=None):
7777

7878
headers = {
7979
"User-Agent": "twilio-python",
80-
}
80+
}
8181

8282
resp = make_request(method, uri, auth=self.auth, data=data,
8383
params=params, headers=headers)

twilio/rest/resources/accounts.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class Account(InstanceResource):
3333
ConnectApps,
3434
Queues,
3535
AuthorizedConnectApps,
36-
]
36+
]
3737

3838
def update(self, **kwargs):
3939
"""

twilio/rest/resources/base.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ def __init__(self, httplib_resp, content, url):
2121
self.url = url
2222

2323

24-
def make_request(method, url,
25-
params=None, data=None, headers=None, cookies=None, files=None,
26-
auth=None, timeout=None, allow_redirects=False, proxies=None):
24+
def make_request(method, url, params=None, data=None, headers=None,
25+
cookies=None, files=None, auth=None, timeout=None,
26+
allow_redirects=False, proxies=None):
2727
"""Sends an HTTP request Returns :class:`Response <models.Response>`
2828
2929
See the requests documentation for explanation of all these parameters
@@ -107,7 +107,7 @@ def __eq__(self, other):
107107
and self.__dict__ == other.__dict__)
108108

109109
def __hash__(self):
110-
return hash(frozenset(self.__dict__))
110+
return hash(frozenset(self.__dict__))
111111

112112
def __ne__(self, other):
113113
return not self.__eq__(other)
@@ -141,8 +141,7 @@ class InstanceResource(Resource):
141141
def __init__(self, parent, sid):
142142
self.parent = parent
143143
self.name = sid
144-
super(InstanceResource, self).__init__(parent.uri,
145-
parent.auth)
144+
super(InstanceResource, self).__init__(parent.uri, parent.auth)
146145

147146
def load(self, entries):
148147
if "from" in entries.keys():

twilio/rest/resources/calls.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,15 +85,16 @@ def create(self, to, from_, url, status_method=None, **kwargs):
8585
occurs requesting or executing the TwiML at url
8686
:param string fallback_method: The HTTP method that Twilio should use
8787
to request the fallback_url
88-
:type fallback_method: None (will make 'POST' request), 'GET', or 'POST'
88+
:type fallback_method: None (will make 'POST' request),
89+
'GET', or 'POST'
8990
:param string status_callback: A URL that Twilio will request when the
9091
call ends to notify your app.
9192
:param string status_method: The HTTP method Twilio should use when
9293
requesting the above URL.
9394
:param string if_machine: Tell Twilio to try and determine if a machine
9495
(like voicemail) or a human has answered the call.
9596
See more in our `answering machine documentation
96-
<http://www.twilio.com/docs/api/rest/making_calls#handling-outcomes-answering-machines">`_.
97+
<http://www.twilio.com/docs/api/rest/making_calls>`_.
9798
:type if_machine: None, 'Continue', or 'Hangup'
9899
:param string send_digits: A string of keys to dial after
99100
connecting to the number.

twilio/rest/resources/conferences.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ class Conference(InstanceResource):
7676

7777
subresources = [
7878
Participants
79-
]
79+
]
8080

8181

8282
class Conferences(ListResource):

twilio/rest/resources/connect_apps.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from twilio.rest.resources import InstanceResource, ListResource
22
from six import iteritems
33

4+
45
class ConnectApp(InstanceResource):
56
""" An authorized connect app """
67
pass

twilio/rest/resources/imports.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,3 @@
1515

1616
# httplib2
1717
import httplib2
18-
19-

twilio/rest/resources/phone_numbers.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def load(self, entries):
6464
if "account_sid" in entries:
6565
# Parse the parent's uri to get the scheme and base
6666
uri = re.sub(r'AC(.*)', entries["account_sid"],
67-
self.parent.base_uri)
67+
self.parent.base_uri)
6868

6969
self.parent = PhoneNumbers(uri, self.parent.auth)
7070
self.base_uri = self.parent.uri
@@ -84,7 +84,8 @@ def update(self, **kwargs):
8484
Update this phone number instance.
8585
"""
8686
kwargs_copy = dict(kwargs)
87-
change_dict_key(kwargs_copy, from_key="status_callback_url", to_key="status_callback")
87+
change_dict_key(kwargs_copy, from_key="status_callback_url",
88+
to_key="status_callback")
8889

8990
a = self.parent.update(self.name, **kwargs_copy)
9091
self.load(a.__dict__)
@@ -171,7 +172,8 @@ def update(self, sid, **kwargs):
171172
Update this phone number instance
172173
"""
173174
kwargs_copy = dict(kwargs)
174-
change_dict_key(kwargs_copy, from_key="status_callback_url", to_key="status_callback")
175+
change_dict_key(kwargs_copy, from_key=&quo 10000 t;status_callback_url",
176+
to_key="status_callback")
175177

176178
if "application_sid" in kwargs_copy:
177179
for sid_type in ["voice_application_sid", "sms_application_sid"]:

twilio/rest/resources/queues.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ class Queues(ListResource):
6161

6262
def list(self, **kwargs):
6363
"""
64-
Returns a page of :class:`Queue` resources as a list sorted by DateUpdated.
65-
For paging informtion see :class:`ListResource`
64+
Returns a page of :class:`Queue` resources as a list sorted
65+
by DateUpdated. For paging informtion see :class:`ListResource`
6666
"""
6767
return self.get_instances(kwargs)
6868

twilio/rest/resources/recordings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def __init__(self, *args, **kwargs):
2828
self.formats = {
2929
"mp3": self.uri + ".mp3",
3030
"wav": self.uri + ".wav",
31-
}
31+
}
3232

3333
def delete(self):
3434
"""

twilio/rest/resources/usage.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from twilio.rest.resources import InstanceResource, ListResource
22

3+
34
class UsageTrigger(InstanceResource):
45
""" A usage trigger resource """
56

@@ -63,12 +64,10 @@ def create(self, **kwargs):
6364
"""
6465
return self.create_instance(kwargs)
6566

66-
6767
def update(self, sid, **kwargs):
6868
""" Update the UsageTrigger with the given sid to have the kwargs """
6969
return self.update_instance(sid, kwargs)
7070

71-
7271
def delete(self, sid):
7372
"""
7473
Delete a :class:`UsageTrigger`
@@ -88,6 +87,7 @@ def load(self, entries):
8887
def uri(self):
8988
return self.__dict__.get('uri')
9089

90+
9191
class BaseUsageRecords(ListResource):
9292
name = "Usage/Records"
9393
instance = UsageRecord
@@ -118,6 +118,7 @@ def load_instance(self, data):
118118

119119

120120
class UsageRecords(BaseUsageRecords):
121+
121122
def __init__(self, base_uri, auth):
122123
super(UsageRecords, self).__init__(base_uri, auth)
123124
self.daily = UsageRecordsDaily(base_uri, auth)
@@ -166,6 +167,7 @@ class UsageRecordsLastMonth(BaseUsageRecords):
166167
UsageRecordsLastMonth
167168
]
168169

170+
169171
class Usage(object):
170172
"&qu 4380 ot;"
171173
Holds all the specific Usage list resources

twilio/rest/resources/util.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from six import iteritems
33

44

5-
def transform_params(p):
5+
def transform_params(parameters):
66
"""
77
Transform parameters, throwing away any None values
88
and convert False and True values to strings
@@ -13,10 +13,13 @@ def transform_params(p):
1313
becomes:
1414
{"Record": "true", "DateCreated": "2012-01-02"}
1515
"""
16-
p = [(format_name(d), convert_boolean(p[d])) for d in p
17-
if p[d] is not None
18-
]
19-
return dict(p)
16+
transformed_parameters = {}
17+
18+
for key, value in iteritems(parameters):
19+
if value is not None:
20+
transformed_parameters[format_name(key)] = convert_boolean(value)
21+
22+
return transformed_parameters
2023

2124

2225
def format_name(word):
@@ -61,12 +64,12 @@ def convert_keys(d):
6164
"""
6265
special = {
6366
"started_before": "StartTime<",
64-
"started_after": "StartTime>",
65-
"started": "StartTime",
66-
"ended_before": "EndTime<",
67-
"ended_after": "EndTime>",
68-
"ended": "EndTime",
69-
"from_": "From",
67+
"started_after": "StartTime>",
68+
"started": "StartTime",
69+
"ended_before": "EndTime<",
70+
"ended_after": "EndTime>",
71+
"ended": "EndTime",
72+
"from_": "From",
7073
}
7174

7275
result = {}
@@ -91,9 +94,11 @@ def inner_func(*args, **kwargs):
9194
inner_func.__repr__ = myfunc.__repr__
9295
return inner_func
9396

97+
9498
def change_dict_key(d, from_key, to_key):
9599
"""
96-
Changes a dictionary's key from from_key to to_key. No-op if the key does not exist.
100+
Changes a dictionary's key from from_key to to_key.
101+
No-op if the key does not exist.
97102
98103
:param d: Dictionary with key to change
99104
:param from_key: Old key

twilio/twiml.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def xml(self):
8484
def append(self, verb):
8585
if not self.nestables or verb.name not in self.nestables:
8686
raise TwimlException("%s is not nestable inside %s" %
87-
(verb.name, self.name))
87+
(verb.name, self.name))
8888
self.verbs.append(verb)
8989
return verb
9090

@@ -104,7 +104,7 @@ class Response(Verb):
104104
'Sms',
105105
'Enqueue',
106106
'Leave'
107-
]
107+
]
108108

109109
def __init__(self, **kwargs):
110110
"""Version: Twilio API version e.g. 2008-08-01 """

twilio/util.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from twilio import jwt
77
from twilio.compat import urlencode
88

9+
910
class RequestValidator(object):
1011

1112
def __init__(self, token):

0 commit comments

Comments
 (0)
0