def server_process(port, mode, **kwargs): import json import falcon from distutils.version import StrictVersion from wsgiref import simple_server class HelloWorldResource(object): def on_get(self, req, resp): resp.body = json.dumps({'text': 'Hello World!!!'}) if StrictVersion(falcon.__version__) < StrictVersion('3.0.0'): app = falcon.API() else: app = falcon.App() app.add_route('/hello/world', HelloWorldResource()) if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import falcon_api_doc falcon_api_doc(app, **kwargs) httpd = simple_server.make_server('localhost', port, app) httpd.serve_forever()
def startup(): if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import starlette_api_doc starlette_api_doc(app, **kwargs)
def register_generated_openid_docs(self, *, host: str, port: int) -> None: cur_dir = os.path.dirname(os.path.abspath(__file__)) schema_yaml_file_name = 'open_api.yaml' schema_yaml_file_path = os.path.join(cur_dir, f'./{schema_yaml_file_name}') self.__app.add_route(path="/schema", route=self.open_api_schema(), methods=["GET", "HEAD"], include_in_schema=False) @exception_handler @self.__app.on_event("shutdown") def shutdown() -> None: os.remove(schema_yaml_file_path) yaml_open_api_schema = yaml.dump( self.__open_api_schema.get_schema(routes=self.__app.routes), default_flow_style=False) with open(schema_yaml_file_path, 'w') as writer: writer.write("servers:\n" f"- url: http://{host}:{port}\n") writer.write(yaml_open_api_schema) api_doc(self.__app, config_path=schema_yaml_file_path, url_prefix="/swagger.io/docs")
def create_app(): working_dir = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(working_dir, 'conf/test.yaml') app = falcon.asgi.App() app.add_route('/hello/world', HelloWorldResource()) from swagger_ui import api_doc api_doc(app, config_path=config_path, url_prefix='/api/doc') return app
def run_server(): """Starts the app on port 5000. This api call can used to start the app from another python script. """ swagger_config_path = path.join(path.dirname(path.abspath(__file__)), 'swagger_files/swagger.json') api_doc(app, config_path=swagger_config_path, url_prefix='/api/doc', title='myBuzzn App API') logger.info("Swagger API configured.") socketio.run(app, port=5000)
def server_process(port, mode, **kwargs): from sanic import Sanic, response app = Sanic(__name__) @app.get(r'/hello/world') async def index_handler(request): return response.text('Hello World!!!') if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import sanic_api_doc sanic_api_doc(app, **kwargs) app.run(host='localhost', port=port)
def server_process(port, mode, **kwargs): from bottle import Bottle, run app = Bottle() @app.route('/hello/world') def hello(): return 'Hello World!!!' if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import bottle_api_doc bottle_api_doc(app, **kwargs) run(app, host='localhost', port=port)
def server_process(port, mode, **kwargs): from aiohttp import web async def hello(request): return web.Response(text="Hello, world") app = web.Application() app.add_routes([web.get('/hello/world', hello)]) if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import aiohttp_api_doc aiohttp_api_doc(app, **kwargs) web.run_app(app, host='localhost', port=port)
def server_process(port, mode, **kwargs): from quart import Quart app = Quart(__name__) @app.route(r'/hello/world', methods=['GET']) async def index_handler(): return 'Hello World!!!' if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import quart_api_doc quart_api_doc(app, **kwargs) app.run(host='localhost', port=port)
def server_process(port, mode, **kwargs): from flask import Flask app = Flask(__name__) @app.route(r'/hello/world') def hello(): return 'Hello World!!!' if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import flask_api_doc flask_api_doc(app, **kwargs) app.run(host='localhost', port=port)
def mk_bottle_app(funcs, **configs): from bottle import Bottle routes, openapi_spec = mk_routes_and_openapi_specs(funcs, **configs) app = Bottle(catchall=False) enable_cors = mk_config('enable_cors', None, configs, default_configs) plugins = mk_config('plugins', None, configs, default_configs) if enable_cors: cors_allowed_origins = mk_config( 'cors_allowed_origins', None, configs, default_configs ) app.install(CorsPlugin(cors_allowed_origins)) publish_openapi = mk_config('publish_openapi', None, configs, default_configs) openapi_insecure = mk_config('openapi_insecure', None, configs, default_configs) publish_swagger = mk_config('publish_swagger', None, configs, default_configs) if plugins: for plugin in plugins: app.install(plugin) for route in routes: route_http_method = route.http_method.upper() http_methods = ( route.http_method if not enable_cors else [OPTIONS, route_http_method] ) # print(f'Mounting route: {route.path} {route.http_method.upper()}') app.route(route.path, http_methods, route, route.method_name) app.route( path='/ping', callback=lambda: {'ping': 'pong'}, name='ping', skip=plugins ) if publish_openapi: skip = plugins if openapi_insecure else None app.route( path='/openapi', callback=lambda: openapi_spec, name='openapi', skip=skip, ) app.openapi_spec = openapi_spec if publish_swagger: swagger_url = mk_config('swagger_url', None, configs, default_configs) swagger_title = mk_config('swagger_title', None, configs, default_configs) api_doc( app, config_spec=json.dumps(openapi_spec), url_prefix=swagger_url, title=swagger_title, ) return app
def create_app(config_object=ProdConfig): app = Flask(__name__.split('.')[0]) app.url_map.strict_slashes = False app.config.from_object(config_object) CORS(app) api_doc(app, config_path='./doc.yaml', url_prefix='/api/doc', title='API doc') register_extensions(app) register_blueprints(app) app.app_context().push() from backend.models.battery import Battery return app
def server_process(port, mode, **kwargs): from chalice import Chalice from chalice.config import Config from chalice.local import create_local_server app = Chalice(__name__) @app.route('/hello/world') def index(): return {'hello': 'world'} if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import chalice_api_doc chalice_api_doc(app, **kwargs) config = Config() create_local_server(app, config, 'localhost', port).serve_forever()
def server_process(port, mode, **kwargs): import tornado.ioloop import tornado.web class HelloWorldHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): return self.write('Hello World!!!') app = tornado.web.Application([ (r'/hello/world', HelloWorldHandler), ]) if mode == 'auto': from swagger_ui import api_doc api_doc(app, **kwargs) else: from swagger_ui import tornado_api_doc tornado_api_doc(app, **kwargs) app.listen(address='localhost', port=port) tornado.ioloop.IOLoop.current().start()
def start(test = False): app = create_app(blueprints=blueprints) app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SECRET_KEY'] = 'ANOTHER ONE' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///reactions.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False if test: app.config['TESTING'] = True app.config['CELERY_ALWAYS_EAGER'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['WTF_CSRF_ENABLED'] = False app.request = test_request else: app.request = real_request api_doc(app, config_path='./reactions/react-specs.yaml', url_prefix='/api', title='API doc') db.init_app(app) db.create_all(app=app) with app.app_context(): q = db.session.query(Like) like = q.first() if like is None: example = Like() example.story_id= 1 example.liker_id= 2 db.session.add(example) db.session.commit() s = db.session.query(Dislike) dislike = s.first() if dislike is None: example = Dislike() example.story_id=1 example.disliker_id= 3 db.session.add(example) db.session.commit() return app
import os from chalice import Chalice app = Chalice(app_name='chalice_test') @app.route('/hello/world') def index(): return {'hello': 'world'} working_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) config_path = os.path.join(working_dir, 'conf/test.yaml') from swagger_ui import api_doc api_doc(app, config_path=config_path, url_prefix='/api/doc')
emit('live_data', {'data': 'Connected with sid ' + request.sid}, room=request.sid) @socketio.on('disconnect', namespace='/live') def disconnect(): del clients[request.sid] def run_server(): """Starts the app on port 5000. This api call can used to start the app from another python script. """ swagger_config_path = path.join(path.dirname(path.abspath(__file__)), 'swagger_files/swagger.json') api_doc(app, config_path=swagger_config_path, url_prefix='/api/doc', title='myBuzzn App API') logger.info("Swagger API configured.") socketio.run(app, port=5000) if __name__ == "__main__": config_path = path.join(path.dirname(path.abspath(__file__)), 'swagger_files/swagger.json') api_doc(app, config_path=config_path, url_prefix='/api/doc', title='myBuzzn App API') logger.info("Swagger API configured.") socketio.run(app, debug=True)
# Scheduled tasks def clean_tmp_folders(): directories = ["tmp/zip_downloads/*", "tmp/ssh/*"] for directory in directories: logger.info("Remove files inside " + directory) files = glob.glob(directory) for f in files: os.remove(f) sched = BackgroundScheduler(daemon=False) sched.add_job(clean_tmp_folders, 'interval', hours=1) sched.start() with app.app_context(): db.init_app(app) db.create_all() app_session = Session(app) app_session.app.session_interface.db.create_all() app.config["SESSION_SQLALCHEMY"] = SQLAlchemy(app) api_doc( app, config_url=config.Config.FLASK_ENDPOINT + "/api/swagger.json", url_prefix="/api/doc", title="SOCA API Documentation", ) if __name__ == '__main__': app.run()
def startup(): cur_dir = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(cur_dir, 'conf/test.yaml') from swagger_ui import api_doc api_doc(app, config_path=config_path)
import os import tornado.ioloop import tornado.web class HelloWorldHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): return self.write('Hello World!!!') def make_app(): return tornado.web.Application([ (r'/hello/world', HelloWorldHandler), ]) if __name__ == '__main__': app = make_app() cur_dir = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(cur_dir, 'conf/test.yaml') # from swagger_ui import tornado_api_doc # tornado_api_doc(app, config_path=config_path, url_prefix='/api/doc/') from swagger_ui import api_doc api_doc(app, config_path=config_path, url_prefix='/api/doc/', editor=True) app.listen(8989) tornado.ioloop.IOLoop.current().start()
la documentacion de `bottle.Bottle`. Pagina oficial de Bottle.py: https://bottlepy.org/ """ def route_mount(self, prefix, _app=None, routes=[]): if _app and isinstance(_app, bottle.Bottle): routes.extend(_app.routes) for route in routes: route.rule = prefix + route.rule route.app = self self.add_route(route) app = BottleGlass() api_doc(app, config_path="../docs/swagger.yaml", url_prefix="/swagger", title="Swagger Doc") app.route_mount('/health', server.routes.health.app) app.route_mount('/auth', server.routes.auth.app) @app.get("/") def index(): return dict(code=200) def error_handler(code=500, message="Internal Error"): @enable_cors def error_error_code(error): bottle.response.status = code bottle.response.content_type = 'application/json'
from flask import Flask from flask_restful import Api from flask_cors import CORS from api.routes.routes import health from handler.userServiceHandler import Users, User from swagger_ui import api_doc app_url_prefix: str = '/v1' app: Flask = Flask(__name__) api: Api = Api(app, prefix=app_url_prefix) CORS(app) app.register_blueprint(health, url_prefix=app_url_prefix) api.add_resource(Users, '/users') api.add_resource(User, '/users/<user_id>') api_doc(app, config_path='./docs/openapi/userApiDefinition.yaml', url_prefix=app_url_prefix + '/api/doc', title='API doc') if __name__ == '__main__': app.run(debug=True, port=3000)
import os from sanic import Sanic, response app = Sanic(__name__) @app.get(r'/hello/world') async def index_handler(request): return response.text('Hello World!!!') if __name__ == '__main__': working_dir = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(working_dir, 'conf/test.yaml') from swagger_ui import api_doc api_doc(app, config_path=config_path) app.run(host='0.0.0.0', port=8989)
@app.route("/js/<path:filename>", methods=["GET"]) async def js(filename) -> Response: """Javascript static endpoint.""" return await send_from_directory("js", filename) @app.route("/img/<path:filename>", methods=["GET"]) async def img(filename) -> Response: """Image static endpoint.""" return await send_from_directory("img", filename) # Swagger UI api_doc(app, config_path="swagger.yaml", url_prefix="/openapi", title="OpenTTS") @app.errorhandler(Exception) async def handle_error(err) -> typing.Tuple[str, int]: """Return error as text.""" _LOGGER.exception(err) return (f"{err.__class__.__name__}: {err}", 500) # ----------------------------------------------------------------------------- # Run Web Server # ----------------------------------------------------------------------------- hyp_config = hypercorn.config.Config()
def create_app(test_config=None): log = logging.getLogger(__name__) discovery = OIDCDiscovery() # a = connexion.FlaskApp(__name__, specification_dir='v1/spec/') # a.add_api('v1.yaml', arguments={ # "tokeninfo_url": discovery["introspection_endpoint"], # "authorization_url": discovery["authorization_endpoint"], # "accesstoken_url": discovery["token_endpoint"] # }) # app = a.app app = Flask(__name__) conf = config.Config() if test_config is None: app.config.update(conf.data) else: # load the test config if passed in app.config.update(conf.data) app.config.update(test_config) ##Routes## v1.Register(app) Compress(app) ## Template the spec and write it to a temporary location tmpFile = "%s/v1.yaml" % conf.data['workingFolder'] f = open("v1/spec/v1.yaml", "r") t = Template(f.read()) f = open(tmpFile, "w") f.write( t.render(server_url="/v1", tokeninfo_url=discovery["introspection_endpoint"], authorization_url=discovery["authorization_endpoint"], accesstoken_url=discovery["token_endpoint"])) api_doc(app, config_path=tmpFile, url_prefix='/api/doc', title='API doc') @app.before_request def before_request(): from timeit import default_timer as timer g.request_start_time = timer() g.request_time = lambda: "%s" % (timer() - g.request_start_time) resp = Response() resp.headers['Content-Type'] = ["application/json"] @app.after_request def after_request(response): set_cors_headers_on_response(response) log.debug('Rendered in %ss', g.request_time()) return response @app.errorhandler(HTTPStatus.NOT_FOUND) def not_found(param): content = jsonify({"error": "Not Found", "code": HTTPStatus.NOT_FOUND}) return make_response(content, HTTPStatus.NOT_FOUND) @app.errorhandler(HTTPStatus.INTERNAL_SERVER_ERROR) def internal_server_error(error): log = app.logger log.error("Internal Error %s - %s" % (request.remote_addr, str(error))) content = jsonify({ "error": "{error}", "code": HTTPStatus.INTERNAL_SERVER_ERROR }) log.error(request.get_data()) log.error(request.form) log.error(request.headers) return make_response(content, HTTPStatus.INTERNAL_SERVER_ERROR) @app.errorhandler(HTTPStatus.BAD_REQUEST) def bad_request_error(error): log = app.logger log.error("Bad Request %s - %s" % (request.remote_addr, str(error))) content = jsonify({ "error": "Bad Request", "code": HTTPStatus.BAD_REQUEST }) log.error(request.get_data()) log.error(request.form) log.error(request.headers) return make_response(content, HTTPStatus.BAD_REQUEST) @app.errorhandler(JoseError) def forbidden(error): log.error("Denied access %s - %s" % (request.remote_addr, str(error))) content = jsonify({"error": "Invalid Token"}) return make_response(content, HTTPStatus.UNAUTHORIZED) @app.errorhandler(ExpiredTokenError) def expired_token(error): content = jsonify({"error": "Token Expired"}) return make_response(content, HTTPStatus.UNAUTHORIZED) @app.route('/', methods=['GET'], strict_slashes=False) def index(): """ Returns a list of valid API version endpoints :return: JSON of valid API version endpoints """ return jsonify([url_for(".v1.get_status", _external=True)]) @app.route('/version', methods=['GET'], strict_slashes=False) def version(): """ Get the current version of the api """ from os import environ hash = "" if environ.get('GITHASH') is not None: hash = environ.get("GITHASH") # import pkg_resources # part of setuptools # print(pkg_resources) # v = pkg_resources.get_distribution("gwa-kong").version v = "" version = v if hash != "": version += "-" + hash responseObj = {"v": v, "hash": hash, "version": version} return jsonify(responseObj) return app