예제 #1
0
def create_app(config: Config = CONFIG) -> Flask:
    application = connexion.FlaskApp("Jobs4You",
                                     specification_dir="app/openapi")

    application.app.config.from_object(config)

    application.add_api(
        "health.yml",
        base_path="/api/health",
        resolver=MethodViewResolver("app.api"),
        validate_responses=True,
        options={"swagger_ui": False},
    )

    application.add_api(
        "jobs.yml",
        base_path="/api",
        resolver=MethodViewResolver("app.api"),
        validate_responses=True,
        options={"swagger_ui": True},
    )

    for exc in default_exceptions:
        application.app.register_error_handler(exc, generic_error_handler)

    DB.init_app(application.app)

    CACHE.init_app(application.app)

    admin_setup(application.app)

    return application.app
예제 #2
0
def create_app(env):
    from db import mongo

    connex_app = connexion.FlaskApp(__name__,
                                    specification_dir='openapi/',
                                    resolver=MethodViewResolver('api'))
    connex_app.add_api('openapi.yaml')

    if env:
        connex_app.app.config['FLASK_ENV'] = env

    # Load secret_key from .env
    connex_app.app.secret_key = os.getenv('SECRET_KEY', 'default_secret_key')

    # Load default settings
    connex_app.app.config.from_object('config.BaseConfig')

    # Load specific settings depending on environment
    if env == 'testing':
        connex_app.app.config.from_object('config.TestingConfig')

    if env == 'development':
        from flask_debugtoolbar import DebugToolbarExtension
        DebugToolbarExtension(connex_app.app)

    # Initializing mongo
    mongo.init_app(connex_app.app)

    # Adding validation error handler
    def handle_validation_error(e):
        return Response(json.dumps(e.messages),
                        400,
                        mimetype='application/json')

    connex_app.app.register_error_handler(ValidationError,
                                          handle_validation_error)

    # Initializing flask_login
    login_manager = LoginManager()
    login_manager.init_app(connex_app.app)
    login_manager.login_view = 'auth.login'
    # connex_app.app.login_manager = login_manager

    @login_manager.user_loader
    def load_user(user_id):
        from models import User
        return User(**mongo.db.users.find_one({'_id': ObjectId(user_id)}))

    # Adding auth views
    from views import auth
    connex_app.app.register_blueprint(auth.bp)

    # Adding custom management commands
    from commands import (create_indexes, generate_users,
                          generate_transaction_for_user)
    connex_app.app.cli.add_command(create_indexes)
    connex_app.app.cli.add_command(generate_users)
    connex_app.app.cli.add_command(generate_transaction_for_user)

    return connex_app.app
def test_methodview_resolve_x_router_controller_without_operation_id():
    operation = OpenAPIOperation(api=None,
                          method='GET',
                          path='/hello/{id}',
                          path_parameters=[],
                          operation={'x-openapi-router-controller': 'fakeapi.Example_method'},
                          app_security=[],
                          components=COMPONENTS,
                          resolver=MethodViewResolver('fakeapi'))
    assert operation.operation_id == 'fakeapi.Example_methodView.get'
예제 #4
0
def create_app():
    '''
  application factory
  '''
    app = connexion.FlaskApp(__name__,
                             specification_dir='openapi/',
                             debug=True)

    # load api
    app.add_api('base.yaml',
                options={"swagger_ui": True},
                arguments={'title': 'MethodViewResolver ipapi'},
                resolver=MethodViewResolver('ipapi'),
                strict_validation=True,
                validate_responses=False)

    # set logging
    app.app.logger.setLevel(LOGLEVEL)
    with app.app.app_context():
        log.i(f'Logging configured at level {LOGLEVEL}')

    @app.app.teardown_appcontext
    def disconnect_db(e):
        '''
    disconnects db at the end of request
    '''
        if hasattr(g, 'rid'):
            rid = str(g.rid)
            del g.rid
            log.d((rid, str(datetime.now()), 'disconnect_db',
                   f'removed request {rid}'))
        else:
            rid = None
        if hasattr(g, 'ipapi'):
            for i in base.collections():
                '''
        g[i] = g.ipapi[i] throws exception
        TypeError: '_AppCtxGlobals' object does not
        support item assignment
        '''
                g.pop(i, None)
                log.d((rid, str(datetime.now()), 'disconnect_db',
                       f'disconnect collection {i}'))
            g.ipapi.client.close()
            del g.ipapi
            log.d((rid, str(datetime.now()), 'disconnect_db',
                   'disconnect database ipapi'))
        #else:
        #log.e((rid, str(datetime.now()), 'disconnect_db',
        #'ipapi not connected (please ignore during database_initialization
        #and openapi/ui manipulation)'))

    return app
def test_methodview_resolve_with_default_module_name_lowercase_verb():
    operation = OpenAPIOperation(
        api=None,
        method='get',
        path='/example_method/{id}',
        path_parameters=[],
        operation={},
        app_security=[],
        components=COMPONENTS,
        resolver=MethodViewResolver('fakeapi')
    )
    assert operation.operation_id == 'fakeapi.Example_methodView.get'
def test_methodview_resolve_with_default_module_name_can_resolve_api_root():
    operation = OpenAPIOperation(
        api=None,
        method='GET',
        path='/',
        path_parameters=[],
        operation={},
        app_security=[],
        components=COMPONENTS,
        resolver=MethodViewResolver('fakeapi.Example_method',)
    )
    assert operation.operation_id == 'fakeapi.Example_methodView.get'
def test_methodview_resolve_with_default_module_name_will_translate_dashes_in_resource_name():
    operation = OpenAPIOperation(
        api=None,
        method='GET',
        path='/example-method',
        path_parameters=[],
        operation={},
        app_security=[],
        components=COMPONENTS,
        resolver=MethodViewResolver('fakeapi')
    )
    assert operation.operation_id == 'fakeapi.Example_methodView.search'
예제 #8
0
파일: app.py 프로젝트: panda2134/Flask-Blog
def create_app():
    con = FlaskApp(__name__, specification_dir='vue-blog-api')
    # con.add_api('api.yaml', resolver=MethodViewResolver('views'), validate_responses=True)
    con.add_api('api.yaml', resolver=MethodViewResolver('views'))

    app = con.app
    app.config.from_pyfile('config.py')
    CORS(app, resources='/api/*', supports_credentials=True)
    with app.app_context():
        models.init_models(app)

    return app
예제 #9
0
def add_api(app: connexion.FlaskApp) -> connexion.FlaskApp:
    """
    Adding swagger specification files
    Endpoint CBV must end on "View"
    https://github.com/zalando/connexion/blob/master/examples/openapi3/methodresolver/app.py
    """
    app.add_api(
        "swagger.yml",
        resolver=MethodViewResolver("api"),
        strict_validation=True,
    )
    return app
def test_methodview_resolve_with_default_module_name_will_resolve_resource_root_post_as_post():
    operation = OpenAPIOperation(
        api=None,
        method='POST',
        path='/example_method',
        path_parameters=[],
        operation={},
        app_security=[],
        components=COMPONENTS,
        resolver=MethodViewResolver('fakeapi')
    )
    assert operation.operation_id == 'fakeapi.Example_methodView.post'
def test_methodview_resolve_with_default_module_name_and_x_router_controller_will_resolve_resource_root_get_as_search():
    operation = OpenAPIOperation(
        api=None,
        method='GET',
        path='/hello',
        path_parameters=[],
        operation={
            'x-openapi-router-controller': 'fakeapi.example_method',
        },
        app_security=[],
        components=COMPONENTS,
        resolver=MethodViewResolver('fakeapi')
    )
    assert operation.operation_id == 'fakeapi.Example_methodView.search'
def test_methodview_resolve_operation_id():
    operation = OpenAPIOperation(
        api=None,
        method='GET',
        path='endpoint',
        path_parameters=[],
        operation={
            'operationId': 'fakeapi.hello.post_greeting',
        },
        app_security=[],
        components=COMPONENTS,
        resolver=MethodViewResolver('fakeapi')
    )
    assert operation.operation_id == 'fakeapi.hello.post_greeting'
def test_methodview_resolve_x_router_controller_with_operation_id():
    operation = OpenAPIOperation(
        api=None,
        method='GET',
        path='endpoint',
        path_parameters=[],
        operation={
            'x-openapi-router-controller': 'fakeapi.Example_methodView',
            'operationId': 'post_greeting',
        },
        app_security=[],
        components=COMPONENTS,
        resolver=MethodViewResolver('fakeapi')
    )
    assert operation.operation_id == 'fakeapi.Example_methodView.post_greeting'
예제 #14
0
def create_app(test_config=None):
    # create and configure the app
    connexionApp = connexion.FlaskApp(__name__,
                                      specification_dir='openapi/',
                                      debug=True)
    app = connexionApp.app

    app.json_encoder = CustomJSONEncoder  # custom json decoder
    # added to decode mongoDB id

    app.config.from_mapping(SECRET_KEY='dev_secret_3fkj$s',
                            DATABASE_HOST="mongodb://*****:*****@app.route('/ping')
    def ping():
        return 'Sharity app is up running :)'

    return app
예제 #15
0
def create_app(config=Config):
    """Generate configurable app instance"""
    connex_app = connexion.App(__name__, specification_dir="openapi")
    connex_app.add_api("notavel-api.yml",
                       resolver=MethodViewResolver("notavel.views"))

    # Get the underlying flask app instance from connex_app:
    app = connex_app.app
    app.config.from_object(config())

    # Initialize plugins:
    db.init_app(app)
    ma.init_app(app)

    with app.app_context():

        db.create_all()

    return app
예제 #16
0
import os

import connexion
from connexion.resolver import MethodViewResolver

app = connexion.FlaskApp(__name__, port=5000, specification_dir='openapi/')
app.add_api('openapi.yml',
            strict_validation=True,
            validate_responses=True,
            resolver=MethodViewResolver('views'))
app.app.config['IMGS_DIR'] = os.path.join('static', 'imgs')
app.app.config['CM_CONFIG'] = 'cats_dogs_128'
예제 #17
0
import os
from logging.config import fileConfig
import connexion
from connexion.resolver import MethodViewResolver

fileConfig(os.path.join(os.path.abspath(os.path.dirname(__file__)),
                        'config/logging.cfg'),
           disable_existing_loggers=False)

# Create the application instance
app = connexion.App(__name__, specification_dir='openapi')
app.app.config.from_pyfile(os.getenv('APP_SETTINGS_PATH') or 'config/dev.cfg')

options = {"swagger_ui": True}
app.add_api('api.yml', options=options, resolver=MethodViewResolver('api'))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080)
예제 #18
0
파일: server.py 프로젝트: litios/Drogon
import connexion
from connexion.resolver import MethodViewResolver

# Create the application instance
app = connexion.FlaskApp(__name__, specification_dir='./')

# Read the swagger.yml file to configure the endpoints
app.add_api('api.yml', resolver=MethodViewResolver('routes'))

# If we're running in stand alone mode, run the application
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
예제 #19
0
#!/usr/bin/env python
import logging

import connexion
from connexion.resolver import MethodViewResolver

logging.basicConfig(level=logging.INFO)

if __name__ == '__main__':
    app = connexion.FlaskApp(__name__, specification_dir='openapi/', debug=True)

    options = {"swagger_ui": True}
    app.add_api('pets-api.yaml',
                options=options,
                arguments={'title': 'MethodViewResolver Example'},
                resolver=MethodViewResolver('api'), strict_validation=True, validate_responses=True )
    app.run(port=9090)
예제 #20
0
파일: app.py 프로젝트: ArkadioG/pygda56
"""Main entrance to application"""

import connexion
from connexion.resolver import MethodViewResolver

options = {'swagger_ui': True}

# if you don't install ui, you have to disable it
app = connexion.FlaskApp(__name__, port=8080)
app.add_api(
    'swagger.yaml',
    validate_responses=True,
    options=options,
    # custom resolver - no need to declare operationId in the specs!
    resolver=MethodViewResolver(default_module_name='documents',
                                collection_endpoint_name='get_all'))

if __name__ == '__main__':
    app.run(debug=True)