Extracted HTTP response codes to constants

There are several places in the source code where HTTP response
codes are used as numeric values.

Status codes 200, 202, 204, 300, 400, 401, 403, 404, 405, 409, 413,
415, 500, 501, 503 under api/v1 and api/v2 are replaced with symbolic
constants from six.moves.http_client thus improves code readability.
More patches will be submitted to address other status codes.

Partial-Bug: #1520159
Change-Id: I7c61122a6b043d7d238bea95ef39d8fa97817df4
This commit is contained in:
poojajadhav 2017-01-04 15:59:44 +05:30
parent 35738c47ab
commit 92980e4972
10 changed files with 34 additions and 24 deletions

View File

@ -24,6 +24,7 @@ from oslo_config import cfg
from oslo_log import log as logging from oslo_log import log as logging
from oslo_middleware import request_id from oslo_middleware import request_id
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from six.moves import http_client
import webob.dec import webob.dec
import webob.exc import webob.exc
@ -129,7 +130,7 @@ class NoAuthMiddleware(base_wsgi.Middleware):
res.headers['X-Auth-Token'] = '%s:%s' % (user_id, project_id) res.headers['X-Auth-Token'] = '%s:%s' % (user_id, project_id)
res.headers['X-Server-Management-Url'] = os_url res.headers['X-Server-Management-Url'] = os_url
res.content_type = 'text/plain' res.content_type = 'text/plain'
res.status = '204' res.status_int = http_client.NO_CONTENT
return res return res
token = req.headers['X-Auth-Token'] token = req.headers['X-Auth-Token']

View File

@ -16,6 +16,7 @@
from oslo_log import log as logging from oslo_log import log as logging
import six import six
from six.moves import http_client
import webob.dec import webob.dec
import webob.exc import webob.exc
@ -49,9 +50,9 @@ class FaultWrapper(base_wsgi.Middleware):
'error': inner}) 'error': inner})
safe = getattr(inner, 'safe', False) safe = getattr(inner, 'safe', False)
headers = getattr(inner, 'headers', None) headers = getattr(inner, 'headers', None)
status = getattr(inner, 'code', 500) status = getattr(inner, 'code', http_client.INTERNAL_SERVER_ERROR)
if status is None: if status is None:
status = 500 status = http_client.INTERNAL_SERVER_ERROR
msg_dict = dict(url=req.url, status=status) msg_dict = dict(url=req.url, status=status)
LOG.info("%(url)s returned with HTTP %(status)d", msg_dict) LOG.info("%(url)s returned with HTTP %(status)d", msg_dict)

View File

@ -25,6 +25,7 @@ from oslo_utils import encodeutils
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import strutils from oslo_utils import strutils
import six import six
from six.moves import http_client
import webob import webob
import webob.exc import webob.exc
@ -441,7 +442,7 @@ class ResponseObject(object):
self.obj = obj self.obj = obj
self.serializers = serializers self.serializers = serializers
self._default_code = 200 self._default_code = http_client.OK
self._code = code self._code = code
self._headers = headers or {} self._headers = headers or {}
self.serializer = None self.serializer = None
@ -1316,16 +1317,16 @@ class Controller(object):
class Fault(webob.exc.HTTPException): class Fault(webob.exc.HTTPException):
"""Wrap webob.exc.HTTPException to provide API friendly response.""" """Wrap webob.exc.HTTPException to provide API friendly response."""
_fault_names = {400: "badRequest", _fault_names = {http_client.BAD_REQUEST: "badRequest",
401: "unauthorized", http_client.UNAUTHORIZED: "unauthorized",
403: "forbidden", http_client.FORBIDDEN: "forbidden",
404: "itemNotFound", http_client.NOT_FOUND: "itemNotFound",
405: "badMethod", http_client.METHOD_NOT_ALLOWED: "badMethod",
409: "conflictingRequest", http_client.CONFLICT: "conflictingRequest",
413: "overLimit", http_client.REQUEST_ENTITY_TOO_LARGE: "overLimit",
415: "badMediaType", http_client.UNSUPPORTED_MEDIA_TYPE: "badMediaType",
501: "notImplemented", http_client.NOT_IMPLEMENTED: "notImplemented",
503: "serviceUnavailable"} http_client.SERVICE_UNAVAILABLE: "serviceUnavailable"}
def __init__(self, exception): def __init__(self, exception):
"""Create a Fault for the given webob.exc.exception.""" """Create a Fault for the given webob.exc.exception."""
@ -1344,7 +1345,7 @@ class Fault(webob.exc.HTTPException):
fault_name: { fault_name: {
'code': code, 'code': code,
'message': i18n.translate(explanation, locale)}} 'message': i18n.translate(explanation, locale)}}
if code == 413: if code == http_client.REQUEST_ENTITY_TOO_LARGE:
retry = self.wrapped_exc.headers.get('Retry-After', None) retry = self.wrapped_exc.headers.get('Retry-After', None)
if retry: if retry:
fault_data[fault_name]['retryAfter'] = retry fault_data[fault_name]['retryAfter'] = retry

View File

@ -15,6 +15,8 @@
"""The volumes snapshots api.""" """The volumes snapshots api."""
from six.moves import http_client
from webob import exc from webob import exc
from cinder.api.openstack import wsgi from cinder.api.openstack import wsgi
@ -70,7 +72,7 @@ class SnapshotsController(snapshots_v2.SnapshotsController):
super(SnapshotsController, self).detail( super(SnapshotsController, self).detail(
_update_search_opts(req))) _update_search_opts(req)))
@wsgi.response(200) @wsgi.response(http_client.OK)
def create(self, req, body): def create(self, req, body):
"""Creates a new snapshot.""" """Creates a new snapshot."""
if (body is None or not body.get('snapshot') or if (body is None or not body.get('snapshot') or

View File

@ -16,6 +16,7 @@
"""The volumes api.""" """The volumes api."""
from oslo_log import log as logging from oslo_log import log as logging
from six.moves import http_client
from webob import exc from webob import exc
from cinder.api.openstack import wsgi from cinder.api.openstack import wsgi
@ -102,7 +103,7 @@ class VolumeController(volumes_v2.VolumeController):
return _volume_v2_to_v1( return _volume_v2_to_v1(
super(VolumeController, self).detail(req)) super(VolumeController, self).detail(req))
@wsgi.response(200) @wsgi.response(http_client.OK)
def create(self, req, body): def create(self, req, body):
"""Creates a new volume.""" """Creates a new volume."""
if (body is None or not body.get('volume') or if (body is None or not body.get('volume') or

View File

@ -415,7 +415,7 @@ class WsgiLimiterProxy(object):
resp = conn.getresponse() resp = conn.getresponse()
if 200 >= resp.status < 300: if http_client.OK >= resp.status < http_client.MULTIPLE_CHOICES:
return None, None return None, None
return resp.getheader("X-Wait-Seconds"), resp.read() or None return resp.getheader("X-Wait-Seconds"), resp.read() or None

View File

@ -13,6 +13,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from six.moves import http_client
import webob import webob
from webob import exc from webob import exc
@ -128,7 +129,7 @@ class Controller(wsgi.Controller):
# Not found exception will be handled at the wsgi level # Not found exception will be handled at the wsgi level
snapshot = self.volume_api.get_snapshot(context, snapshot_id) snapshot = self.volume_api.get_snapshot(context, snapshot_id)
self.volume_api.delete_snapshot_metadata(context, snapshot, id) self.volume_api.delete_snapshot_metadata(context, snapshot, id)
return webob.Response(status_int=200) return webob.Response(status_int=http_client.OK)
def create_resource(): def create_resource():

View File

@ -18,6 +18,7 @@
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import encodeutils from oslo_utils import encodeutils
from oslo_utils import strutils from oslo_utils import strutils
from six.moves import http_client
import webob import webob
from webob import exc from webob import exc
@ -64,7 +65,7 @@ class SnapshotsController(wsgi.Controller):
snapshot = self.volume_api.get_snapshot(context, id) snapshot = self.volume_api.get_snapshot(context, id)
self.volume_api.delete_snapshot(context, snapshot) self.volume_api.delete_snapshot(context, snapshot)
return webob.Response(status_int=202) return webob.Response(status_int=http_client.ACCEPTED)
def index(self, req): def index(self, req):
"""Returns a summary list of snapshots.""" """Returns a summary list of snapshots."""
@ -108,7 +109,7 @@ class SnapshotsController(wsgi.Controller):
snapshots = self._view_builder.summary_list(req, snapshots.objects) snapshots = self._view_builder.summary_list(req, snapshots.objects)
return snapshots return snapshots
@wsgi.response(202) @wsgi.response(http_client.ACCEPTED)
def create(self, req, body): def create(self, req, body):
"""Creates a new snapshot.""" """Creates a new snapshot."""
kwargs = {} kwargs = {}

View File

@ -13,6 +13,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from six.moves import http_client
import webob import webob
from cinder.api import common from cinder.api import common
@ -136,7 +137,7 @@ class Controller(wsgi.Controller):
volume, volume,
id, id,
meta_type=common.METADATA_TYPES.user) meta_type=common.METADATA_TYPES.user)
return webob.Response(status_int=200) return webob.Response(status_int=http_client.OK)
def create_resource(): def create_resource():

View File

@ -19,6 +19,7 @@
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import uuidutils from oslo_utils import uuidutils
from six.moves import http_client
import webob import webob
from webob import exc from webob import exc
@ -75,7 +76,7 @@ class VolumeController(wsgi.Controller):
# Not found exception will be handled at the wsgi level # Not found exception will be handled at the wsgi level
volume = self.volume_api.get(context, id) volume = self.volume_api.get(context, id)
self.volume_api.delete(context, volume, cascade=cascade) self.volume_api.delete(context, volume, cascade=cascade)
return webob.Response(status_int=202) return webob.Response(status_int=http_client.ACCEPTED)
def index(self, req): def index(self, req):
"""Returns a summary list of volumes.""" """Returns a summary list of volumes."""
@ -171,7 +172,7 @@ class VolumeController(wsgi.Controller):
"access requested image.") "access requested image.")
raise exc.HTTPBadRequest(explanation=msg) raise exc.HTTPBadRequest(explanation=msg)
@wsgi.response(202) @wsgi.response(http_client.ACCEPTED)
def create(self, req, body): def create(self, req, body):
"""Creates a new volume.""" """Creates a new volume."""
self.assert_valid_body(body, 'volume') self.assert_valid_body(body, 'volume')