Skip to content

Commit

Permalink
Allow passing a json_error_formatter to the middleware
Browse files Browse the repository at this point in the history
This is so error responses can be formatted according to the rules
of the application.

Change-Id: Ie44399447a349ebc49251dc63c23f56c6423fca6
  • Loading branch information
cdent committed Mar 20, 2018
1 parent b5359fc commit f816e32
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
6 changes: 6 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ versions_list
It's assumed that any application that is using microversions will have such
a list for its own housekeeping and documentation.

One named parameter is optional:

json_error_formatter
A Webob error formatter that can be used to structure the response when JSON
is expected.

For example::

def app():
Expand Down
15 changes: 11 additions & 4 deletions microversion_parse/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,33 +37,40 @@ class MicroversionMiddleware(object):
Otherwise the application is called.
"""

def __init__(self, application, service_type, versions):
def __init__(self, application, service_type, versions,
json_error_formatter=None):
"""Create the WSGI middleware.
:param application: The application hosting the service.
:param service_type: The service type (entry in keystone catalog)
of the application.
:param versions: An ordered list of legitimate versions for the
application.
:param json_error_formatter: A Webob exception error formatter.
See Webob for details.
"""
self.application = application
self.service_type = service_type
self.microversion_environ = '%s.microversion' % service_type
self.versions = versions
self.json_error_formatter = json_error_formatter

@webob.dec.wsgify
def __call__(self, req):
try:
microversion = microversion_parse.extract_version(
req.headers, self.service_type, self.versions)
# TODO(cdent): These error response are not formatted according to
# api-sig guidelines.
# api-sig guidelines, unless a json_error_formatter is provided
# that can do it. For an example, see the placement service.
except ValueError as exc:
raise webob.exc.HTTPNotAcceptable(
('Invalid microversion: %(error)s') % {'error': exc})
('Invalid microversion: %(error)s') % {'error': exc},
json_formatter=self.json_error_formatter)
except TypeError as exc:
raise webob.exc.HTTPBadRequest(
('Invalid microversion: %(error)s') % {'error': exc})
('Invalid microversion: %(error)s') % {'error': exc},
json_formatter=self.json_error_formatter)

req.environ[self.microversion_environ] = microversion
microversion_header = '%s %s' % (self.service_type, microversion)
Expand Down

0 comments on commit f816e32

Please sign in to comment.