def create_app(config): """ Wrapper function for Flask app params: config: Config """ app = Flask(__name__) app.config.from_object(config) model_path = os.path.abspath(os.getenv('MODEL_PATH', default='models/neuralParscit/')) word_emb_path = os.path.abspath(os.getenv('WORD_EMB_PATH', default='vectors_with_unk.kv')) with app.app_context(): logging.info("Loading model from {} and using word embeddings from {}".format(model_path, word_emb_path)) model, inference = get_model(model_path, word_emb_path) setattr(app, 'model', model) setattr(app, 'inference', inference) setattr(app, 'word_to_id', {v:i for i, v in model.id_to_word.items()}) setattr(app, 'char_to_id', {v:i for i, v in model.id_to_char.items()}) API_DOC_PATH = '/docs' SWAGGER_PATH = '/swagger' api_bp = Blueprint('api', __name__) api = Api(api_bp, add_api_spec_resource=False) api.add_resource(Parse, '/parscit/parse') api.add_resource(ParseBatch, '/parscit/parse/batch') docs = [api.get_swagger_doc()] swagger_ui_blueprint = get_swaggerui_blueprint( API_DOC_PATH, SWAGGER_PATH + '.json', config={ 'app_name': 'ParsCit API' } ) app.register_blueprint(api.blueprint) app.register_blueprint(get_swagger_blueprint(docs, SWAGGER_PATH, title='ParsCit API', api_version='1.0', base_path='/')) app.register_blueprint(swagger_ui_blueprint, url_prefix=API_DOC_PATH) @app.errorhandler(404) def not_found(error): """ Handles URLs that are not specified """ return jsonify({ 'message': "API doesn't exist" }), 404 return app
def add_documentation(self): self.docs.append(self.api.get_swagger_doc()) self.flask_app.register_blueprint( get_swagger_blueprint(self.docs, API_JSON_ENTRYPOINT, title=self.title, api_version=BPM_VERSION)) self.flask_app.register_blueprint(get_swaggerui_blueprint( API_UI, API_JSON_ENTRYPOINT + '.json', config={'supportedSubmitMethods': ['get']}), url_prefix=API_UI)
def register_blueprints(app): """Register Flask blueprints.""" app.register_blueprint(get_api_blueprint(app)) # Prepare a blueprint to serve the combined list of swagger document objects and register it app.register_blueprint( get_swagger_blueprint(get_swagger_docs(app), app.config['API_SWAGGER_URL'], title=app.config['API_TITLE'], api_version=app.config['API_VERSION'], base_path=app.config['API_URL_PREFIX'])) # Allow CORS for the Swagger URL so swagger-ui can access it # CORS(app, resources={r"%s.json" % app.config['API_SWAGGER_URL']: {"origins": "*"}}) # CORS(app, resources={r"/api/*": {"origins": "*"}}) CORS(app, resources={r"/api*": {"origins": "*"}}) return None
def append_swagger_doc(app): """ 添加swagger文档,从api中获得文档,并统一添加到一个blueprint中 :param app: :return: """ docs = [] def append_custom_path(url, operator): nonlocal docs from . import users, pictures docs.append(users.api.get_swagger_doc()) docs.append(pictures.api.get_swagger_doc()) #特别的为JWT的登入接口 添加文档 if len(docs) == 0: return doc = docs[0] doc['definitions'].update( {UserLoginSchema.__name__: UserLoginSchema.definitions()}) doc['paths'].update({ '/auth': { 'post': { 'tags': ['auth'], 'description': 'login', 'summary': '登入', 'parameters': [ { 'description': '', 'in': 'body', 'name': 'body', 'schema': { "$ref": "#/definitions/UserLoginSchema" } }, ], 'responses': { '200': { 'description': 'ok' } } } } }) # 下面所有的配置只会影响最后生成的文档 app.register_blueprint( get_swagger_blueprint( docs, '/api/swagger', # 使用mydomain.com/api/swagger.json 访问文档 title='irides Api文档', api_version='1', tags=[{ 'name': 'pictures', 'description': '图片' }, { 'name': 'auth', 'description': '授权' }, { 'name': 'user', 'description': '用户' }], base_path='/api', # 请求前缀,最后所有的请求都是mydomain.com/base_path/.... schemes=['http', 'https'], security_definitions={ 'jwt': { "type": "apiKey", "name": "Authorization", "in": "header", "description": "需要添加:'Bearer AccessToken'不包括引号" } }))
}) Compress(app) CORS(app) # Config SECRET_KEY = os.environ.get("CXG_SECRET_KEY", default="SparkleAndShine") app.config.update(SECRET_KEY=SECRET_KEY) # Application Data data = None # A list of swagger document objects docs = [] resources = get_api_resources() docs.append(resources.get_swagger_doc()) app.register_blueprint(webapp.bp) app.register_blueprint(resources.blueprint) app.register_blueprint( get_swagger_blueprint( docs, "/api/swagger", produces=["application/json"], title="cellxgene rest api", description= "An API connecting ExpressionMatrix2 clustering algorithm to cellxgene", )) app.add_url_rule("/", endpoint="index")
def append_swagger_doc(app): """ 添加swagger文档,从api中获得文档,并统一添加到一个blueprint中 :param app: :return: """ docs = [] def append_custom_path(url, operator): nonlocal docs from . import users, pictures docs.append(users.api.get_swagger_doc()) docs.append(pictures.api.get_swagger_doc()) # 特别的为JWT的登入接口 添加文档 if len(docs) == 0: return doc = docs[0] doc["definitions"].update({UserLoginSchema.__name__: UserLoginSchema.definitions()}) doc["paths"].update( { "/auth": { "post": { "tags": ["auth"], "description": "login", "summary": "登入", "parameters": [ { "description": "", "in": "body", "name": "body", "schema": {"$ref": "#/definitions/UserLoginSchema"}, } ], "responses": {"200": {"description": "ok"}}, } } } ) # 下面所有的配置只会影响最后生成的文档 app.register_blueprint( get_swagger_blueprint( docs, "/api/swagger", # 使用mydomain.com/api/swagger.json 访问文档 title="irides Api文档", api_version="1", tags=[ {"name": "pictures", "description": "图片"}, {"name": "auth", "description": "授权"}, {"name": "user", "description": "用户"}, ], base_path="/api", # 请求前缀,最后所有的请求都是mydomain.com/base_path/.... schemes=["http", "https"], security_definitions={ "jwt": { "type": "apiKey", "name": "Authorization", "in": "header", "description": "需要添加:'Bearer AccessToken'不包括引号", } }, ) )
def configure_swagger(app, docs): """This function register endpoint for swagger.""" app.register_blueprint( get_swagger_blueprint(docs, '/api/swagger', title='Sites Flask API', api_version='1') )
# A list of swagger document objects docs = [] # Get user resources user_resources = get_user_resources() # Retrieve and save the swagger document object (do this for each set of resources). docs.append(user_resources.get_swagger_doc()) # Register the blueprint for user resources app.register_blueprint(user_resources.blueprint) # Prepare a blueprint to server the combined list of swagger document objects and register it app.register_blueprint( get_swagger_blueprint(docs, '/api/swagger', title='Example', api_version='1')) @app.route('/') def index(): return """<head> <meta http-equiv="refresh" content="0; url=http://petstore.swagger.io/?url=http://localhost:5000/api/swagger.json" /> </head>""" if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')