Merge "Yardstick api database v2 model"
[yardstick.git] / api / server.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
11 import inspect
12 import logging
13 from six.moves import filter
14
15 from flasgger import Swagger
16 from flask import Flask
17 from flask_restful import Api
18
19 from api.database import Base
20 from api.database import db_session
21 from api.database import engine
22 from api.database.v1 import models
23 from api.urls import urlpatterns
24 from api import ApiResource
25 from yardstick import _init_logging
26 from yardstick.common import utils
27
28 logger = logging.getLogger(__name__)
29
30 app = Flask(__name__)
31
32 Swagger(app)
33
34 api = Api(app)
35
36
37 @app.teardown_request
38 def shutdown_session(exception=None):
39     db_session.remove()
40
41
42 def get_resource(resource_name):
43     name = ''.join(resource_name.split('_'))
44     return next((r for r in utils.itersubclasses(ApiResource)
45                  if r.__name__.lower() == name))
46
47
48 def init_db():
49     def func(a):
50         try:
51             if issubclass(a[1], Base):
52                 return True
53         except TypeError:
54             pass
55         return False
56
57     subclses = filter(func, inspect.getmembers(models, inspect.isclass))
58     logger.debug('Import models: %s', [a[1] for a in subclses])
59     Base.metadata.create_all(bind=engine)
60
61
62 def app_wrapper(*args, **kwargs):
63     init_db()
64     return app(*args, **kwargs)
65
66
67 for u in urlpatterns:
68     api.add_resource(get_resource(u.endpoint), u.url, endpoint=u.endpoint)
69
70
71 if __name__ == '__main__':
72     _init_logging()
73     logger.setLevel(logging.DEBUG)
74     logger.info('Starting server')
75     init_db()
76     app.run(host='0.0.0.0')