Merge "Create API to update openrc"
[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 __init__(self):
30         super(ApiResource, self).__init__()
31
32     def _post_args(self):  # pylint: disable=no-self-use
33         # pylint: disable=maybe-no-member
34         """ Return action and args after parsing request """
35
36         data = request.json if request.json else {}
37         params = api_utils.change_to_str_in_dict(data)
38         action = params.get('action', request.form.get('action', ''))
39         args = params.get('args', {})
40         try:
41             args['file'] = request.files['file']
42         except KeyError:
43             pass
44         LOGGER.debug('Input args are: action: %s, args: %s', action, args)
45
46         return action, args
47
48     def _dispatch_post(self):
49         """ Dispatch request """
50         action, args = self._post_args()
51         return self._dispatch(args, action)
52
53     def _dispatch(self, args, action):
54         """
55         Dynamically load the classes with reflection and
56         obtain corresponding methods
57         """
58         try:
59             return getattr(self, action)(args)
60         except AttributeError:
61             api_utils.result_handler(status=1, data='No such action')
62
63
64 # Import modules from package "functest.api.resources"
65 # and append them into sys.modules
66 api_utils.import_modules_from_package("functest.api.resources")