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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
18 from flask import request
19 from flask_restful import reqparse
20 from werkzeug.exceptions import BadRequest
22 from yarf.baseresource import BaseResource
24 class RequestArgument(object):
25 """ More advanced arguments
27 name: Name of the argument
28 default: The default value if not defined
29 validate: function pointer to a validation function that will
30 be called to validate the argument.
31 The function should return tuple containing
32 status: (boolean) True if validation passed
34 reason: (string) Setting the reasoning for the
36 typeof: The typeof the argument. The argument will be converted
37 to the type you define. Should be a function pointer
39 def __init__(self, name, default=None, validate=None, typeof=lambda x: six.text_type(x)):
40 self.argument_class = reqparse.Argument(name=name, default=default, type=typeof)
41 if validate and inspect.isfunction(validate):
42 self.validate_func = validate
44 self.validate_func = None
47 def validate(self, value):
48 if not self.validate_func:
50 status, reason = self.validate_func(value)
52 raise BadRequest(description=reason)
54 class RestResource(BaseResource):
55 """ Class from which the plugins should inherit
57 extra_wrappers: are function wrappers that will
58 be executed when any function is
59 executed by the frame (for example
61 parser_arguments: Are the arguments that can be defined
62 if you need arguments for your plugin
63 these arguments can be fetched with
69 int_arg_class = RequestArgument
71 """ Function to get arguments from request
72 The function will call validate to the
73 arguments if they are of type RequestArgument
74 Returns: A dictionary of the arguments
78 args = cls.parser.parse_args()
79 for arg in args.keys():
80 for parg in cls.parser_arguments:
81 if isinstance(parg, cls.int_arg_class) and parg.name == arg:
82 parg.validate(args[arg])
89 token = request.headers.get("X-Auth-Token", type=str)
90 except KeyError as err:
91 cls.logger.info("Failed to get auth token from request.")