def main(global_config, **settings):
    """ WSGI-Server erzeugen und konfigurieren. """

    # extrat all flask.* configuration items
    flaskConfig = pasteToFlaskConfig(global_config, settings)
    DEBUG = flaskConfig.get('DEBUG', '0') in ['1', 'on', 'true']
    VERBOSE = int(global_config.get('STARTUP_VERBOSE', 0))

    # create app instance
    connexionApp = connexion.App("{{cookiecutter.project_name}}", debug=DEBUG, swagger_ui=True)
    flaskApp = connexionApp.app

    # configure
    flaskApp.config.update(flaskConfig)
    cloudFoundryfyConfig(flaskApp.config)
    
    # Rest-Endpoint CF Spring Actuator like Metadaten (Definition im sub-package api.actuator)
    apiFile = pkg_resources.resource_filename(__name__, 'schema/actuator.yml')
    connexionApp.add_api(apiFile, strict_validation=False, validate_responses=True,
                         resolver=connexion.RestyResolver('%s.api.actuator' % (__package__)),
                         base_path='/cloudfoundryapplication')

    # Restendpoint App Version 1 (Definition im sub-package api)
    apiFile = pkg_resources.resource_filename(__name__, 'schema/app_v1.yml')
    connexionApp.add_api(apiFile, strict_validation=True, validate_responses=True,
                         resolver=connexion.RestyResolver('%s.api' % (__package__)))

    if VERBOSE > 0:
        print(yaml.dump(flaskApp.config))

    if DEBUG:
        from flask_debugtoolbar import DebugToolbarExtension
        toolbar = DebugToolbarExtension()
        toolbar.init_app(flaskApp)

    {% if cookiecutter.use_reldb.startswith('y') %}
    # proaktive Initialisierung der Datenbank (entfernen -> lazy)
    from .model import getDb
    with flaskApp.app_context():
        db = getDb()
    {%- endif -%}

    {% if cookiecutter.use_ui.startswith('y') %}
    # simple web-ui page without swagger
    from .ui.hello import helloPage
    flaskApp.register_blueprint(helloPage)
    {%- endif -%}

    return flaskApp
Пример #2
0
    def run_forever(self):
        app = connexion.FlaskApp(__name__)
        init_jwt(app.app)

        @app.app.teardown_appcontext
        def shutdown_session(exception=None):
            db_session.remove()

        app.add_api(API.SPEC_FILE,
                    arguments={
                        'title': API.TITLE,
                        'url_prefix': API.URL_PREFIX,
                        'RESPONSES': API.RESPONSES
                    },
                    resolver=connexion.RestyResolver(API.IMPL_LOCATION),
                    strict_validation=True)
        CORS(app.app)
        log.info('[⚙] Starting API server with {} backend'.format(
            API_SERVER.BACKEND))
        URL = '{schema}://{host}:{port}/{url_prefix}/ui/'.format(
            schema=API.URL_SCHEMA,
            host=API.URL_HOSTNAME,
            port=API.URL_PORT,
            url_prefix=API.URL_PREFIX)
        log.info(
            green('[✔] API documentation (Swagger UI) available at: {}'.format(
                URL)))
        app.run(server=API_SERVER.BACKEND,
                host=API_SERVER.HOST,
                port=API_SERVER.PORT,
                debug=API_SERVER.DEBUG,
                log=APILogger)
Пример #3
0
def create_app(specs):
    """Create reposcan app."""

    init_logging()
    LOGGER.info("Starting (version %s).", VMAAS_VERSION)
    sync_interval = int(os.getenv('REPOSCAN_SYNC_INTERVAL_MINUTES', "360")) * 60000
    if sync_interval > 0:
        PeriodicCallback(periodic_sync, sync_interval).start()
    else:
        LOGGER.info("Periodic syncing disabled.")

    ws_handler = ReposcanWebsocket()

    def terminate(*_):
        """Trigger shutdown."""
        LOGGER.info("Signal received, stopping application.")
        # Kill asyncio ioloop
        IOLoop.instance().add_callback_from_signal(ws_handler.stop)
        # Kill background pool
        SyncTask.cancel()

    for sig in KILL_SIGNALS:
        signal.signal(sig, terminate)

    ws_handler.websocket_reconnect()
    ws_handler.reconnect_callback = PeriodicCallback(ws_handler.websocket_reconnect,
                                                     WEBSOCKET_RECONNECT_INTERVAL * 1000)
    ws_handler.reconnect_callback.start()


    app = connexion.App(__name__, options={
        'swagger_ui': True,
        'openapi_spec_path': '/openapi.json'
    })

    # Response validation is disabled due to returing streamed response in GET /pkgtree
    # https://github.com/zalando/connexion/pull/467 should fix it
    for route, spec in specs.items():
        app.add_api(spec, resolver=connexion.RestyResolver('reposcan'),
                    validate_responses=False,
                    strict_validation=True,
                    base_path=route,
                    arguments={"vmaas_version": VMAAS_VERSION}
                    )


    @app.app.route('/metrics', methods=['GET'])
    def metrics():  # pylint: disable=unused-variable
        # /metrics API shouldn't be visible in the API documentation,
        # hence it's added here in the create_app step
        return generate_latest(), 200, {'Content-Type': 'text/plain; charset=utf-8'}

    @app.app.after_request
    def set_headers(response):  # pylint: disable=unused-variable
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type"
        return response

    return app
Пример #4
0
def create_app():
    connexion_app = connexion.App(__name__, specification_dir="specs/")
    connexion_api = connexion_app.add_api(
        resolver=connexion.RestyResolver("jboard.viewsets"),
        specification="v1.yaml",
        strict_validation=True,
        validate_responses=True,
    )
    flask_app = connexion_app.app
    flask_app.config["JSON_SORT_KEYS"] = False
    flask_app.config["spec"] = connexion_api.specification
    return flask_app
Пример #5
0
def client():
    app = connexion.FlaskApp(__name__)
    app.add_api('../../tensorhive/api/' + API.SPEC_FILE,
                arguments={
                    'title': API.TITLE,
                    'url_prefix': API.URL_PREFIX,
                    'RESPONSES': API.RESPONSES
                },
                resolver=connexion.RestyResolver(API.IMPL_LOCATION),
                strict_validation=True)
    CORS(app.app)
    return app.app.test_client()
Пример #6
0
from jinja2 import Environment, PackageLoader
from filters import get_all_apis_router, get_entity_fields

SWAGGER_PATH = "swagger/"
API_PATH = 'endpoints'

app = connexion.App(__name__, specification_dir=SWAGGER_PATH)
application = app.app
application.url_map.strict_slashes = False

_env = Environment(loader=PackageLoader('swagger'))
swagger_string = _env.get_template("main.yaml").render(
    lstrip=False,
    api=get_all_apis_router("api", SWAGGER_PATH),
    schemas=get_all_apis_router("schemas", SWAGGER_PATH),
    **get_entity_fields(),
)
import pprint
pprint.pprint(swagger_string)

specification = yaml.safe_load(swagger_string)

app.add_api(
    specification,
    resolver=connexion.RestyResolver(API_PATH),
    options={"swagger_ui": True},
)

if __name__ == '__main__':
    app.run()
Пример #7
0

@app.route(api_url + '/users', methods=['POST'])
@cross_origin(origin='*')
def create_user():

    id = request.form['id']
    name = request.form['name']

    if id and name and request.method == "POST":
        users = db.Users.find_one({'id': id})
        if users is not None:
            resp = jsonify('User already exists')
            resp.status_code = 402
            return resp
        else:
            db.Users.insert_one({'id': id, 'name': name})
            resp = jsonify('User added successfully!')
            resp.status_code = 201
            return resp
    else:
        resp = jsonify('Bad Request')
        resp.status_code = 400
        return resp


if __name__ == "__main__":
    app.add_api('my_api.yaml', resolver=connexion.RestyResolver('api'))

    app.run(port=3000, debug=True)
Пример #8
0
def create_app():
    """Create VmaaS application and servers"""

    init_logging()

    LOGGER.info("Starting (version %s).", VMAAS_VERSION)
    LOGGER.info('Hotcache enabled: %s', os.getenv("HOTCACHE_ENABLED", "YES"))

    with open('webapp.spec.yaml', 'rb') as specfile:
        SPEC = yaml.safe_load(specfile)  # pylint: disable=invalid-name

    @web.middleware
    async def timing_middleware(request, handler, **kwargs):
        """ Middleware that handles timing of requests"""
        start_time = time.time()
        if asyncio.iscoroutinefunction(handler):
            res = await handler(request, **kwargs)
        else:
            res = handler(request, **kwargs)

        duration = (time.time() - start_time)
        # (0)  /(1) /(2) /(3)
        #     /api /v1  /updates
        const_path = '/'.join(request.path.split('/')[:4])
        REQUEST_TIME.labels(request.method, const_path).observe(duration)
        REQUEST_COUNTS.labels(request.method, const_path, res.status).inc()

        return res

    @web.middleware
    async def error_formater(request, handler, **kwargs):
        #pylint: disable=broad-except
        def build_error(detail, status):
            errors = {"detail": detail, "status": status}
            return {"errors": [errors]}

        res = await handler(request, **kwargs)

        try:
            if res.status >= 400:
                original_error = loads(res.body)
                better_error = build_error(original_error["detail"], original_error["status"])
                return web.json_response(better_error, status=res.status)
            return res
        except TypeError: # The error response is not made by connexion
            better_error = build_error(original_error, res.status)
            return web.json_response(better_error, status=res.status)
        except Exception as _:
            LOGGER.exception(_)
            return web.json_response(build_error("Internal server error", 500), status=500)


    app = connexion.AioHttpApp(__name__, options={
        'swagger_ui': True,
        'openapi_spec_path': '/openapi.json',
        'middlewares': [error_formater,
                        timing_middleware]
    })

    def metrics(request, **kwargs): #pylint: disable=unused-argument
        """Provide current prometheus metrics"""
        # /metrics API shouldn't be visible in the API documentation,
        # hence it's added here in the create_app step
        return web.Response(text=generate_latest().decode('utf-8'))

    async def on_prepare(request, response): #pylint: disable=unused-argument
        """Hook for preparing new responses"""
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type"

    app.app.on_response_prepare.append(on_prepare)
    app.app.router.add_get("/metrics", metrics)

    app.add_api(SPEC, resolver=connexion.RestyResolver('app'),
                validate_responses=False,
                strict_validation=False,
                base_path='/api',
                pass_context_arg_name='request'
                )

    BaseHandler.db_cache = Cache()
    load_cache_to_apis()

    return app
Пример #9
0
def create_app():
    """Create VmaaS application and servers"""

    init_logging()

    LOGGER.info("Starting (version %s).", VMAAS_VERSION)

    with open('webapp.spec.yaml', 'rb') as specfile:
        SPEC = yaml.safe_load(specfile)  # pylint: disable=invalid-name
    SPEC['info']['version'] = VMAAS_VERSION

    @web.middleware
    async def timing_middleware(request, handler, **kwargs):
        """ Middleware that handles timing of requests"""
        start_time = time.time()
        if asyncio.iscoroutinefunction(handler):
            res = await handler(request, **kwargs)
        else:
            res = handler(request, **kwargs)

        duration = (time.time() - start_time)
        # (0)  /(1) /(2) /(3)
        #     /api /v1  /updates
        const_path = '/'.join(request.path.split('/')[:4])
        REQUEST_TIME.labels(request.method, const_path).observe(duration)
        REQUEST_COUNTS.labels(request.method, const_path, res.status).inc()

        return res

    @web.middleware
    async def gzip_middleware(request, handler, **kwargs):
        """ Middleware that compress response using gzip"""
        res = await handler(request, **kwargs)
        header = 'Accept-Encoding'
        if header in request.headers and "gzip" in request.headers[header]:
            gzipped_body = gzip.compress(res.body,
                                         compresslevel=GZIP_COMPRESS_LEVEL)
            res.body = gzipped_body
            res.headers["Content-Encoding"] = "gzip"
        return res

    @web.middleware
    async def error_handler(request, handler, **kwargs):
        def format_error(detail, status):
            res = {}
            res["type"] = "about:blank"
            res["detail"] = detail
            res["status"] = status

            return res

        res = await handler(request, **kwargs)

        if res.status >= 400:
            body = loads(res.body)
            better_error = format_error(body, res.status)
            return web.json_response(better_error, status=res.status)

        return res

    middlewares = []
    if GZIP_RESPONSE_ENABLE:
        middlewares.append(gzip_middleware)
    middlewares.extend([error_handler, timing_middleware])

    app = connexion.AioHttpApp(__name__,
                               options={
                                   'swagger_ui': True,
                                   'openapi_spec_path': '/openapi.json',
                                   'middlewares': middlewares
                               })

    def metrics(request, **kwargs):  # pylint: disable=unused-argument
        """Provide current prometheus metrics"""
        # /metrics API shouldn't be visible in the API documentation,
        # hence it's added here in the create_app step
        return web.Response(text=generate_latest().decode('utf-8'))

    async def on_prepare(request, response):  # pylint: disable=unused-argument
        """Hook for preparing new responses"""
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type"

    app.app.on_response_prepare.append(on_prepare)
    app.app.router.add_get("/metrics", metrics)

    app.add_api(SPEC,
                resolver=connexion.RestyResolver('app'),
                validate_responses=False,
                strict_validation=False,
                base_path='/api',
                pass_context_arg_name='request')

    BaseHandler.db_cache = Cache()
    load_cache_to_apis()

    return app
Пример #10
0
from typing import Any, Dict
from pathlib import Path
import sentry_sdk
import os

from libs.database.engine import set_session_destroyer
from migration import migrate # 지우지마


if os.environ.get('SY_STAGE', '') == 'PRODUCTION':
    sentry_sdk.init("https://[email protected]/5233605")


app = connexion.App(__name__, specification_dir='admin/spec/', options={'swagger_path': swagger_ui_3_path})
set_session_destroyer(app.app)
CORS(app.app)

def get_bundled_specs(main_file: Path) -> Dict[str, Any]:
    parser = prance.ResolvingParser(str(main_file.absolute()),
                                    lazy = True, strict = True)
    parser.parse()
    return parser.specification


app.add_api(get_bundled_specs(Path("admin/spec/main.yaml")),
            resolver = connexion.RestyResolver("cms_rest_api"))
# base path 를 넣으면 GKE 에서도 제대로 될 거 같음!
# https://connexion.readthedocs.io/en/latest/routing.html


Пример #11
0
def create_app(specs):
    """Create VmaaS application and servers"""

    LOGGER.info("Starting (version %s).", VMAAS_VERSION)

    @web.middleware
    async def timing_middleware(request, handler, **kwargs):
        """ Middleware that handles timing of requests"""
        start_time = time.time()
        if asyncio.iscoroutinefunction(handler):
            res = await handler(request, **kwargs)
        else:
            res = handler(request, **kwargs)

        duration = (time.time() - start_time)
        # (0)  /(1) /(2) /(3)
        #     /api /v1  /updates
        const_path = '/'.join(request.path.split('/')[:4])
        REQUEST_TIME.labels(request.method, const_path).observe(duration)
        REQUEST_COUNTS.labels(request.method, const_path, res.status).inc()

        return res

    @web.middleware
    async def gzip_middleware(request, handler, **kwargs):
        """ Middleware that compress response using gzip"""
        res = await handler(request, **kwargs)
        header = 'Accept-Encoding'

        try:
            if res.body is not None and header in request.headers and "gzip" in request.headers[
                    header]:
                gzipped_body = gzip.compress(res.body,
                                             compresslevel=GZIP_COMPRESS_LEVEL)
                res.body = gzipped_body
                res.headers["Content-Encoding"] = "gzip"
                return res
        except (TypeError, AttributeError):
            LOGGER.warning("unable to gzip response '%s'", request.path)
        return res

    @web.middleware
    async def error_handler(request, handler, **kwargs):
        def format_error(detail, status):
            res = {}
            res["type"] = "about:blank"
            res["detail"] = detail
            res["status"] = status

            return res

        res = await handler(request, **kwargs)

        if res.status >= 400 and res.body:
            body = loads(res.body)
            better_error = format_error(body, res.status)
            return web.json_response(better_error, status=res.status)

        return res

    middlewares = []
    if GZIP_RESPONSE_ENABLE:
        middlewares.append(gzip_middleware)
    middlewares.extend([error_handler, timing_middleware])

    app = connexion.AioHttpApp(__name__,
                               options={
                                   'swagger_ui': True,
                                   'openapi_spec_path': '/openapi.json',
                                   'middlewares': middlewares
                               })

    def metrics(request, **kwargs):  # pylint: disable=unused-argument
        """Provide current prometheus metrics"""
        # /metrics API shouldn't be visible in the API documentation,
        # hence it's added here in the create_app step
        return web.Response(text=generate_latest().decode('utf-8'))

    def dummy_200(request, **kwargs):  # pylint: disable=unused-argument
        """Dummy endpoint returning 200"""
        return web.Response()

    async def on_prepare(request, response):  # pylint: disable=unused-argument
        """Hook for preparing new responses"""
        response.headers["Access-Control-Allow-Origin"] = "*"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type"
        response.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS, POST'

    app.app.on_response_prepare.append(on_prepare)
    app.app.router.add_get("/metrics", metrics)
    app.app.router.add_get("/healthz", HealthHandler.get)
    app.app.router.add_route("OPTIONS", "/api/v3/cves", dummy_200)

    for route, spec in specs.items():
        app.add_api(spec,
                    resolver=connexion.RestyResolver('app'),
                    validate_responses=False,
                    strict_validation=False,
                    base_path=route,
                    pass_context_arg_name='request',
                    arguments={'vmaas_version': VMAAS_VERSION})

    BaseHandler.db_cache = Cache()
    load_cache_to_apis()

    return app
Пример #12
0
import connexion
from api import config
from api.db import DB

app = connexion.FlaskApp(__name__)

app.add_api(
    "swagger.yaml",
    resolver=connexion.RestyResolver("customer_review.api"),
    strict_validation=True,
    validate_responses=True,
)
app = app.app

app.config.update(**config.MYSQL.params())
DB.init_app(app)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
Пример #13
0
import connexion

app = connexion.FlaskApp(__name__)
app.add_api('swagger.yml',
            resolver=connexion.RestyResolver('primer.api'),
            strict_validation=True,
            validate_responses=True)

if __name__ == '__main__':
    app.run()
Пример #14
0
from models.db import db
import models.utils as db_utils

APP_DIR = '/home/scairns/code/bairng/server/app/openapi'
OPENAPI_DIR = APP_DIR
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/bairng_server.db'

connex_app = connexion.FlaskApp(__name__, specification_dir=OPENAPI_DIR)
app = connex_app.app
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.secret_key = os.environ.get('BAIRNG_SECRET_KEY')  #'dev' in dev

login_manager = LoginManager()
login_manager.init_app(app)

connex_app.add_api('bairng_api.yaml', resolver=connexion.RestyResolver('api'))
app.register_blueprint(api.api, url_prefix='/api')
app.register_blueprint(auth.auth_api, url_prefix='/auth')

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--debug",
                        dest='debug',
                        help="run in debug mode",
                        action="store_true",
                        default=0)
    args = parser.parse_args()
    app.app_context().push()

    db_utils.init_db(app)