Skip to content

Commit fa43d08

Browse files
author
Maru Newby
committed
Clean up codebase in accordance with HACKING/PEP8.
* Adds HACKING.rst * Addresses 981208 Change-Id: I3d701ca9a748a0c4ceada7d76a31dc6bb2d5969b
1 parent 05c5a2b commit fa43d08

7 files changed

Lines changed: 539 additions & 251 deletions

File tree

HACKING.rst

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
QuantumClient Style Commandments
2+
================================
3+
4+
- Step 1: Read http://www.python.org/dev/peps/pep-0008/
5+
- Step 2: Read http://www.python.org/dev/peps/pep-0008/ again
6+
- Step 3: Read on
7+
8+
9+
General
10+
-------
11+
- Put two newlines between top-level code (funcs, classes, etc)
12+
- Put one newline between methods in classes and anywhere else
13+
- Do not write "except:", use "except Exception:" at the very least
14+
- Include your name with TODOs as in "#TODO(termie)"
15+
- Do not shadow a built-in or reserved word. Example::
16+
17+
def list():
18+
return [1, 2, 3]
19+
20+
mylist = list() # BAD, shadows `list` built-in
21+
22+
class Foo(object):
23+
def list(self):
24+
return [1, 2, 3]
25+
26+
mylist = Foo().list() # OKAY, does not shadow built-in
27+
28+
29+
Imports
30+
-------
31+
- Do not make relative imports
32+
- Order your imports by the full module path
33+
- Organize your imports according to the following template
34+
35+
Example::
36+
37+
# vim: tabstop=4 shiftwidth=4 softtabstop=4
38+
{{stdlib imports in human alphabetical order}}
39+
\n
40+
{{third-party lib imports in human alphabetical order}}
41+
\n
42+
{{quantum imports in human alphabetical order}}
43+
\n
44+
\n
45+
{{begin your code}}
46+
47+
48+
Human Alphabetical Order Examples
49+
---------------------------------
50+
Example::
51+
52+
import httplib
53+
import logging
54+
import random
55+
import StringIO
56+
import time
57+
import unittest
58+
59+
import eventlet
60+
import webob.exc
61+
62+
import quantum.api.networks
63+
from quantum.api import ports
64+
from quantum.db import models
65+
from quantum.extensions import multiport
66+
import quantum.manager
67+
from quantum import service
68+
69+
70+
Docstrings
71+
----------
72+
Example::
73+
74+
"""A one line docstring looks like this and ends in a period."""
75+
76+
77+
"""A multiline docstring has a one-line summary, less than 80 characters.
78+
79+
Then a new paragraph after a newline that explains in more detail any
80+
general information about the function, class or method. Example usages
81+
are also great to have here if it is a complex class for function.
82+
83+
When writing the docstring for a class, an extra line should be placed
84+
after the closing quotations. For more in-depth explanations for these
85+
decisions see http://www.python.org/dev/peps/pep-0257/
86+
87+
If you are going to describe parameters and return values, use Sphinx, the
88+
appropriate syntax is as follows.
89+
90+
:param foo: the foo parameter
91+
:param bar: the bar parameter
92+
:returns: return_type -- description of the return value
93+
:returns: description of the return value
94+
:raises: AttributeError, KeyError
95+
"""
96+
97+
98+
Dictionaries/Lists
99+
------------------
100+
If a dictionary (dict) or list object is longer than 80 characters, its items
101+
should be split with newlines. Embedded iterables should have their items
102+
indented. Additionally, the last item in the dictionary should have a trailing
103+
comma. This increases readability and simplifies future diffs.
104+
105+
Example::
106+
107+
my_dictionary = {
108+
"image": {
109+
"name": "Just a Snapshot",
110+
"size": 2749573,
111+
"properties": {
112+
"user_id": 12,
113+
"arch": "x86_64",
114+
},
115+
"things": [
116+
"thing_one",
117+
"thing_two",
118+
],
119+
"status": "ACTIVE",
120+
},
121+
}
122+
123+
124+
Calling Methods
125+
---------------
126+
Calls to methods 80 characters or longer should format each argument with
127+
newlines. This is not a requirement, but a guideline::
128+
129+
unnecessarily_long_function_name('string one',
130+
'string two',
131+
kwarg1=constants.ACTIVE,
132+
kwarg2=['a', 'b', 'c'])
133+
134+
135+
Rather than constructing parameters inline, it is better to break things up::
136+
137+
list_of_strings = [
138+
'what_a_long_string',
139+
'not as long',
140+
]
141+
142+
dict_of_numbers = {
143+
'one': 1,
144+
'two': 2,
145+
'twenty four': 24,
146+
}
147+
148+
object_one.call_a_method('string three',
149+
'string four',
150+
kwarg1=list_of_strings,
151+
kwarg2=dict_of_numbers)
152+
153+
154+
Internationalization (i18n) Strings
155+
-----------------------------------
156+
In order to support multiple languages, we have a mechanism to support
157+
automatic translations of exception and log strings.
158+
159+
Example::
160+
161+
msg = _("An error occurred")
162+
raise HTTPBadRequest(explanation=msg)
163+
164+
If you have a variable to place within the string, first internationalize the
165+
template string then do the replacement.
166+
167+
Example::
168+
169+
msg = _("Missing parameter: %s") % ("flavor",)
170+
LOG.error(msg)
171+
172+
If you have multiple variables to place in the string, use keyword parameters.
173+
This helps our translators reorder parameters when needed.
174+
175+
Example::
176+
177+
msg = _("The server with id %(s_id)s has no key %(m_key)s")
178+
LOG.error(msg % {"s_id": "1234", "m_key": "imageId"})
179+
180+
181+
Creating Unit Tests
182+
-------------------
183+
For every new feature, unit tests should be created that both test and
184+
(implicitly) document the usage of said feature. If submitting a patch for a
185+
bug that had no unit test, a new passing unit test should be added. If a
186+
submitted bug fix does have a unit test, be sure to add a new one that fails
187+
without the patch and passes with the patch.

quantumclient/__init__.py

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
# under the License.
1717
# @author: Tyler Smith, Cisco Systems
1818

19-
import logging
2019
import gettext
2120
import httplib
21+
import logging
2222
import socket
2323
import time
2424
import urllib
@@ -33,6 +33,8 @@
3333

3434

3535
LOG = logging.getLogger('quantumclient')
36+
37+
3638
AUTH_TOKEN_HEADER = "X-Auth-Token"
3739

3840

@@ -53,7 +55,7 @@ def exception_handler_v10(status_code, error_content):
5355
430: 'portNotFound',
5456
431: 'requestedStateInvalid',
5557
432: 'portInUse',
56-
440: 'alreadyAttached'
58+
440: 'alreadyAttached',
5759
}
5860

5961
quantum_errors = {
@@ -66,7 +68,7 @@ def exception_handler_v10(status_code, error_content):
6668
431: exceptions.StateInvalidClient,
6769
432: exceptions.PortInUseClient,
6870
440: exceptions.AlreadyAttachedClient,
69-
501: NotImplementedError
71+
501: NotImplementedError,
7072
}
7173

7274
# Find real error type
@@ -75,8 +77,7 @@ def exception_handler_v10(status_code, error_content):
7577
error_type = quantum_error_types.get(status_code)
7678
if error_type:
7779
error_dict = error_content[error_type]
78-
error_message = error_dict['message'] + "\n" +\
79-
error_dict['detail']
80+
error_message = error_dict['message'] + "\n" + error_dict['detail']
8081
else:
8182
error_message = error_content
8283
# raise the appropriate error!
@@ -128,7 +129,7 @@ def exception_handler_v11(status_code, error_content):
128129

129130
EXCEPTION_HANDLERS = {
130131
'1.0': exception_handler_v10,
131-
'1.1': exception_handler_v11
132+
'1.1': exception_handler_v11,
132133
}
133134

134135

@@ -166,9 +167,12 @@ class Client(object):
166167
"network": ["id", "name"],
167168
"port": ["id", "state"],
168169
"attachment": ["id"]},
169-
"plurals": {"networks": "network",
170-
"ports": "port"}},
171-
}
170+
"plurals": {
171+
"networks": "network",
172+
"ports": "port",
173+
},
174+
},
175+
}
172176

173177
# Action query strings
174178
networks_path = "/networks"
@@ -249,8 +253,8 @@ def _send_request(self, conn, method, action, body, headers):
249253
# Salvatore: Isolating this piece of code in its own method to
250254
# facilitate stubout for testing
251255
if self.logger:
252-
self.logger.debug("Quantum Client Request:\n" \
253-
+ method + " " + action + "\n")
256+
self.logger.debug("Quantum Client Request:\n"
257+
+ method + " " + action + "\n")
254258
if body:
255259
self.logger.debug(body)
256260
conn.request(method, action, body, headers)
@@ -286,7 +290,7 @@ def do_request(self, method, action, body=None,
286290
try:
287291
connection_type = self.get_connection_type()
288292
headers = headers or {"Content-Type":
289-
"application/%s" % self.format}
293+
"application/%s" % self.format}
290294
# if available, add authentication token
291295
if self.auth_token:
292296
headers[AUTH_TOKEN_HEADER] = self.auth_token
@@ -301,8 +305,8 @@ def do_request(self, method, action, body=None,
301305
status_code = self.get_status_code(res)
302306
data = res.read()
303307
if self.logger:
304-
self.logger.debug("Quantum Client Reply (code = %s) :\n %s" \
305-
% (str(status_code), data))
308+
self.logger.debug("Quantum Client Reply (code = %s) :\n %s" %
309+
(str(status_code), data))
306310
if status_code in (httplib.OK,
307311
httplib.CREATED,
308312
httplib.ACCEPTED,
@@ -335,17 +339,17 @@ def serialize(self, data):
335339
elif type(data) is dict:
336340
return Serializer().serialize(data, self.content_type())
337341
else:
338-
raise Exception("unable to serialize object of type = '%s'" \
339-
% type(data))
342+
raise Exception("unable to serialize object of type = '%s'" %
343+
type(data))
340344

341345
def deserialize(self, data, status_code):
342346
"""
343347
Deserializes a an xml or json string into a dictionary
344348
"""
345349
if status_code == 204:
346350
return data
347-
return Serializer(self._serialization_metadata).\
348-
deserialize(data, self.content_type())
351+
return Serializer(self._serialization_metadata).deserialize(
352+
data, self.content_type())
349353

350354
def content_type(self, format=None):
351355
"""

0 commit comments

Comments
 (0)