#!/usr/bin/env python3 import connexion import logging from injector import Binder from flask_injector import FlaskInjector from connexion.resolver import RestyResolver from flask_cors import CORS from services.raf import RafCalculator # Setup the binding for the raf calculator def configure(binder: Binder) -> Binder: binder.bind(RafCalculator, RafCalculator()) # Logging config if __name__ == '__main__': logging.basicConfig(level=logging.INFO) app = connexion.App(__name__, specification_dir='swagger/') app.add_api('raf.yaml', resolver=RestyResolver('api')) FlaskInjector(app=app.app, modules=[configure]) CORS(app.app) app.run(port=8080)
lazy=True, strict=False) parser.parse() return parser.specification # Use OpenAPI Swagger page, and redirct SwaggerUI to root options = {'swagger_path': swagger_ui_3_path, "swagger_url": ""} # Note this app is a wrapper around FlaskAPP, use app.app to access # the actual Flask app app = connexion.App(__name__, options=options) app.add_api( aggregate_specs(Path(__file__).parent / "swagger/api.yml"), validate_responses=True, resolver=RestyResolver('src.api'), ) def handler(environ, start_response) -> flask.Flask: """This function is required by the deployment. For more information, check here: https://www.alibabacloud.com/help/doc-detail/74756.htm?spm=a2c63.l28256.a3.18.a2543c943bYfKr """ # do something here return app(environ, start_response) if __name__ == "__main__": app.run(host=args.host,
import connexion from flask import Flask, jsonify from connexion.resolver import RestyResolver from resources import definitions as defn if __name__ == "__main__": app = connexion.App(__name__, specification_dir=defn.SWAGGER_DIR) app.add_api(defn.SWAGGER_CONF,resolver=RestyResolver('api')) app.run(port=defn.SERVICE_PORT)
from flask import Flask import connexion from connexion.resolver import RestyResolver from flask.ext.cors import CORS app = connexion.FlaskApp(__name__) app.add_api('swagger.yml', resolver=RestyResolver('api')) CORS(app.app) @app.route('/') def default_landing(): return 'See <a href="/v1/ui">swagger api</a> and try it <a href="v1/pain?seed=high">here</a>' if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5003)
# app.app.errorhandler(BaseUtilsException)(handle_exception) def create_app(): """ Create an application instance for adev to pickup up Returns: aiohttp.web.Application instance """ app = connexion.AioHttpApp(__name__, specification_dir='specs/', port=8000) app.add_api( 'service.yaml', resolver=RestyResolver('api'), strict_validation=True, validate_responses=True, pass_context_arg_name= 'request' # aiohttp param to pass the context into each request - gets headers, etc ) return app.app if __name__ == "__main__": app = connexion.AioHttpApp(__name__, specification_dir='specs/', port=8000) app.add_api('service.yaml', resolver=RestyResolver('api'), strict_validation=True, validate_responses=True, pass_context_arg_name='request') app.run(port=8000, debug=True)
import connexion from decouple import config from injector import Binder from flask_injector import FlaskInjector from connexion.resolver import RestyResolver from conf.elasticsearch_mapper import room_mapping from services.elasticsearch import ElasticSearchIndex, ElasticSearchFactory def configure(binder: Binder) -> Binder: binder.bind( ElasticSearchIndex, ElasticSearchIndex( ElasticSearchFactory( config('ELASTICSEARCH_HOST'), config('ELASTICSEARCH_PORT'), ), 'rooms', 'room', room_mapping)) return binder if __name__ == '__main__': app = connexion.App(__name__, specification_dir='swagger/') app.add_api('indexer.yaml', resolver=RestyResolver('api')) FlaskInjector(app=app.app, modules=[configure]) app.run(port=9090)
def test_resty_get_function(): function = RestyResolver('connexion').resolve_function_from_operation_id( 'connexion.app.App.common_error_handler') assert function == connexion.app.App.common_error_handler
if __name__ == "__main__": coloredlogs.install(level="INFO") td = TemporaryDirectory() tmpdir = td.name openapi_fn = tmpdir + "/openapi.yaml" open(openapi_fn, "w").write(generate_openapi_yaml()) _logger.info(f"Wrote {openapi_fn}") cxapp = connexion.App(__name__, debug=True, specification_dir=tmpdir) cxapp.add_api(openapi_fn, validate_responses=True, strict_validation=True, resolver=RestyResolver("anyvar.restapi.routes")) @cxapp.route('/redoc') def redoc(): return redoc_template, 200 @cxapp.route('/rapidoc') def rapidoc(): return rapidoc_template, 200 @cxapp.route('/') def index(): return redirect("/ui") cxapp.run(host="0.0.0.0", processes=1)
import os import connexion from flask_injector import FlaskInjector from connexion.resolver import RestyResolver from services.CouchProvider import CouchProvider from injector import Binder def configure(binder: Binder) -> Binder: binder.bind(CouchProvider) if __name__ == '__main__': app = connexion.App(__name__, specification_dir='swagger/' ) # Provide the app and the directory of the docs app.add_api('couch-service-docs.yaml', resolver=RestyResolver('api')) FlaskInjector(app=app.app, modules=[configure]) app.run(port=int(os.environ.get( 'PORT', 2020))) # os.environ is handy if you intend to launch on heroku
DB_HOST = os.environ["DB_HOST"] DB_NAME = os.environ["DB_NAME"] # Construct DB string DB_URL = "mysql+mysqlconnector://{user}:{passwd}@{host}/{db}".format( user=DB_USER, passwd=DB_PASSWD, host=DB_HOST, db=DB_NAME, ) app_connex = connexion.App(__name__, specification_dir="api") app = app_connex.app app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL app_connex.add_api("xtract_api_spec.yaml", resolver=RestyResolver("api")) application = app db = None def get_db(): db = SQLAlchemy(app) @app.route("/") def home(): """ Hello world @ 5000 """ return api.stockdata.get("AMZN", False)
#!/usr/bin/env python import connexion import logging from connexion.resolver import RestyResolver logging.basicConfig(level=logging.INFO) if __name__ == '__main__': app = connexion.App(__name__) app.add_api('resty-api.yaml', arguments={'title': 'RestyResolver Example'}, resolver=RestyResolver('api')) app.run(port=9090)
from flask import Flask import connexion from flask_injector import FlaskInjector from Flask_projects.Encrypt_project.password_encryption.service import configure from connexion.resolver import RestyResolver # app = connexion.FlaskApp(__name__, port=4000, host='192.168.1.7',specification_dir='swagger/') app = connexion.FlaskApp(__name__, port=4000, specification_dir='swagger/') app.add_api('user_password.yaml', resolver=RestyResolver("api")) flask_injector = FlaskInjector(app=app.app) # , modules=[configure]
import connexion from connexion.resolver import RestyResolver from models.db import db, configureAppForDB if __name__ == '__main__': connexionApp = connexion.App(__name__, specification_dir='swagger/') connexionApp.add_api('v1.yaml', resolver=RestyResolver('api.v1')) # Configure MongoEngine # app here is the Flask instance configureAppForDB(connexionApp.app) db.init_app(connexionApp.app) db.create_all(app=connexionApp.app) connexionApp.run(port=9090)
from connexion.resolver import RestyResolver import connexion if __name__ == '__main__': app = connexion.App(__name__, specification_dir='swagger/') app.add_api('postService.yaml', resolver=RestyResolver('api')) app.run(port=8081)
# Set up Connexion for debugging based on FLASK_DEBUG environment variable if 'FLASK_DEBUG' in os.environ and int(os.environ['FLASK_DEBUG']) >= 1: DEBUG_APP = True #pragma: no cover else: DEBUG_APP = False # Create the connextion-based Flask app, and tell it where to look for API specs APP = connexion.FlaskApp(__name__, specification_dir='spec/', debug=DEBUG_APP) FAPP = APP.app # JWT implementation JWT = JWTManager(FAPP) # Add our specific API spec, and tell it to use the Resty resolver to find the # specific python module to handle the API call by navigating the source tree # according to the API structure. All API modules are in the "api" directory APP.add_api(OPENAPI_SPEC, resolver=RestyResolver('api')) # Set a reference to the app and request loggers created in app_logging.yaml LOGGER = logging.getLogger('appLogger') REQUEST_LOGGER = logging.getLogger('requestLogger') # Log the API spec we're using LOGGER.info('API Specification: ' + OPENAPI_SPEC) APPSERVER_PORT = os.environ['APPSERVER_CPORT'] LOGGER.info('Running on port: ' + APPSERVER_PORT) LOGGER.debug('DebugSetting: ' + str(DEBUG_APP)) # Get the secret key from the environment FAPP.config['SECRET_KEY'] = os.environ['SECRET_KEY']
from flask import Flask from connexion.resolver import RestyResolver import connexion from flask import request #app = Flask(__name__) app = connexion.App(__name__, specification_dir='swagger/') app.add_api('AV_api.yaml', resolver=RestyResolver('app')) #app.run(port="9090") from app import views
init_logging(logging_env_var_start="ASH_LOG_") _LOGGER = logging.getLogger("ash") _LOGGER.setLevel(logging.DEBUG if bool(int(os.getenv("ASH_DEBUG", 0))) else logging.INFO) _LOGGER.info(f"This is Ash API v{__version__}") _LOGGER.debug("DEBUG mode is enabled!") # Expose for uWSGI. app = connexion.FlaskApp(__name__, specification_dir=Configuration.SWAGGER_YAML_PATH, debug=True) app.add_api( "ash-api.yaml", options={"swagger_ui": True}, arguments={"title": "Ash API"}, resolver=RestyResolver("thoth.ash.api"), strict_validation=True, validate_responses=True, ) application = app.app # create tracer and put it in the application configuration Configuration.tracer = init_jaeger_tracer("ash_api") # create metrics and manager metrics = PrometheusMetrics(application) manager = Manager(application)
def create_app(spec_files, wait_on_cyndi=True): """Creates an aplication object which is then served by tornado""" app = connexion.App('Vulnerability Engine Manager', options={'swagger_ui': True}) app.app.url_map.strict_slashes = False for route in spec_files.keys(): app.add_api(spec_files[route], resolver=RestyResolver('api'), validate_responses=True, strict_validation=True, base_path=route, arguments={'app_version': APP_VERSION}) app.add_error_handler(MissingEntitlementException, forbidden_missing_entitlement) app.add_error_handler(RbacException, forbidden_rbac) @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 registry = CollectorRegistry() multiprocess.MultiProcessCollector(registry) return generate_latest(registry) @app.app.after_request def set_default_headers(response): # pylint: disable=unused-variable response.headers["Access-Control-Allow-Origin"] = "*" response.headers[ "Access-Control-Allow-Headers"] = "Content-Type, Access-Control-Allow-Headers, \ Authorization, X-Requested-With, x-rh-identity" response.headers[ 'Access-Control-Allow-Methods'] = 'GET, OPTIONS, PATCH, POST' # format default connexion errors into nicer messages if response.status_code >= 400: original = json.loads(response.data.decode('utf-8')) if isinstance(original, dict) and 'errors' not in original: response.data = json.dumps({ 'errors': [{ 'detail': original['detail'], 'status': str(original['status']) }] }) return response # This hook ensures that a connection is opened to handle any queries # generated by the request. @app.app.before_request def _db_connect(): try: DB.connect() except OperationalError: LOGGER.exception("Error occured while connecting to database. %s", format_exc()) abort(503, "DB is not running") # This hook ensures that the connection is closed when we've finished # processing the request. @app.app.teardown_request def _db_close(exc): # pylint: disable=unused-argument if not DB.is_closed(): DB.close() if wait_on_cyndi: @app.app.before_first_request def _on_first_request(): _wait_on_cyndi() return app
import os import connexion from connexion.resolver import RestyResolver from providers.couchProvider import CouchProvider #from injector import Binder #app = connexion.App(__name__, specification_dir='swagger/') #app.add_api('swagger.yaml', resolver=RestyResolver('providers')) import logging logger = logging.getLogger('connexion.apis.app') if __name__ == '__main__': logger.debug('what') app = connexion.App( __name__, specification_dir='swagger/' ) # Provide the app and the directory of the docs specification_dir='swagger/' app.add_api('swagger.yaml', arguments={'title': 'RestyResolver Example'}, resolver=RestyResolver('providers')) #FlaskInjector(app=app.app, modules=[configure]) app.run(port=int(os.environ.get('POST', 5000)))
from connexion.resolver import RestyResolver import connexion if __name__ == '__main__': app = connexion.App(__name__, port=5004, specification_dir='swagger/') app.add_api('cart_api.yaml', resolver=RestyResolver('api')) app.run()
if required_scopes is not None and not validate_scope(required_scopes, info['scope']): raise OAuthScopeProblem( description='Provided user doesn\'t have the required access rights', required_scopes=required_scopes, token_scopes=info['scope'] ) return {"sub":username, "secret":password} def configure(binder: Binder) -> Binder: binder.bind( DegiroService, to=DegiroService() ) #Redefine application as a connexion app. application = connexion.App(__name__, specification_dir='openapi/') # Setup RestyResolver and the OpenAPI docs application.add_api('degiro-openapi.yaml', resolver=RestyResolver('api'), arguments={'title': 'Degiro OpenAPI'}) #FlaskInjector Setup defined after configure FlaskInjector(app=application.app, modules=[configure]) if __name__ == '__main__': #Start the flask server on either a predefined port from the host machine or 2025 application.run(debug=False, \ #server='tornado', port=int(os.environ.get('PORT', 2025)))
from connexion.resolver import RestyResolver import connexion import os from jwcrypto import jwk import flask_monitoringdashboard as dashboard SECRET_KEY = os.environ.get('Secret_Key') if not SECRET_KEY: key = jwk.JWK(generate='oct', size=256) os.environ['Secret_Key'] = key.export() if __name__ == '__main__': options = {"swagger_ui": False} app = connexion.App(__name__, specification_dir="../swager/", options=options) dashboard.config.init_from(file='../config.cfg') dashboard.bind(app) app.add_api('simple_microservice.yaml', resolver=RestyResolver('api')) app.run(9090) # options = {"swagger_ui": False} # app = connexion.FlaskApp(__name__, specification_dir='openapi/', options=options) # path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # path = os.path.join(path, "swager", "simple_microservice.yaml") # print(path) # app.add_api(path)
def create_app(runtime_environment): connexion_options = {"swagger_ui": True} # This feels like a hack but it is needed. The logging configuration # needs to be setup before the flask app is initialized. configure_logging() app_config = Config(runtime_environment) app_config.log_configuration() connexion_app = connexion.App("inventory", specification_dir="./swagger/", options=connexion_options) # Read the swagger.yml file to configure the endpoints parser = ResolvingParser(SPECIFICATION_FILE) parser.parse() for api_url in app_config.api_urls: if api_url: connexion_app.add_api( parser.specification, arguments={"title": "RestyResolver Example"}, resolver=RestyResolver("api"), validate_responses=True, strict_validation=True, base_path=api_url, ) logger.info("Listening on API: %s", api_url) # Add an error handler that will convert our top level exceptions # into error responses connexion_app.add_error_handler(InventoryException, render_exception) flask_app = connexion_app.app flask_app.config["SQLALCHEMY_ECHO"] = False flask_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False flask_app.config["SQLALCHEMY_DATABASE_URI"] = app_config.db_uri flask_app.config["SQLALCHEMY_POOL_SIZE"] = app_config.db_pool_size flask_app.config["SQLALCHEMY_POOL_TIMEOUT"] = app_config.db_pool_timeout flask_app.config["INVENTORY_CONFIG"] = app_config db.init_app(flask_app) flask_app.register_blueprint(monitoring_blueprint, url_prefix=app_config.mgmt_url_path_prefix) @flask_app.before_request def set_request_id(): threadctx.request_id = request.headers.get(REQUEST_ID_HEADER, UNKNOWN_REQUEST_ID_VALUE) if runtime_environment.event_producer_enabled: flask_app.event_producer = EventProducer(app_config) else: logger.warning( "WARNING: The event producer has been disabled. " "The message queue based event notifications have been disabled.") payload_tracker_producer = None if not runtime_environment.payload_tracker_enabled: # If we are running in "testing" mode, then inject the NullProducer. payload_tracker_producer = payload_tracker.NullProducer() logger.warning( "WARNING: Using the NullProducer for the payload tracker producer. " "No payload tracker events will be sent to to payload tracker.") payload_tracker.init_payload_tracker(app_config, producer=payload_tracker_producer) # HTTP request metrics if runtime_environment.metrics_endpoint_enabled: PrometheusMetrics( flask_app, defaults_prefix="inventory", group_by="url_rule", path=None, excluded_paths=[ "^/metrics$", "^/health$", "^/version$", r"^/favicon\.ico$" ], ) return flask_app
from connexion.resolver import RestyResolver import connexion from injector import Binder from flask_injector import FlaskInjector from services.provider import ItemsProvider def configure(binder: Binder) -> Binder: binder.bind( ItemsProvider, ItemsProvider([{"Name": "Test 1"}]) ) if __name__ == '__main__': app = connexion.App(__name__, specification_dir='swagger/') app.add_api('my_first_app.yaml', resolver=RestyResolver('api')) FlaskInjector(app=app.app, modules=[configure]) app.run(port=9090)
def liveness(): pass @staticmethod def readiness(): try: db.engine.execute('SELECT 1') except Exception as error: raise HealthError("Can't connect to the database") from error def create_app(self): # pylint: disable=redefined-outer-name app = Flask(self.import_name, **self.server_args) app.register_blueprint(healthz, url_prefix="/api/healthz") app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) # pylint: disable=unused-variable migrate = Migrate(app, db) # type: ignore # noqa: F841 app.config['HEALTHZ'] = { "live": self.liveness, "ready": self.readiness, } return app conn_app = DashDotDb('dashdotdb', specification_dir='schemas') conn_app.add_api('swagger.yaml', resolver=RestyResolver('dashdotdb.controllers')) app = conn_app.app # pylint: disable=unused-variable
def register_swagger_api(connexion_flask_app) -> None: """Take a connexion FlaskApp and register swagger API""" connexion_flask_app.add_api( 'api_spec.yaml', resolver=RestyResolver('persephone_api.api_endpoints'), validate_responses=True)
import connexion from injector import Binder from flask_injector import FlaskInjector from connexion.resolver import RestyResolver from services.provider import ItemsProvider def configure(binder: Binder) -> Binder: binder.bind( ItemsProvider, ItemsProvider([{"Name": "Test 1"}]) ) if __name__ == '__main__': app = connexion.FlaskApp(__name__, port=9090, specification_dir='swagger/') app.add_api('my_super_app.yaml', resolver=RestyResolver('api')) FlaskInjector(app=app.app, modules=[configure]) # app.add_api('my_super_app.yaml') app.run(host='0.0.0.0', debug=True,threaded=True) # app.run()
# -*- coding: utf-8 -*- """[summary] """ import connexion from connexion.resolver import RestyResolver connexionApp = connexion.FlaskApp(__name__, specification_dir='swagger/') connexionApp.add_api('hello_world_swagger.yaml', resolver=RestyResolver('api')) app = connexionApp.app if __name__ == '__main__': connexionApp.run(port=9090)
#!/bin/python3 # -*- coding: utf-8 -*- """ Stratnames API """ __license__ = "TBD" # Open source or proprietary? Apache 2.0, or MIT? __version__ = "0.1" import connexion from connexion.resolver import RestyResolver from flask_cors import CORS app = connexion.App(__name__) app.add_api('openapi.yaml', resolver=RestyResolver('api')) CORS(app.app) logo = r""" ( ( ) * ( ( ( )\ ) * ))\ ) ( * ) ( /( ( ( ` )\ ) ( )\ ))\ ) (()/(` ) /(()/( )\ ` ) /( )\()) )\ )\))( ( (()/( )\ (()/(()/( /(_))( )(_))(_)|(((_)( ( )(_)|(_)((((_)( ((_)()\ )\ /(_)) ((((_)( /(_))(_)) (_)) (_(_()|_)) )\ _ )\(_(_()) _((_)\ _ )\(_()((_|(_)(_)) )\ _ )\(_))(_)) / __||_ _| _ \ (_)_\(_)_ _|| \| (_)_\(_) \/ | __/ __| (_)_\(_) _ \_ _| \__ \ | | | / / _ \ | | | .` |/ _ \ | |\/| | _|\__ \ / _ \ | _/| | |___/ |_| |_|_\ /_/ \_\ |_| |_|\_/_/ \_\|_| |_|___|___/ /_/ \_\|_| |___| """ print(logo) app.run(port=8080)
_LOGGER.info(f"This is Management API v%s", __version__) _LOGGER.debug("DEBUG mode is enabled!") _THOTH_API_HTTPS = bool(int(os.getenv("THOTH_API_HTTPS", 1))) # Expose for uWSGI. app = connexion.FlaskApp( __name__, specification_dir=Configuration.SWAGGER_YAML_PATH, debug=True ) app.add_api( "openapi.yaml", options={"swagger_ui": True}, arguments={"title": "Management API"}, resolver=RestyResolver("thoth.management_api"), strict_validation=True, validate_responses=False, ) application = app.app # create tracer and put it in the application configuration Configuration.tracer = init_jaeger_tracer("management_api") # create metrics and manager metrics = PrometheusMetrics(application) manager = Manager(application)