Merge "Create API to run test suite"
[yardstick.git] / api / base.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 import re
10 import importlib
11 import logging
12
13 from flask import request
14 from flask_restful import Resource
15
16 from api.utils import common as common_utils
17
18 logger = logging.getLogger(__name__)
19 logger.setLevel(logging.DEBUG)
20
21
22 class ApiResource(Resource):
23
24     def _post_args(self):
25         params = common_utils.translate_to_str(request.json)
26         action = params.get('action', '')
27         args = params.get('args', {})
28         logger.debug('Input args is: action: %s, args: %s', action, args)
29
30         return action, args
31
32     def _get_args(self):
33         args = common_utils.translate_to_str(request.args)
34         logger.debug('Input args is: args: %s', args)
35
36         return args
37
38     def _dispatch_post(self):
39         action, args = self._post_args()
40         return self._dispatch(args, action)
41
42     def _dispatch_get(self):
43         args = self._get_args()
44         return self._dispatch(args)
45
46     def _dispatch(self, args, action='default'):
47         module_name = re.sub(r'([A-Z][a-z]*)', r'_\1',
48                              self.__class__.__name__)[1:].lower()
49
50         module_name = 'api.resources.%s' % module_name
51         resources = importlib.import_module(module_name)
52         try:
53             return getattr(resources, action)(args)
54         except NameError:
55             common_utils.error_handler('Wrong action')