Seed code for yarf
[ta/yarf.git] / src / yarf / restresource.py
1 # Copyright 2019 Nokia
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 implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15
16 import inspect
17 import six
18 from flask import request
19 from flask_restful import reqparse
20 from werkzeug.exceptions import BadRequest
21
22 from yarf.baseresource import BaseResource
23
24 class RequestArgument(object):
25     """ More advanced arguments
26         Parameters:
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
33                                         False if not
34                       reason: (string) Setting the reasoning for the
35                                        failure
36             typeof: The typeof the argument. The argument will be converted
37                     to the type you define. Should be a function pointer
38     """
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
43         else:
44             self.validate_func = None
45         self.name = name
46
47     def validate(self, value):
48         if not self.validate_func:
49             return
50         status, reason = self.validate_func(value)
51         if not status:
52             raise BadRequest(description=reason)
53
54 class RestResource(BaseResource):
55     """ Class from which the plugins should inherit
56         Variables:
57         extra_wrappers: are function wrappers that will
58                         be executed when any function is
59                         executed by the frame (for example
60                         get)
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
64                           get_args
65     """
66     extra_wrappers = []
67     parser_arguments = []
68     endpoints = None
69     int_arg_class = RequestArgument
70
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
75     """
76     @classmethod
77     def get_args(cls):
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])
83         return args
84
85     @classmethod
86     def get_token(cls):
87         token = ""
88         try:
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.")
92         return token
93