Merge "Update the details of tempest results"
[functest.git] / functest / api / base.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """
11 The base class to dispatch request
12
13 """
14
15 import logging
16
17 from flask import request
18 from flask_restful import Resource
19
20 from functest.api.common import api_utils
21
22
23 LOGGER = logging.getLogger(__name__)
24
25
26 class ApiResource(Resource):
27     """ API Resource class"""
28
29     def _post_args(self):  # pylint: disable=no-self-use
30         # pylint: disable=maybe-no-member
31         """ Return action and args after parsing request """
32
33         data = request.json if request.json else {}
34         params = api_utils.change_to_str_in_dict(data)
35         action = params.get('action', request.form.get('action', ''))
36         args = params.get('args', {})
37         try:
38             args['file'] = request.files['file']
39         except KeyError:
40             pass
41         LOGGER.debug('Input args are: action: %s, args: %s', action, args)
42
43         return action, args
44
45     def _get_args(self):  # pylint: disable=no-self-use
46         """ Convert the unicode to string for request.args """
47         args = api_utils.change_to_str_in_dict(request.args)
48         return args
49
50     def _dispatch_post(self):
51         """ Dispatch request """
52         action, args = self._post_args()
53         return self._dispatch(args, action)
54
55     def _dispatch(self, args, action):
56         """
57         Dynamically load the classes with reflection and
58         obtain corresponding methods
59         """
60         try:
61             return getattr(self, action)(args)
62         except AttributeError:
63             api_utils.result_handler(status=1, data='No such action')
64
65
66 # Import modules from package "functest.api.resources"
67 # and append them into sys.modules
68 api_utils.import_modules_from_package("functest.api.resources")