Merge "project-ize kibana_dashboard"
[releng.git] / utils / test / result_collection_api / opnfv_testapi / tornado_swagger / views.py
1 ##############################################################################
2 # Copyright (c) 2016 ZTE Corporation
3 # feng.xiaowei@zte.com.cn
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 inspect
10 import json
11
12 import tornado.template
13 import tornado.web
14
15 from settings import SWAGGER_VERSION, SWAGGER_API_LIST, SWAGGER_API_SPEC
16 from settings import models, basePath
17
18
19 def json_dumps(obj, pretty=False):
20     return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) \
21         if pretty else json.dumps(obj)
22
23
24 class SwaggerUIHandler(tornado.web.RequestHandler):
25     def initialize(self, static_path, **kwds):
26         self.static_path = static_path
27
28     def get_template_path(self):
29         return self.static_path
30
31     def get(self):
32         discovery_url = basePath() + self.reverse_url(SWAGGER_API_LIST)
33         self.render('index.html', discovery_url=discovery_url)
34
35
36 class SwaggerResourcesHandler(tornado.web.RequestHandler):
37     def initialize(self, api_version, exclude_namespaces, **kwds):
38         self.api_version = api_version
39         self.exclude_namespaces = exclude_namespaces
40
41     def get(self):
42         self.set_header('content-type', 'application/json')
43         resources = {
44             'apiVersion': self.api_version,
45             'swaggerVersion': SWAGGER_VERSION,
46             'basePath': basePath(),
47             'produces': ["application/json"],
48             'description': 'Test Api Spec',
49             'apis': [{
50                 'path': self.reverse_url(SWAGGER_API_SPEC),
51                 'description': 'Test Api Spec'
52             }]
53         }
54
55         self.finish(json_dumps(resources, self.get_arguments('pretty')))
56
57
58 class SwaggerApiHandler(tornado.web.RequestHandler):
59     def initialize(self, api_version, base_url, **kwds):
60         self.api_version = api_version
61         self.base_url = base_url
62
63     def get(self):
64         self.set_header('content-type', 'application/json')
65         apis = self.find_api(self.application.handlers)
66         if apis is None:
67             raise tornado.web.HTTPError(404)
68
69         specs = {
70             'apiVersion': self.api_version,
71             'swaggerVersion': SWAGGER_VERSION,
72             'basePath': basePath(),
73             'apis': [self.__get_api_spec__(path, spec, operations)
74                      for path, spec, operations in apis],
75             'models': self.__get_models_spec(models)
76         }
77         self.finish(json_dumps(specs, self.get_arguments('pretty')))
78
79     def __get_models_spec(self, models):
80         models_spec = {}
81         for model in models:
82             models_spec.setdefault(model.id, self.__get_model_spec(model))
83         return models_spec
84
85     @staticmethod
86     def __get_model_spec(model):
87         return {
88             'description': model.summary,
89             'id': model.id,
90             'notes': model.notes,
91             'properties': model.properties,
92             'required': model.required
93         }
94
95     @staticmethod
96     def __get_api_spec__(path, spec, operations):
97         return {
98             'path': path,
99             'description': spec.handler_class.__doc__,
100             'operations': [{
101                 'httpMethod': api.func.__name__.upper(),
102                 'nickname': api.nickname,
103                 'parameters': api.params.values(),
104                 'summary': api.summary,
105                 'notes': api.notes,
106                 'responseClass': api.responseClass,
107                 'responseMessages': api.responseMessages,
108             } for api in operations]
109         }
110
111     @staticmethod
112     def find_api(host_handlers):
113         def get_path(url, args):
114             return url % tuple(['{%s}' % arg for arg in args])
115
116         def get_operations(cls):
117             return [member.rest_api
118                     for (_, member) in inspect.getmembers(cls)
119                     if hasattr(member, 'rest_api')]
120
121         for host, handlers in host_handlers:
122             for spec in handlers:
123                 for (_, mbr) in inspect.getmembers(spec.handler_class):
124                     if inspect.ismethod(mbr) and hasattr(mbr, 'rest_api'):
125                         path = get_path(spec._path, mbr.rest_api.func_args)
126                         operations = get_operations(spec.handler_class)
127                         yield path, spec, operations
128                         break