| 1 |
# Copyright (c) 2013 Red Hat, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 12 |
# implied. |
| 13 |
# See the License for the specific language governing permissions and |
| 14 |
# limitations under the License. |
| 15 |
|
| 16 |
import jsonschema |
| 17 |
from jsonschema import validators |
| 18 |
|
| 19 |
from zaqarclient import errors |
| 20 |
|
| 21 |
|
| 22 |
class Api: |
| 23 |
|
| 24 |
schema = {} |
| 25 |
label = None |
| 26 |
validators = {} |
| 27 |
|
| 28 |
def is_supported(self, operation): |
| 29 |
"""Returns `True` if `operation` is supported |
| 30 |
|
| 31 |
:param operation: The operation to check on. |
| 32 |
:type operation: str |
| 33 |
|
| 34 |
:rtype: bool |
| 35 |
""" |
| 36 |
return operation in self.schema |
| 37 |
|
| 38 |
def get_schema(self, operation): |
| 39 |
"""Returns the schema for an operation |
| 40 |
|
| 41 |
:param operation: Operation for which params need |
| 42 |
to be validated. |
| 43 |
:type operation: str |
| 44 |
|
| 45 |
:returns: Operation's schema |
| 46 |
:rtype: dict |
| 47 |
|
| 48 |
:raises: `errors.InvalidOperation` if the operation |
| 49 |
does not exist |
| 50 |
""" |
| 51 |
try: |
| 52 |
return self.schema[operation] |
| 53 |
except KeyError: |
| 54 |
# TODO(flaper87): gettext support |
| 55 |
msg = '{} is not a valid operation'.format(operation) |
| 56 |
raise errors.InvalidOperation(msg) |
| 57 |
|
| 58 |
def validate(self, operation, params): |
| 59 |
"""Validates the request data |
| 60 |
|
| 61 |
This method relies on jsonschema and exists |
| 62 |
just as a way for third-party transport to validate |
| 63 |
the request. It's not recommended to validate every |
| 64 |
request since they are already validated server side. |
| 65 |
|
| 66 |
:param operation: Operation's for which params need |
| 67 |
to be validated. |
| 68 |
:type operation: str |
| 69 |
:param params: Params to validate |
| 70 |
:type params: dict |
| 71 |
|
| 72 |
:returns: True if the schema is valid, False otherwise |
| 73 |
:raises: `errors.InvalidOperation` if the operation |
| 74 |
does not exist |
| 75 |
""" |
| 76 |
|
| 77 |
if operation not in self.validators: |
| 78 |
schema = self.get_schema(operation) |
| 79 |
self.validators[operation] = validators.Draft4Validator(schema) |
| 80 |
|
| 81 |
try: |
| 82 |
self.validators[operation].validate(params) |
| 83 |
except jsonschema.ValidationError: |
| 84 |
# TODO(flaper87): Log error |
| 85 |
return False |
| 86 |
|
| 87 |
return True |