Add API to show test case documentation
[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
19 logger = logging.getLogger(__name__)
20 logger.setLevel(logging.DEBUG)
21
22
23 class ApiResource(Resource):
24
25     def _post_args(self):
26         data = request.json if request.json else {}
27         params = common_utils.translate_to_str(data)
28         action = params.get('action', request.form.get('action', ''))
29         args = params.get('args', {})
30
31         try:
32             args['file'] = request.files['file']
33         except KeyError:
34             pass
35
36         logger.debug('Input args is: action: %s, args: %s', action, args)
37
38         return action, args
39
40     def _get_args(self):
41         args = common_utils.translate_to_str(request.args)
42         logger.debug('Input args is: args: %s', args)
43
44         return args
45
46     def _dispatch_post(self):
47         action, args = self._post_args()
48         return self._dispatch(args, action)
49
50     def _dispatch_get(self, **kwargs):
51         args = self._get_args()
52         args.update(kwargs)
53         return self._dispatch(args)
54
55     def _dispatch(self, args, action='default'):
56         module_name = re.sub(r'([A-Z][a-z]*)', r'_\1',
57                              self.__class__.__name__)[1:].lower()
58
59         module_name = 'api.resources.%s' % module_name
60         resources = importlib.import_module(module_name)
61         try:
62             return getattr(resources, action)(args)
63         except NameError:
64             common_utils.error_handler('Wrong action')