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
def configure_error_handlers(app: FlaskApp): app.add_error_handler(401, unauthorized_error_handler) app.add_error_handler(403, authorization_error_handler) app.add_error_handler(IncorrectAuthorizeArgumentError, authorization_error_handler) app.add_error_handler(500, internal_error_handler) app.add_error_handler(DoesNotExist, not_found_error) return app
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
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])
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
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
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 })
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
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_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 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
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
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
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
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
def create_app(app_name, config_name): config_obj = get_config(config_name) cnnx_app = FlaskApp(app_name) flask_app = cnnx_app.app flask_app.config.from_object(config_obj) flask_app.app_context().push() register_logger(flask_app) register_extensions(flask_app) register_api(cnnx_app) return flask_app
def register_errorhandlers(app: Flask, connex: FlaskApp): """Register error handlers.""" connex.add_error_handler(BadRequest, v1.handle_http_exception(JSONRPCInvalidRequest)) @app.after_request def transform(response: Response) -> Response: if response.status_code != HTTPStatus.OK: jsonrpc = jsonify({ "jsonrpc": "2.0", "id": None, "error": { "code": -32602, "message": "Oops", "data": response.json } }) jsonrpc.status_code = response.status_code return jsonrpc else: return response
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
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
def create_app(config_name): config_obj = get_config(config_name) swagger_dir = op.abspath(op.join(op.dirname(__name__), 'api_specs')) cnnx_app = FlaskApp(__name__, specification_dir=swagger_dir) flask_app = cnnx_app.app flask_app.config.from_object(config_obj) flask_app.app_context().push() register_logger(flask_app) register_extensions(flask_app) register_api(cnnx_app) return flask_app
def create_app(config_name): config_obj = get_config(config_name) swagger_dir = op.abspath(op.join(op.dirname(__name__), 'api_specs')) print(swagger_dir) cnnx_app = FlaskApp(__name__, specification_dir=swagger_dir) flask_app = cnnx_app.app flask_app.config.from_object(config_obj) flask_app.app_context().push() login_manager.init_app(flask_app) flask_app.register_blueprint(client, url_prefix='/') register_logger(flask_app) register_extensions(flask_app) register_api(cnnx_app) return flask_app
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)
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
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_") +
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
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
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
"""ConnexionApp and SQLAlchemy objects instantiation""" from connexion import FlaskApp import os from config import app_config from flask_sqlalchemy import SQLAlchemy connexion_app: FlaskApp = FlaskApp(__name__) connexion_app.app.config.from_object(app_config[os.getenv('APP_SETTINGS') or 'default']) db: SQLAlchemy = SQLAlchemy(connexion_app.app)
def create_app(package_name): app = FlaskApp(__name__, specification_dir='./') app.add_api('openapi.yaml') return app