class ApiDoc(object): def __init__(self, app=None): self.app = app self.swagger = Swagger() if app: self.init_app(app) def init_app(self, app): self.app = app app.config['SWAGGER'] = {"swagger_version": "2.0", "specs": self.get_specs()} self.swagger.init_app(self.app) def get_specs(self): def get_spec_config(api): ver = '_'.join(api.split('_')[1:]) return dict(version=ver, title='Api v' + ver, endpoint='spec_' + api, route='/docs/api/v%s' % ver, rule_filter=lambda rule: rule.endpoint.startswith(api)) return [get_spec_config(api) for api in self.find_apis()] def find_apis(self): path = os.path.join(self.app.config['BASE_DIR'], 'controllers') return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) and name.startswith('api')]
class ApiDoc(object): def __init__(self, app=None): self.app = app self.swagger = Swagger() if app: self.init_app(app) def init_app(self, app): self.app = app app.config['SWAGGER'] = { "swagger_version": "2.0", "specs": self.get_specs() } self.swagger.init_app(self.app) def get_specs(self): def get_spec_config(api): ver = '_'.join(api.split('_')[1:]) return dict(version=ver, title='Api v' + ver, endpoint='spec_' + api, route='/docs/api/v%s' % ver, rule_filter=lambda rule: rule.endpoint.startswith(api)) return [get_spec_config(api) for api in self.find_apis()] def find_apis(self): path = os.path.join(self.app.config['BASE_DIR'], 'controllers') return [ name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) and name.startswith('api') ]
def apply_swagger(app): from flasgger import Swagger tags = [tag for _, bp in bp_list for tag in bp.tags] # 默认与 config/setting.py 的 SWAGGER 合并 # 可以将secure.py中的SWAGGER全部写入template swagger = Swagger(template={'tags': tags}) swagger.init_app(app)
def apply_swagger(app): from flasgger import Swagger, LazyString from app.core.json_encoder import JSONEncoder as _JSONEncoder class JSONEncoder(_JSONEncoder): def default(self, obj): if isinstance(obj, LazyString): return str(obj) return super(JSONEncoder, self).default(obj) app.json_encoder = JSONEncoder # 访问swagger文档前自动执行(可以用于文档的安全访问管理) def before_access(f): @wraps(f) def decorated(*args, **kwargs): return f(*args, **kwargs) return decorated def on_host(): host = request.host if ',' in host: return host.split(',')[-1] return host swagger = Swagger( decorators=[before_access], template={ 'host': LazyString(on_host), # Swagger请求的服务端地址 'schemes': [LazyString(lambda: 'https' if request.is_secure else 'http')], # 通信协议: http或https或多个 'tags': app.config['SWAGGER_TAGS'], # 接口在文档中的类别和顺序 }) swagger.init_app(app)
def create_app(*config_cls) -> Flask: log(message='Flask application initialized with {}'.format(', '.join( [config.__name__ for config in config_cls])), keyword='INFO') flask_app = Flask(__name__) for config in config_cls: flask_app.config.from_object(config) connect(**flask_app.config['MONGODB_SETTINGS']) CORS(flask_app, resources={ r"*": { "origin": "*" }, }) swagger = Swagger(template=Config.template) swagger.init_app(flask_app) JWTManager().init_app(flask_app) Router().init_app(flask_app) return flask_app
def create_app(test_config=None): """Return a Flask app with the blueprints and config from this module.""" app = Flask(__name__) swagger = Swagger() if test_config is None: app.config.from_pyfile('config.py') else: app.config.update(test_config) swagger.init_app(app) app.register_blueprint(__main__.root) return app
def register_plugin(app): # 解决跨域问题 from flask_cors import CORS cors = CORS() cors.init_app(app, resources={"/*": {"origins": "*"}}) # 连接数据库 from app.models.base import db db.init_app(app) with app.app_context(): # 手动将app推入栈 db.create_all() # 首次模型映射(ORM ==> SQL),若无则建表; 初始化使用 # Debug模式下可以查阅 API文档 if app.config['DEBUG']: from flasgger import Swagger from app.api.v1 import template swagger = Swagger(template=template) # 可以将secure.py中的SWAGGER全部写入template swagger.init_app(app)
def get_specs_data(mod): """ return all specs dictionary for some app """ # for each example app in /examples folder client = mod.app.test_client() # init swag if not yet inititalized (no-routes example) if getattr(mod.app, 'swag', None) is None: _swag = Swagger() _swag.config['endpoint'] = str(random.randint(1, 5000)) _swag.init_app(mod.app) # get all the specs defined for the example app apidocs = client.get('/apidocs/?json=true') specs = json.loads(apidocs.data.decode("utf-8")).get('specs') specs_data = {} for spec in specs: # for each spec get the spec url url = spec['url'] response = client.get(url) decoded = response.data.decode("utf-8") specs_data[url] = json.loads(decoded) return specs_data
def specs_data(app, client): """ return all specs dictionary for the Flask App """ specs_route = None specs_data = dict() swag = getattr(app, 'swag', None) # init swag if not yet inititalized (no-routes example) if swag is None: _swag = Swagger() _swag.config['endpoint'] = str(random.randint(1, 5000)) _swag.init_app(app) # get all the specs defined for the example app else: try: flasgger_config = swag.config if flasgger_config.get('swagger_ui') is False: return specs_data specs_route = flasgger_config.get('specs_route', '/apidocs/') except AttributeError: pass if specs_route is None: specs_route = '/apidocs/' apidocs = client.get('?'.join((specs_route, 'json=true'))) specs = json.loads(apidocs.data.decode("utf-8")).get('specs') for spec in specs: # for each spec get the spec url url = spec['url'] response = client.get(url) decoded = response.data.decode("utf-8") specs_data[url] = json.loads(decoded) return specs_data
'basePath': '/ ', # Title 바로 아래에 위치할 Base URL } template = { 'schemes': ['http'], 'tags': [{ 'name': 'hi', 'description': 'hi Tag Description' }] # 각 태그들에 대해 미리 명시 } # config와 template의 경계가 조금 애매하지만, 세팅 종류가 굉장히 많으니 그러려니 하고 넘어가는 편이 좋다 swagger = Swagger(template=template) swagger.init_app(app) @app.route('/') @swag_from({ 'tags': ['hi'], 'parameters': [{ 'name': 'id', 'in': 'query', 'type': 'str', 'required': True }], 'responses': { '200': { 'description': 'Success. Responses Your ID', 'examples': {
def apply_swagger(app): from flasgger import Swagger # 默认与 config/setting.py 的 SWAGGER 合并 # 可以将secure.py中的SWAGGER全部写入template swagger = Swagger(template={'tags': app.config['SWAGGER_TAGS']}) swagger.init_app(app)
def create_app(): from .db import db # Models from .providers.models import Provider from .medicines.models import Medicine from .customers.models import Customer from .accounts.models import User # Views from .accounts.views import user_blueprint, auth_blueprint from .medicines.views import medicine_blueprint, upload_blueprint from .providers.views import provider_blueprint from .customers.views import customer_blueprint # Common from .common.exceptions import InvalidUsage from .common.handlers import bad_request_handler, unauthorized_handler from .accounts.utils import jwt_identity, identity_loader, DecimalJSONEncoder app = Flask(__name__) app.json_encoder = DecimalJSONEncoder app.config.from_object(environ.get("FLASK_SETTINGS_MODULE")) # database and migrations db.init_app(app) Migrate(app, db) # marshmallow ma = Marshmallow(app) ma.init_app(app) # jwt extended jwt = JWTManager(app) jwt.init_app(app) jwt.user_identity_loader(identity_loader) jwt.user_loader_callback_loader(jwt_identity) # bcrypt bcrypt = Bcrypt() bcrypt.init_app(app) # CORs cors = CORS() cors.init_app(app) # Minio storage = Minio(app) storage.init_app(app) # Swagger swagger = Swagger() swagger.init_app(app) # error handlers app.register_error_handler(InvalidUsage, bad_request_handler) app.register_error_handler(HTTPStatus.BAD_REQUEST, bad_request_handler) app.register_error_handler(HTTPStatus.UNAUTHORIZED, unauthorized_handler) # blueprints app.register_blueprint(auth_blueprint) # Authentication app.register_blueprint(provider_blueprint) # Provider app.register_blueprint(user_blueprint) # Users app.register_blueprint(customer_blueprint) # Customers app.register_blueprint(medicine_blueprint) # Medicines app.register_blueprint(upload_blueprint) # Medicines upload return app
} swag = Swagger(template={ "swagger": "2.0", "info": { "title": "Swagger Basic Auth App", "version": "1.0", }, "consumes": [ "application/json", ], "produces": [ "application/json", ], }, ) # passing decorators in init_app swag.init_app(app, decorators=[requires_basic_auth]) @app.route("/echo/<name>", methods=["GET", "POST"]) def echo(name): """ Echo back the name and any posted parameters. --- tags: - echo parameters: - in: path name: name type: string required: true - in: body