Skip to content

Commit 4287fc0

Browse files
committed
Merge pull request #3708 from mboersma/use-dict-views
More efficient iteration
2 parents 33bc75f + 034a77f commit 4287fc0

13 files changed

Lines changed: 34 additions & 33 deletions

File tree

client/deis.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,7 +1357,7 @@ def config_pull(self, args):
13571357
# write env_dict to .env
13581358
try:
13591359
with open('.env', 'w') as f:
1360-
for i in env_dict.keys():
1360+
for i in env_dict:
13611361
f.write("{}={}\n".format(i, env_dict[i]))
13621362
except IOError:
13631363
self._logger.error('could not write to local env')
@@ -1744,7 +1744,7 @@ def ps_list(self, args, app=None):
17441744
c_map = {}
17451745
for item in processes['results']:
17461746
c_map.setdefault(item['type'], []).append(item)
1747-
for c_type in c_map.keys():
1747+
for c_type in c_map:
17481748
self._logger.info("--- {c_type}: ".format(**locals()))
17491749
for c in c_map[c_type]:
17501750
self._logger.info("{type}.{num} {state} ({release})".format(**c))

controller/api/models.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def validate_id_is_docker_compatible(value):
8484
def validate_app_structure(value):
8585
"""Error if the dict values aren't ints >= 0."""
8686
try:
87-
if any(int(v) < 0 for v in value.itervalues()):
87+
if any(int(v) < 0 for v in value.viewvalues()):
8888
raise ValueError("Must be greater than or equal to zero")
8989
except ValueError, err:
9090
raise ValidationError(err)
@@ -230,7 +230,7 @@ def scale(self, user, structure): # noqa
230230
release = self.release_set.latest()
231231
# test for available process types
232232
available_process_types = release.build.procfile or {}
233-
for container_type in requested_structure.keys():
233+
for container_type in requested_structure:
234234
if container_type == 'cmd':
235235
continue # allow docker cmd types in case we don't have the image source
236236
if container_type not in available_process_types:
@@ -242,6 +242,7 @@ def scale(self, user, structure): # noqa
242242
# iterate and scale by container type (web, worker, etc)
243243
changed = False
244244
to_add, to_remove = [], []
245+
# iterate on a copy of the container_type keys
245246
for container_type in requested_structure.keys():
246247
containers = list(self.container_set.filter(type=container_type).order_by('created'))
247248
# increment new container nums off the most recent container
@@ -613,8 +614,8 @@ def save(self, **kwargs):
613614
try:
614615
previous_build = self.app.build_set.latest()
615616
to_destroy = []
616-
for proctype in previous_build.procfile.keys():
617-
if proctype not in self.procfile.keys():
617+
for proctype in previous_build.procfile:
618+
if proctype not in self.procfile:
618619
for c in self.app.container_set.filter(type=proctype):
619620
to_destroy.append(c)
620621
self.app._destroy_containers(to_destroy)
@@ -665,7 +666,7 @@ def save(self, **kwargs):
665666
new_data = {}
666667
data.update(new_data)
667668
# remove config keys if we provided a null value
668-
[data.pop(k) for k, v in new_data.items() if v is None]
669+
[data.pop(k) for k, v in new_data.viewitems() if v is None]
669670
setattr(self, attr, data)
670671
except Config.DoesNotExist:
671672
pass

controller/api/serializers.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ class Meta:
141141
model = models.Config
142142

143143
def validate_memory(self, value):
144-
for k, v in value.items():
144+
for k, v in value.viewitems():
145145
if v is None: # use NoneType to unset a value
146146
continue
147147
if not re.match(PROCTYPE_MATCH, k):
@@ -152,15 +152,15 @@ def validate_memory(self, value):
152152
return value
153153

154154
def validate_cpu(self, value):
155-
for k, v in value.items():
155+
for k, v in value.viewitems():
156156
if v is None: # use NoneType to unset a value
157157
continue
158158
if not re.match(PROCTYPE_MATCH, k):
159159
raise serializers.ValidationError("Process types can only contain [a-z]")
160160
shares = re.match(CPUSHARE_MATCH, str(v))
161161
if not shares:
162162
raise serializers.ValidationError("CPU shares must be an integer")
163-
for v in shares.groupdict().values():
163+
for v in shares.groupdict().viewvalues():
164164
try:
165165
i = int(v)
166166
except ValueError:
@@ -170,7 +170,7 @@ def validate_cpu(self, value):
170170
return value
171171

172172
def validate_tags(self, value):
173-
for k, v in value.items():
173+
for k, v in value.viewitems():
174174
if v is None: # use NoneType to unset a value
175175
continue
176176
if not re.match(TAGKEY_MATCH, k):

controller/api/tests/test_app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def test_response_data(self):
7272
response = self.client.post('/v1/apps', json.dumps(body),
7373
content_type='application/json',
7474
HTTP_AUTHORIZATION='token {}'.format(self.token))
75-
for key in response.data.keys():
75+
for key in response.data:
7676
self.assertIn(key, ['uuid', 'created', 'updated', 'id', 'owner', 'url', 'structure'])
7777
expected = {
7878
'id': 'test',

controller/api/tests/test_auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_auth(self):
4242
url = '/v1/auth/register'
4343
response = self.client.post(url, json.dumps(submit), content_type='application/json')
4444
self.assertEqual(response.status_code, 201)
45-
for key in response.data.keys():
45+
for key in response.data:
4646
self.assertIn(key, ['id', 'last_login', 'is_superuser', 'username', 'first_name',
4747
'last_name', 'email', 'is_active', 'is_superuser', 'is_staff',
4848
'date_joined', 'groups', 'user_permissions'])
@@ -122,7 +122,7 @@ def test_auth_registration_admin_only_works(self):
122122
HTTP_AUTHORIZATION='token {}'.format(token))
123123

124124
self.assertEqual(response.status_code, 201)
125-
for key in response.data.keys():
125+
for key in response.data:
126126
self.assertIn(key, ['id', 'last_login', 'is_superuser', 'username', 'first_name',
127127
'last_name', 'email', 'is_active', 'is_superuser', 'is_staff',
128128
'date_joined', 'groups', 'user_permissions'])

controller/api/tests/test_build.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def test_response_data(self):
9595
body = {'image': 'autotest/example'}
9696
response = self.client.post(url, json.dumps(body), content_type='application/json',
9797
HTTP_AUTHORIZATION='token {}'.format(self.token))
98-
for key in response.data.keys():
98+
for key in response.data:
9999
self.assertIn(key, ['uuid', 'owner', 'created', 'updated', 'app', 'dockerfile',
100100
'image', 'procfile', 'sha'])
101101
expected = {

controller/api/tests/test_config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def test_response_data(self):
119119
body = {'values': json.dumps({'PORT': '5000'})}
120120
response = self.client.post(url, json.dumps(body), content_type='application/json',
121121
HTTP_AUTHORIZATION='token {}'.format(self.token))
122-
for key in response.data.keys():
122+
for key in response.data:
123123
self.assertIn(key, ['uuid', 'owner', 'created', 'updated', 'app', 'values', 'memory',
124124
'cpu', 'tags'])
125125
expected = {

controller/api/tests/test_domain.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def test_response_data(self):
3939
response = self.client.post('/v1/apps/test/domains', json.dumps(body),
4040
content_type='application/json',
4141
HTTP_AUTHORIZATION='token {}'.format(self.token))
42-
for key in response.data.keys():
42+
for key in response.data:
4343
self.assertIn(key, ['uuid', 'owner', 'created', 'updated', 'app', 'domain'])
4444
expected = {
4545
'owner': self.user.username,

controller/api/tests/test_scheduler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def test_destroy_chaos(self):
232232
self.assertEqual(states, set(['error']))
233233
# make sure we can cleanup after enough tries
234234
containers = 20
235-
for _ in range(100):
235+
for _ in xrange(100):
236236
url = "/v1/apps/{app_id}/scale".format(**locals())
237237
body = {'web': 0}
238238
response = self.client.post(url, json.dumps(body), content_type='application/json',

controller/api/views.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def scale(self, request, **kwargs):
134134
new_structure = {}
135135
app = self.get_object()
136136
try:
137-
for target, count in request.data.items():
137+
for target, count in request.data.viewitems():
138138
new_structure[target] = int(count)
139139
models.validate_app_structure(new_structure)
140140
app.scale(request.user, new_structure)

0 commit comments

Comments
 (0)