Stop using decorators for parse and validate

Instead of using a decorator for parsing the incoming data we can use
calls to the objects, making the code much more readable.
This commit is contained in:
Alvaro Lopez Garcia 2015-04-20 15:53:16 +02:00
parent a55edb366a
commit 88c6a4f29d
4 changed files with 24 additions and 29 deletions

View File

@ -74,15 +74,6 @@ class Controller(object):
else:
raise exception_from_response(response)
@staticmethod
def validate(schema):
def accepts(f):
def _validate(obj, req, body, *args, **kwargs):
parsed_obj = req.validate(schema)
return f(obj, parsed_obj, req, body, *args, **kwargs)
return _validate
return accepts
def exception_from_response(response):
"""Convert an OpenStack V2 Fault into a webob exception.

View File

@ -24,6 +24,7 @@ from ooi.occi.infrastructure import storage_link
from ooi.openstack import contextualization
from ooi.openstack import helpers
from ooi.openstack import templates
from ooi.wsgi import parsers
class Controller(ooi.api.base.Controller):
@ -66,19 +67,24 @@ class Controller(ooi.api.base.Controller):
return collection.Collection(resources=occi_compute_resources)
@ooi.api.base.Controller.validate(
{"kind": compute.ComputeResource.kind,
"mixins": [
templates.OpenStackOSTemplate,
templates.OpenStackResourceTemplate,
],
"optional_mixins": [
contextualization.user_data,
contextualization.public_key,
]
})
def create(self, obj, req, body):
def create(self, req, body):
tenant_id = req.environ["keystone.token_auth"].user.project_id
parser = req.get_parser()(req.headers, req.body)
scheme = {
"kind": compute.ComputeResource.kind,
"mixins": [
templates.OpenStackOSTemplate,
templates.OpenStackResourceTemplate,
],
"optional_mixins": [
contextualization.user_data,
contextualization.public_key,
]
}
obj = parser.parse()
validator = parsers.Validator(obj)
validator.validate(scheme)
name = obj.get("occi.core.title", "OCCI VM")
image = obj["schemes"][templates.OpenStackOSTemplate.scheme][0]
flavor = obj["schemes"][templates.OpenStackResourceTemplate.scheme][0]

View File

@ -61,15 +61,9 @@ class Request(webob.Request):
return content_type
def get_parser(self):
mtype = parsers.get_media_map().get(self.get_content_type,
"header")
mtype = parsers.get_media_map().get(self.get_content_type(), "header")
return parsers.get_default_parsers()[mtype]
def validate(self, schema):
parser = self.get_parser()(self.headers, self.body)
parser.validate(schema)
return parser.parsed_obj
class OCCIMiddleware(object):

View File

@ -36,6 +36,11 @@ class BaseParser(object):
def parse(self):
raise NotImplemented
class Validator(object):
def __init__(self, obj):
self.parsed_obj = obj
def _validate_kind(self, kind):
try:
if kind.type_id != self.parsed_obj["kind"]:
@ -76,7 +81,6 @@ class BaseParser(object):
return unmatched
def validate(self, schema):
self.parsed_obj = self.parse()
if "kind" in schema:
self._validate_kind(schema["kind"])
unmatched = copy.copy(self.parsed_obj["mixins"])