def test_security_over_inexistent_endpoints(oauth_requests, secure_api_spec_dir):
    app1 = FlaskApp(__name__, port=5001, specification_dir=secure_api_spec_dir,
                    swagger_ui=False, debug=True, auth_all_paths=True)
    app1.add_api('swagger.yaml')
    assert app1.port == 5001

    app_client = app1.app.test_client()
    headers = {"Authorization": "Bearer 300"}
    get_inexistent_endpoint = app_client.get('/v1.0/does-not-exist-invalid-token',
                                             headers=headers)  # type: flask.Response
    assert get_inexistent_endpoint.status_code == 401
    assert get_inexistent_endpoint.content_type == 'application/problem+json'

    headers = {"Authorization": "Bearer 100"}
    get_inexistent_endpoint = app_client.get('/v1.0/does-not-exist-valid-token',
                                             headers=headers)  # type: flask.Response
    assert get_inexistent_endpoint.status_code == 404
    assert get_inexistent_endpoint.content_type == 'application/problem+json'

    get_inexistent_endpoint = app_client.get('/v1.0/does-not-exist-no-token')  # type: flask.Response
    assert get_inexistent_endpoint.status_code == 401

    swagger_ui = app_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui.status_code == 401

    headers = {"Authorization": "Bearer 100"}
    post_greeting = app_client.post('/v1.0/greeting/rcaricio', data={}, headers=headers)  # type: flask.Response
    assert post_greeting.status_code == 200

    post_greeting = app_client.post('/v1.0/greeting/rcaricio', data={})  # type: flask.Response
    assert post_greeting.status_code == 401
Exemple #2
0
def test_swagger_json_api(simple_api_spec_dir):
    """ Verify the swagger.json file is returned for default setting passed to api. """
    app = FlaskApp(__name__, 5001, simple_api_spec_dir, debug=True)
    app.add_api('swagger.yaml')

    app_client = app.app.test_client()
    swagger_json = app_client.get('/v1.0/swagger.json')  # type: flask.Response
    assert swagger_json.status_code == 200
Exemple #3
0
def test_no_swagger_json_api(simple_api_spec_dir):
    """ Verify the swagger.json file is not returned when set to False when adding api. """
    app = FlaskApp(__name__, 5001, simple_api_spec_dir, debug=True)
    app.add_api('swagger.yaml', swagger_json=False)

    app_client = app.app.test_client()
    swagger_json = app_client.get('/v1.0/swagger.json')  # type: flask.Response
    assert swagger_json.status_code == 404
Exemple #4
0
def _setup_api(connexion_app: connexion.FlaskApp, debug: bool,
               swagger_ui: bool):
    """Setup the rest API within the Flask app."""
    connexion_app.add_api(
        specification='swagger.yaml',
        arguments={'title': 'This is the HTTP API for tackle.'},
        options={
            "debug": debug,
            "swagger_ui": swagger_ui
        })
Exemple #5
0
def build_app_from_fixture(api_spec_folder, **kwargs):
    debug = True
    if 'debug' in kwargs:
        debug = kwargs['debug']
        del (kwargs['debug'])
    app = FlaskApp(__name__,
                   5001,
                   FIXTURES_FOLDER / api_spec_folder,
                   debug=debug)
    app.add_api('swagger.yaml', **kwargs)
    return app
Exemple #6
0
def test_app_with_relative_path(simple_api_spec_dir):
    # Create the app with a realative path and run the test_app testcase below.
    app = FlaskApp(__name__,
                   5001,
                   '..' / simple_api_spec_dir.relative_to(TEST_FOLDER),
                   debug=True)
    app.add_api('swagger.yaml')

    app_client = app.app.test_client()
    get_bye = app_client.get('/v1.0/bye/jsantos')  # type: flask.Response
    assert get_bye.status_code == 200
    assert get_bye.data == b'Goodbye jsantos'
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
Exemple #8
0
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
def new_wrapper() -> FlaskApp:
    """
    Factory function to build a Connexion wrapper to manage the Flask
    application in which QuantumLeap runs.

    :return: the Connexion wrapper.
    """
    wrapper = FlaskApp(__name__, specification_dir=SPEC_DIR)
    wrapper.add_api(
        SPEC,
        arguments={'title': 'QuantumLeap V2 API'},
        pythonic_params=True,
        # validate_responses=True, strict_validation=True
    )
    return wrapper
Exemple #10
0
def create_app(config_object: Config = ProdConfig) -> FlaskApp:
    """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.

    :param config_object: The configuration object to use.
    """

    # TODO: Validate config, abort the app if it's not valid
    connex = FlaskApp(__name__.split('.')[0],
                      specification_dir=config_object.SPECIFICATION_DIR,
                      debug=config_object.DEBUG)
    api = connex.add_api(config_object.API_SPEC,
                         validate_responses=config_object.VALIDATE_RESPONSES,
                         resolver_error=BadRequest)  # type: FlaskApi
    app = connex.app  # type: Flask
    app.logger.setLevel(config_object.LOG_LEVEL)

    log_sysinfo(app, config_object)
    register_config(app, connex, config_object)
    register_extensions(app, config_object)
    register_errorhandlers(app, connex)
    register_shellcontext(connex)
    register_commands(app)

    app.logger.info("Created Flask app %s", app.name)

    return connex
Exemple #11
0
def test_no_swagger_ui(simple_api_spec_dir):
    app = FlaskApp(__name__,
                   5001,
                   simple_api_spec_dir,
                   swagger_ui=False,
                   debug=True)
    app.add_api('swagger.yaml')

    app_client = app.app.test_client()
    swagger_ui = app_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui.status_code == 404

    app2 = FlaskApp(__name__, 5001, simple_api_spec_dir, debug=True)
    app2.add_api('swagger.yaml', swagger_ui=False)
    app2_client = app2.app.test_client()
    swagger_ui2 = app2_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui2.status_code == 404
Exemple #12
0
class Application(object):
    def __init__(self, port: int):
        logging.basicConfig(level=logging.INFO)
        self._port = port
        self._app = FlaskApp(__name__,
                             port=self._port,
                             specification_dir='swagger/')
        self._app.add_api('raaspy.yaml')
        FlaskInjector(app=self._app.app, modules=[self.configure])

    @classmethod
    def configure(cls, binder: Binder):
        return binder

    @property
    def app(self):
        return self._app
Exemple #13
0
def test_security_over_inexistent_endpoints(oauth_requests,
                                            secure_api_spec_dir):
    app1 = FlaskApp(__name__,
                    port=5001,
                    specification_dir=secure_api_spec_dir,
                    swagger_ui=False,
                    debug=True,
                    auth_all_paths=True)
    app1.add_api('swagger.yaml')
    assert app1.port == 5001

    app_client = app1.app.test_client()
    headers = {"Authorization": "Bearer 300"}
    get_inexistent_endpoint = app_client.get(
        '/v1.0/does-not-exist-invalid-token',
        headers=headers)  # type: flask.Response
    assert get_inexistent_endpoint.status_code == 401
    assert get_inexistent_endpoint.content_type == 'application/problem+json'

    headers = {"Authorization": "Bearer 100"}
    get_inexistent_endpoint = app_client.get(
        '/v1.0/does-not-exist-valid-token',
        headers=headers)  # type: flask.Response
    assert get_inexistent_endpoint.status_code == 404
    assert get_inexistent_endpoint.content_type == 'application/problem+json'

    get_inexistent_endpoint = app_client.get(
        '/v1.0/does-not-exist-no-token')  # type: flask.Response
    assert get_inexistent_endpoint.status_code == 401

    swagger_ui = app_client.get('/v1.0/ui/')  # type: flask.Response
    assert swagger_ui.status_code == 401

    headers = {"Authorization": "Bearer 100"}
    post_greeting = app_client.post('/v1.0/greeting/rcaricio',
                                    data={},
                                    headers=headers)  # type: flask.Response
    assert post_greeting.status_code == 200

    post_greeting = app_client.post('/v1.0/greeting/rcaricio',
                                    data={})  # type: flask.Response
    assert post_greeting.status_code == 401
Exemple #14
0
def test_dict_as_yaml_path(simple_api_spec_dir):

    swagger_yaml_path = simple_api_spec_dir / 'swagger.yaml'

    with swagger_yaml_path.open(mode='rb') as swagger_yaml:
        contents = swagger_yaml.read()
        try:
            swagger_template = contents.decode()
        except UnicodeDecodeError:
            swagger_template = contents.decode('utf-8', 'replace')

        swagger_string = jinja2.Template(swagger_template).render({})
        specification = yaml.safe_load(swagger_string)  # type: dict

    app = FlaskApp(__name__, 5001, simple_api_spec_dir, debug=True)
    app.add_api(specification)

    app_client = app.app.test_client()
    swagger_json = app_client.get('/v1.0/swagger.json')  # type: flask.Response
    assert swagger_json.status_code == 200
Exemple #15
0
def create_wsgi():
    application = FlaskApp(__name__)
    config = settings.load_config((
        settings.FlaskSettings,
        settings.SentrySetting,
    ))
    application.app.config.from_object(config)
    CORS(application.app)

    application.add_api(specification='v1/openapi.yaml',
                        resolver=VersionResolver('app.http.v1.handlers'),
                        strict_validation=True,
                        validate_responses=True)

    @application.app.teardown_appcontext
    def shutdown_session(exception):
        models.session.remove()

    sentry_init(dsn=config.SENTRY_DSN,
                integrations=[sentry_flask.FlaskIntegration()])

    return application
Exemple #16
0
    def create_connexion_app(self):
        app = FlaskApp('fusillade')
        # The Flask/Connection app's logger has its own multi-line formatter and configuration. Rather than suppressing
        # it we let it do its thing, give it a special name and only enable it if Fusillade_DEBUG > 1.
        # Most of the Fusillade web app's logging is done through the FusilladeChaliceApp.app logger not the Flask
        # app's logger.
        app.app.logger_name = 'fus.api'
        debug = Config.log_level() > 1
        app.app.debug = debug
        app.app.logger.info('Flask debug is %s.',
                            'enabled' if debug else 'disabled')

        resolver = RestyResolver("fusillade.api",
                                 collection_endpoint_name="list")
        self.connexion_apis.append(
            app.add_api(self.swagger_spec_path,
                        resolver=resolver,
                        validate_responses=True,
                        arguments=os.environ,
                        options={"swagger_path": self.swagger_spec_path}))
        self.connexion_apis.append(
            app.add_api(self.swagger_internal_spec_path,
                        validate_responses=True))
        return app
Exemple #17
0
def app():
    app = FlaskApp(__name__, 5001, SPEC_FOLDER, debug=True)
    app.add_api('api.yaml', validate_responses=True)
    return app
def create_app():
    app = FlaskApp(__name__, specification_dir="./")
    app.add_api("openapi.yaml")
    return app
Exemple #19
0
import argparse
import os
import subprocess
import sys

from connexion import FlaskApp as Flask

specification_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, specification_dir)

# Create the application instance
app = Flask(__name__, specification_dir=specification_dir)

# Read the open api .yml file to configure the
# endpoints
# TODO allow for specifying multiple swagger files
app.add_api(os.path.join("openapi", "swagger.yml"))

port = int(os.environ.get("SMARTNOISE_SERVICE_PORT", 5000))
os.environ["SMARTNOISE_SERVICE_PORT"] = str(port)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=port)

# flask app
app = app.app
Exemple #20
0
from connexion import FlaskApp

app = FlaskApp(__name__)
app.add_api("spec/openapi.yaml")

app.run()
def create_app(package_name):
    app = FlaskApp(__name__, specification_dir='./')
    app.add_api('openapi.yaml')

    return app
Exemple #22
0
import os
from hashlib import sha256
from flask import redirect, render_template, send_from_directory, request, url_for, session, Response
from connexion import FlaskApp
from flask_pymongo import PyMongo
from flask_dance.contrib.github import make_github_blueprint, github

from pymongo import ASCENDING
from pymongo.errors import PyMongoError
from bson import ObjectId

from .plot import bp as plot_bp
from .helpers import MongoJSONEncoder, ObjectIdConverter

app = FlaskApp(__name__)
app.add_api("api.yaml")
app.app.secret_key = os.environ['FLASK_SECRET_KEY']
app.app.register_blueprint(plot_bp)
app.app.json_encoder = MongoJSONEncoder
app.app.url_map.converters['objectid'] = ObjectIdConverter


def dev():
    """Detect dev environment"""
    return os.environ.get("AWS_EXECUTION_ENV") is None


GITHUB_OAUTH_CLIENT_ID = os.environ[("" if dev() else "PROD_") +
                                    "GITHUB_OAUTH_CLIENT_ID"]
GITHUB_OAUTH_CLIENT_SECRET = os.environ[("" if dev() else "PROD_") +
                                        "GITHUB_OAUTH_CLIENT_SECRET"]
Exemple #23
0
def create_app():
    app = FlaskApp(__name__, specification_dir="openapi/")
    CORS(app.app, resources={r"*": {"origins": "http://localhost:8080"}}, supports_credentials=True)
    app.add_api("api.yaml")
    return app
Exemple #24
0
def create_app(testing=False):
    """
    Creates an instance of the Image Search app.
    """

    # create connexion app
    connexion_options = {'swagger_path': swagger_ui_3_path}
    connexion_app = FlaskApp(__name__,
                             specification_dir='./swagger',
                             options=connexion_options)
    connexion_app.add_api('swagger.yml')

    # get a reference to underlying flask app
    app = connexion_app.app

    # do this because we want to allow instance configs
    app.config.root_path = app.instance_path

    # load default config
    app.config.from_object('config.Default')

    # load instance config (if present)
    app.config.from_pyfile('config.py', silent=True)

    # load test config (if testing)
    if testing:
        app.config.from_object('config.Test')

    app.config.update({'TESTING': testing})

    # load environment variables (if present)
    app.config.update({
        'DEBUG':
        os.environ.get('DEBUG',
                       str(app.config.get('DEBUG'))).lower() == 'true',
        'ENV':
        os.environ.get('ENV', app.config.get('ENV')),
        'GOOGLE_API_KEY':
        os.environ.get('GOOGLE_API_KEY', app.config.get('GOOGLE_API_KEY')),
        'GOOGLE_CSE_ID':
        os.environ.get('GOOGLE_CSE_ID', app.config.get('GOOGLE_CSE_ID')),
        'MONGODB_DB':
        os.environ.get('MONGODB_DB', app.config.get('MONGODB_DB')),
        'MONGODB_HOST':
        os.environ.get('MONGODB_HOST', app.config.get('MONGODB_HOST')),
        'MONGODB_PASSWORD':
        os.environ.get('MONGODB_PASSWORD', app.config.get('MONGODB_PASSWORD')),
        'MONGODB_PORT':
        int(os.environ.get('MONGODB_PORT', app.config.get('MONGODB_PORT'))),
        'MONGODB_USERNAME':
        os.environ.get('MONGODB_USERNAME', app.config.get('MONGODB_USERNAME')),
        'SECRET_KEY':
        os.environ.get('SECRET_KEY', app.config.get('SECRET_KEY')),
        'SERVER_NAME':
        os.environ.get('SERVER_NAME', app.config.get('SERVER_NAME')),
        'SESSION_COOKIE_DOMAIN':
        os.environ.get('SESSION_COOKIE_DOMAIN',
                       app.config.get('SESSION_COOKIE_DOMAIN'))
    })

    # init extensions
    mongoengine.init_app(app)

    # disable strict trailing slashes e.g. so /latest and /latest/ both resolve to same endpoint
    app.url_map.strict_slashes = False

    # register blueprints
    from imagesearch.blueprints import home
    app.register_blueprint(home)

    # disable caching when debugging
    if app.debug:

        @app.after_request
        def after_request(response):
            response.headers[
                'Cache-Control'] = 'no-cache, no-store, must-revalidate'
            response.headers['Expires'] = 0
            response.headers['Pragma'] = 'no-cache'
            return response

    return app
Exemple #25
0
def test_add_api_with_function_resolver_function_is_wrapped(
        simple_api_spec_dir):
    app = FlaskApp(__name__, specification_dir=simple_api_spec_dir)
    api = app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar'))
    assert api.resolver.resolve_function_from_operation_id('faux')(
        'bah') == 'bar'
def post_hello(body):
    if not body:
        return problem(status=400,
                       title="Bad Request",
                       detail="Body should be a json object.")
    print(f"body, {body.__class__}")
    return {"UNEXPECTED_STRING": 1}


def configure_logger(log_config="logging.yaml"):
    """Configure the logging subsystem."""
    if not isfile(log_config):
        return basicConfig()

    from logging.config import dictConfig

    with open(log_config) as fh:
        log_config = yaml_load(fh)
        return dictConfig(log_config)


if __name__ == "__main__":
    configure_logger()
    app = FlaskApp("hello",
                   port=8443,
                   specification_dir=dirname(__file__),
                   options={"swagger_ui": True})
    app.add_api("simple.yaml", validate_responses=True, strict_validation=True)
    app.run(ssl_context="adhoc", debug=True)
from flask import Flask
from flask import request
from flask.views import View
from connexion import FlaskApp


class SimpleTest(View):
    def dispatch_request(self):
        return 'foo'


get_test = SimpleTest.as_view('get_test')

if __name__ == '__main__':
    options = {"swagger_ui": True}

    app = FlaskApp(__name__, options=options)
    app.add_api('openapi.yaml')
    app.run()
Exemple #28
0
from connexion import FlaskApp
from connexion.resolver import RestyResolver

app = FlaskApp(__name__, specification_dir='openapi/')
app.add_api('openapi.yml', resolver=RestyResolver('amf.routes'))
app = app.app
Exemple #29
0
from os import environ
from connexion import FlaskApp
from mongoengine import connect
from modules.error_handlers import configure_error_handlers

app_is_debug_mode = environ['FLASK_IS_DEBUG'] == 'True'
app_use_reloader = environ['FLASK_USE_RELOADER'] == 'True'

app = FlaskApp(__name__, specification_dir='swagger/')
app = configure_error_handlers(app=app)
app.add_api('timers_api_documentation.yaml', strict_validation=True)

if __name__ == '__main__':
    connect(environ['MONGO_DATABASE_NAME'],
            host=environ['MONGO_DATABASE_SERVER'],
            port=int(environ['MONGO_DATABASE_PORT']))
    app.run(port=int(environ['FLASK_DEFAULT_PORT']),
            debug=app_is_debug_mode,
            use_reloader=app_use_reloader,
            threaded=False)
            'attachment_filename': attachment_filename,
            'mime_type': mime_type
        }))

    return send_file(filename,
                     mimetype=mime_type,
                     as_attachment=download,
                     attachment_filename=attachment_filename)


###########################################
# BEGIN API
###########################################

app = FlaskApp(__name__, options={})
app.add_api('openapi.yaml', base_path=ENV.BASE_HREF)
CORS(app.app)
application = app.app


@application.teardown_appcontext
def shutdown_session(exception: Exception = None) -> None:
    """ Boilerplate connexion code """
    database_provider.db_session.remove()


@application.errorhandler(SBNSISException)
def handle_sbnsis_error(error: Exception):
    """Log errors."""
    get_logger().exception('SBS Survey Image Service error.')
    return str(error), getattr(error, 'code', 500)
Exemple #31
0
 def provide_flask_injected(self, api: TestAPIInterface, injector: Injector) -> FlaskApp:
   spec = generate_spec(TestAPIInterface)
   flask_app = FlaskApp(api.__name__)
   flask_app.add_api(spec, resolver=ModuleResolver(api))
   FlaskInjector(app=flask_app.app, injector=injector)
   return flask_app.app