Merge "move flatten dict key to common utils"
[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 from __future__ import absolute_import
10 import re
11 import importlib
12 import logging
13
14 from flask import request
15 from flask_restful import Resource
16
17 from api.utils import common as common_utils
18 from yardstick.common import constants as consts
19
20 logger = logging.getLogger(__name__)
21 logger.setLevel(logging.DEBUG)
22
23
24 class ApiResource(Resource):
25
26     def _post_args(self):
27         data = request.json if request.json else {}
28         params = common_utils.translate_to_str(data)
29         action = params.get('action', request.form.get('action', ''))
30         args = params.get('args', {})
31
32         try:
33             args['file'] = request.files['file']
34         except KeyError:
35             pass
36
37         logger.debug('Input args is: action: %s, args: %s', action, args)
38
39         return action, args
40
41     def _get_args(self):
42         args = common_utils.translate_to_str(request.args)
43         logger.debug('Input args is: args: %s', args)
44
45         return args
46
47     def _dispatch_post(self):
48         action, args = self._post_args()
49         return self._dispatch(args, action)
50
51     def _dispatch_get(self, **kwargs):
52         args = self._get_args()
53         args.update(kwargs)
54         return self._dispatch(args)
55
56     def _dispatch(self, args, action='default'):
57         module_name = re.sub(r'([A-Z][a-z]*)', r'_\1',
58                              self.__class__.__name__)[1:].lower()
59
60         module_name = 'api.resources.%s' % module_name
61         resources = importlib.import_module(module_name)
62         try:
63             return getattr(resources, action)(args)
64         except AttributeError:
65             common_utils.result_handler(consts.API_ERROR, 'No such action')