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 __init__(self, app=None): self.app = app self.swagger = Swagger() if app: self.init_app(app)
'version': '0.0.1', 'title': 'Api v1', 'endpoint': 'spec/', 'description': 'Version 1 of the Swagger Waitlist API', 'route': '/spec/v1/swagger.json', # rule_filter is optional # it is a callable to filter the views to extract 'rule_filter': lambda rule: ('_v1' in rule.endpoint), # definition_filter is optional # it is a callable to filter the definition models to include 'definition_filter': lambda definition: ('v1_model' in definition.tags) }], 'host': LazyString(lambda: request.host), 'basePath': '', 'uiversion': 3, } template = {"schemes": [LazyString(lambda: request.scheme)]} swag = Swagger(app, template=template)
"headers": [], "specs": [ { "endpoint": "spec", "route": "/spec.json", "rule_filter": lambda rule: True, # all in "model_filter": lambda tag: True, # all in } ], "static_url_path": "/flasgger_static", # "static_folder": "static", # must be set by user "swagger_ui": True, "specs_route": "/", } swagger = Swagger(app, sanitizer=NO_SANITIZER, template=template, config=swagger_config) # Set up Bugsnag exception tracking, if desired. To use Bugsnag, install the # Bugsnag Python client with the command "pip install bugsnag", and set the # environment variable BUGSNAG_API_KEY. You can also optionally set # BUGSNAG_RELEASE_STAGE. if os.environ.get("BUGSNAG_API_KEY") is not None: try: import bugsnag import bugsnag.flask release_stage = os.environ.get("BUGSNAG_RELEASE_STAGE") or "production" bugsnag.configure( api_key=os.environ.get("BUGSNAG_API_KEY"), project_root=os.path.dirname(os.path.abspath(__file__)), use_ssl=True,
"model_filter": lambda tag: True, # all in }], "static_url_path": "/flasgger_static", # "static_folder": "static", # must be set by user "swagger_ui": True, "specs_route": "/", } template = dict(swaggerUiPrefix=LazyString( lambda: request.environ.get("HTTP_X_SCRIPT_NAME", ""))) app.json_encoder = LazyJSONEncoder swagger = Swagger(app, config=swagger_config, template=template) def hello_banking_api(): return jsonify({ "message": "You can start creating account and transfer between acounts" }) dict_of_errors = { 700: 'Account number must be greater than zero', 701: 'Account number must be unique', 702: 'Currency code should be one of them : TRY, USD, EUR', 703: 'balance cant be negative', 704: 'balance cant have precision greater then two',
from flasgger import Swagger from app import create_app from instance.config import app_config config_name = os.getenv('FLASK_CONFIG') app = create_app(config_name) swag = Swagger( app, template={ "info": { "title": "Yummy Recipes api-v1", "description": "API that registers and logs in a user so as to use the features and functionality of yummy recipes." }, "securityDefinitions": { "TokenHeader": { "type": "apiKey", "name": "Authorization", "in": "header" } } }) @app.route("/") def main(): return redirect('/apidocs')
from dart.web.api.subscription import api_subscription_bp from dart.web.ui.index import index_bp from flasgger import Swagger _logger = logging.getLogger(__name__) api_version_prefix = '/api/1' config_path = os.environ['DART_CONFIG'] config = configuration(config_path) logging.config.dictConfig(config['logging']) _logger.info('loaded config from path: %s' % config_path) app = Flask(__name__, template_folder='ui/templates', static_folder='ui/static') Swagger(app) # enables swagger-ui on /apidocs/index.html app.dart_context = AppContext(config=config, exclude_injectable_module_paths=[ 'dart.message.engine_listener', 'dart.message.trigger_listener', 'dart.message.subscription_listener' ]) app.config.update(config['flask']) db.init_app(app) app.register_blueprint(admin_bp, url_prefix='/admin') app.register_blueprint(api_dataset_bp, url_prefix=api_version_prefix) app.register_blueprint(api_datastore_bp, url_prefix=api_version_prefix) app.register_blueprint(api_engine_bp, url_prefix=api_version_prefix)
'''A module that contains documentation for swagger implementation which maps to the files for the flask api ''' import os from flasgger import Swagger from app import create_app CONFIG_NAME = os.getenv('APP_SETTINGS') app = create_app(CONFIG_NAME) SWAGGER = Swagger(app) @app.route('/auth/register', methods=['POST']) def register_user(): """Endpoint creating a user To register insert a valid email address such as '*****@*****.**' or '*****@*****.**' Insert a password for the email that you insert. The password can be a string. --- parameters: - name: user_email in: formData type: string description: A valid email for a user required: true - name: user_password in: formData type: string description: password for the user required: true responses:
ckeditor = CKEditor() swagger_template = { # "openapi": "3.0.0", # "components": { # "securitySchemes": { # "bearerAuth": { # "type": "http", # "scheme": "bearer", # "bearerFormat": "JWT", # } # } # }, } swagger = Swagger(template=swagger_template) admin = Admin( name="GN-Citizen: Backoffice d'administration", template_mode="bootstrap3", url="/".join([urlparse(app_conf["API_ENDPOINT"]).path, "admin"]), ) taxhub_url = valid_api_url(app_conf.get("API_TAXHUB", "")) taxhub_lists_url = taxhub_url + "biblistes/" def list_and_import_gnc_modules(app, mod_path=GNC_EXTERNAL_MODULE): """ Get all the module enabled from gn_commons.t_modules
"headers": [], "specs": [{ "endpoint": 'apispec', "route": '/apispec.json', "rule_filter": lambda rule: True, # all in "model_filter": lambda tag: True, # all in }], "static_url_path": "/flasgger_static", # "static_folder": "static", # must be set by user "swagger_ui": True, "specs_route": "/" } swagger = Swagger(app, config=swagger_config, template_file='docs/default.yml') @app.route('/search', methods=['GET']) # @cache.cached(timeout=30, query_string=True) def api_search(): return api_full_search() @app.route('/fullsearch', methods=['GET']) # @cache.cached(timeout=30, query_string=True) def api_full_search(): headers = {'content-type': 'application/json'} keyword = request.args.get("q") app.logger.info('the parameter is given: %s', keyword) result = ""
from flask import Flask, jsonify, request from flasgger import Swagger app = Flask(__name__) swagger = Swagger(app, template={ "swagger": "3.0", "openapi": "3.0.0", "info": { "title": "TODO", "version": "0.0.1", }, "components": { "schemas": { "Todo": { "properties": { "name": { "type": "string" }, "task": { "type": "string" } } } } } }) todos = {}
from datetime import datetime, timedelta from elasticsearch import Elasticsearch, NotFoundError from elasticsearch_dsl import Search, query, Q, DocType, utils from elasticsearch_dsl.exceptions import IllegalOperation from flasgger import Swagger es = Elasticsearch(timeout=60) app = Flask(__name__) from flask_cors import CORS, cross_origin CORS(app) app.config["SWAGGER"] = {"title": "Bitshares ES API", "uiversion": 2} Swagger(app, template_file="wrapper.yaml") if __name__ == "__main__": app.run(host="0.0.0.0", port=5000) @app.route("/get_account_history") def get_account_history(): account_id = request.args.get("account_id", False) operation_type = request.args.get("operation_type", False) from_ = request.args.get("from_", 0) size = request.args.get("size", 10) from_date = request.args.get("from_date", "2015-10-10") to_date = request.args.get("to_date", "now") sort_by = request.args.get("sort_by", "-block_data.block_time")
def create_app(*, config_module_class: str) -> Flask: """ Creates app in function so that flask with flask extensions can be initialized with specific config. Here it defines the route of APIs so that it can be seen in one place where implementation is separated. Config is being fetched via module.class name where module.class name can be passed through environment variable. This is to make config fetched through runtime PYTHON_PATH so that Config class can be easily injected. More on: http://flask.pocoo.org/docs/1.0/config/ :param config_module_class: name of the config :return: Flask """ if FLASK_APP_MODULE_NAME and FLASK_APP_CLASS_NAME: print( f'Using requested Flask module {FLASK_APP_MODULE_NAME} ' f'and class {FLASK_APP_CLASS_NAME}', file=sys.stderr) class_obj = getattr(importlib.import_module(FLASK_APP_MODULE_NAME), FLASK_APP_CLASS_NAME) flask_kwargs_dict = {} # type: Dict[str, Any] if FLASK_APP_KWARGS_DICT_STR: print( f'Using kwargs {FLASK_APP_KWARGS_DICT_STR} to instantiate Flask', file=sys.stderr) flask_kwargs_dict = ast.literal_eval(FLASK_APP_KWARGS_DICT_STR) app = class_obj(__name__, **flask_kwargs_dict) else: app = Flask(__name__) config_module_class = \ os.getenv('SEARCH_SVC_CONFIG_MODULE_CLASS') or config_module_class app.config.from_object(config_module_class) if app.config.get('LOG_CONFIG_FILE'): logging.config.fileConfig(app.config.get('LOG_CONFIG_FILE'), disable_existing_loggers=False) else: logging.basicConfig(format=app.config.get('LOG_FORMAT'), datefmt=app.config.get('LOG_DATE_FORMAT')) logging.getLogger().setLevel(app.config.get('LOG_LEVEL')) logging.info( 'Creating app with config name {}'.format(config_module_class)) logging.info('Created app with config name {}'.format(config_module_class)) api_bp = Blueprint('api', __name__) api_bp.add_url_rule('/healthcheck', 'healthcheck', healthcheck) api = Api(api_bp) # Table Search API # TODO: Rename endpoint to be more generic and accept a resource type so that logic can be re-used api.add_resource(SearchTableFilterAPI, '/search_table') api.add_resource(SearchTableAPI, '/search') api.add_resource(SearchTableFieldAPI, '/search/field/<field_name>/field_val/<field_value>') # User Search API api.add_resource(SearchUserAPI, '/search_user') # DocumentAPI api.add_resource(DocumentTablesAPI, '/document_table') api.add_resource(DocumentTableAPI, '/document_table/<document_id>') api.add_resource(DocumentUsersAPI, '/document_user') api.add_resource(DocumentUserAPI, '/document_user/<document_id>') app.register_blueprint(api_bp) if app.config.get('SWAGGER_ENABLED'): Swagger(app, template_file=os.path.join( ROOT_DIR, app.config.get('SWAGGER_TEMPLATE_PATH')), parse=True) return app
import collections from flasgger import Swagger, Flasgger import yaml from yaml.representer import Representer from pidgin.app import app, app_info def write_swagger(): """ Generate the Swagger documentation and store it in a file. """ yaml.add_representer(collections.defaultdict, Representer.represent_dict) outfile = 'openapi/swagger.yml' with open(outfile, 'w') as f: data = Flasgger.get_apispecs(swagger) yaml.dump(data, f, default_flow_style=False) print('Generated docs') if __name__ == '__main__': try: with app.app_context(): swagger = Swagger(app, template=app_info) write_swagger() except Exception as e: print('Could not geberate docs: {}'.format(e))
app = Flask(__name__) app.json_encoder = LazyJSONEncoder ES_SERVER = {"host": config["es_host"], "port": int(config["es_port"])} INDEX_NAME = 'arguments' es = Elasticsearch(hosts=[ES_SERVER]) reversed = True if (reversed): app.wsgi_app = ReverseProxied(app.wsgi_app) template2 = dict(swaggerUiPrefix=LazyString( lambda: request.environ.get('HTTP_X_SCRIPT_NAME', ''))) swagger = Swagger(app, template=template2) else: swagger = Swagger(app) api = Api(app) def create_api_url(endpoint): return 'http://' + config["backend_host"] + ":" + config[ "backend_port"] + "/" + endpoint class Sender: def send(self, text, classifier): if classifier == "WD":
def main(): # clear /etc/exports to avoid duplicated nfs client with open('/etc/exports', 'w') as f: f.write('') os.chdir('/home/%s/RESTfulSwarm/GlobalManager' % utl.get_username()) global db_address global db_client global db global worker_col global worker_resource_col global gm_address global dockerClient gm_address = utl.get_local_address() template = { "swagger": "2.0", "info": { "title": "RESTfulSwarm", "description": "An RESTful application for Docker Swarm.", "contact": { "responsibleDeveloper": "Zhuangwei Kang", "email": "*****@*****.**" }, "version": "0.0.1" }, "host": '%s:%s' % (gm_address, SystemConstants.GM_PORT), "basePath": "", "schemes": [ "http", ] } swagger = Swagger(app, template=template) dockerClient = docker.set_client() # mongodb with open('../DBInfo.json') as f: db_info = json.load(f) db_client = mg.get_client(usr=db_info['user'], pwd=db_info['pwd'], db_name=db_info['db_name'], address=db_info['address'], port=SystemConstants.MONGODB_PORT) db = mg.get_db(db_client, SystemConstants.MONGODB_NAME) worker_col = mg.get_col(db, SystemConstants.WorkersInfo) worker_resource_col = mg.get_col(db, SystemConstants.WorkersResourceInfo) # periodically prune unused network def prune_nw(): while True: networks = [] for job in job_buffer[:]: job_info = mg.filter_col(mg.get_col(db, job), 'job_name', job) if job_info is not None and job_info['status'] == 'Down': networks.append(job_info['job_info']['network']['name']) job_buffer.remove(job) docker.rm_networks(dockerClient, networks) print('Remove networks:', networks) time.sleep(60) prune_nw_thr = threading.Thread(target=prune_nw, args=()) prune_nw_thr.daemon = True prune_nw_thr.start() os.chdir('/home/%s/RESTfulSwarm/ManagementEngine' % utl.get_username()) app.run(host=gm_address, port=SystemConstants.GM_PORT, debug=False)
import os import redis from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from flask_mail import Mail from celery import Celery from flasgger import Swagger from flask_admin import Admin, BaseView, expose from config import config db = SQLAlchemy() swagger = Swagger() celery = Celery() mail = Mail() from app.admin import admin def create_app(config_name="default"): app = Flask(__name__, static_url_path="") app.config.from_object(config[config_name]) config[config_name].init_app(app) mail.init_app(app) db.init_app(app) swagger.init_app(app) CORS(app, supports_credentials=True) pool = redis.ConnectionPool(host=app.config["REDIS_HOST"], port=app.config["REDIS_PORT"], decode_responses=True)
from flask import (Flask, request) from flask_restful import (Api, Resource) from flasgger import Swagger from LogStream import input, filter, output, local_file_manager import logging import threading import uuid import time import json application = Flask(__name__) api = Api(application) swagger = Swagger(application) def setup_logging(log_level, log_file): if log_level == 'debug': log_level = logging.DEBUG elif log_level == 'verbose': log_level = logging.INFO else: log_level = logging.WARNING logging.basicConfig(filename=log_file, format='%(asctime)s %(levelname)s %(message)s', level=log_level) return logging.getLogger(__name__) @swagger.definition('cas', tags=['v2_model']) class ConfigCAS:
DB_NAME = os.getenv('DB_NAME') app = Flask("css-backend") app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'postgresql://{user}:{pw}@{host}/{db}'.format( user=DB_USERNAME, pw=DB_PASSWORD, host=DB_HOST, db=DB_NAME) app.config['SQLALCHEMY_ECHO'] = DEBUG app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False if DEBUG: app.config['SWAGGER'] = { 'title': app.import_name, 'version': '{version}-{commit}'.format(version=VERSION, commit=GIT_COMMIT), 'openapi': '3.0.2' } swagger = Swagger(app, template={ 'securityDefinitions': { 'bearerAuth': { 'type': 'http', 'scheme': 'bearer' } } }) db = SQLAlchemy(app) ma = Marshmallow(app) #migrate = Migrate(app, db)
if isinstance(v, collections.MutableMapping): items.extend( self.covert_to_flat_dict(v, new_key, sep=sep, to_upper=to_upper).items()) else: items.append((new_key, v)) return dict(items) def __repr__(self): """""" return "<{}: {}>".format(self.class_name, self.__dict__) swag = Swagger(app) # you can pass config here Swagger(config={}) # file schema definitions class FileAPI(MethodView): def get(self, file_id): """ Get a list of files First line is the summary All following lines until the hyphens is added to description --- tags: - files parameters: - name: file_id in: path
"info": { "title": "Example API for python-flask stack", "description": "API for helloworld, plus health/monitoring", "contact": { "responsibleOrganization": "IBM", "responsibleDeveloper": "Henry Nash", "email": "*****@*****.**", "url": "https://appsody.dev", }, "version": "0.2" }, "schemes": [ "http" ], } swagger = Swagger(app, template=swagger_template) # The python-flask stack includes the prometheus metrics engine. You can ensure your endpoints # are included in these metrics by enclosing them in the @track_requests wrapper. @app.route('/hello') @track_requests def HelloWorld(): # To include an endpoint in the swagger ui and specification, we include a docstring that # defines the attributes of this endpoint. """A hello message Example endpoint returning a hello message --- responses: 200: description: A successful reply examples:
]).decode() #methods={'MC','MC-S','QMC-S','MLMC','MLMC-A','FFT','FGL','COS','FD', # 'FD-NU','FD-AD','RBF','RBF-FD','RBF-PUM','RBF-LSML','RBF-AD','RBF-MLT'}; methods = [ 'MC-S', 'QMC-S', 'MLMC', 'MLMC-A', 'FFT', 'FGL', 'COS', 'FD', 'FD-NU', 'FD-AD', 'RBF', 'RBF-FD', 'RBF-PUM', 'RBF-LSML', 'RBF-AD', 'RBF-MLT' ] app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER Swagger(app, template={ "info": { "title": "BENCHOP as a Service API", "version": "0.6", } }) # all_problems = ['problem1_A1', 'problem1_A2', 'problem1_B1', 'problem1_B2', 'problem1_C1', 'problem1_C2'] all_problems = ['problem1_A1', 'problem1_B1', 'problem1_B2', 'problem1_C1'] # [[x], [y], [z]] -> [x, y, z] def flat_result(res): return list(np.hstack(res)) @app.route('/') def goto_api():
# web处理异步线程引起的玄学bug,预测必须执行此条才能正确运行,同样,训练得执行model._make_train_function()才可以 model._make_predict_function() emotion_detector = EmotionDetector(labels=get_labels('fer2013'), face_detector=DlibFaceDetector(), emotion_classifier=model, emotion_offsets=(10, 10)) # swagger配置 swagger_config = Swagger.DEFAULT_CONFIG swagger_config['title'] = config.SWAGGER_TITLE # 配置大标题 swagger_config['description'] = config.SWAGGER_DESC # 配置公共描述内容 swagger_config['host'] = config.SWAGGER_HOST # 请求域名 # swagger_config['swagger_ui_bundle_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js' # swagger_config['swagger_ui_standalone_preset_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js' # swagger_config['jquery_js'] = '//unpkg.com/[email protected]/dist/jquery.min.js' # swagger_config['swagger_ui_css'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui.css' Swagger(app, config=swagger_config) class MyResponse(Response): @classmethod def force_type(cls, response, environ=None): if isinstance(response, (list, dict)): response = jsonify(response) response.status_code = 200 return super(Response, cls).force_type(response, environ) class MyFlask(Flask): response_class = MyResponse
def add_docs(app, cfg, template): Swagger(app, config=cfg, template_file=template)
def create_app(): app = Flask(__name__) # CORS(app) # cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) app.config['SWAGGER'] = { 'title': 'KAE Console API', 'uiversion': 3, } app.url_map.converters['date'] = DateConverter app.config.from_object('console.config') app.secret_key = app.config['SECRET_KEY'] app.url_map.strict_slashes = False make_celery(app) db.init_app(app) init_oauth(app) mako.init_app(app) cache.init_app(app) sess.init_app(app) sockets.init_app(app) migrate = Migrate(app, db) from console.admin import init_admin admin = Admin(app, name='KAE', template_mode='bootstrap3') init_admin(admin) from console.libs.view import user_require swagger = Swagger(app, decorators=[ user_require(False), ], template=yaml.load(swagger_yaml_template)) if not DEBUG: sentry = Sentry(dsn=SENTRY_DSN) sentry.init_app(app) for bp_name in api_blueprints: bp = import_string('%s.api.%s:bp' % (__package__, bp_name)) app.register_blueprint(bp) from console.api.ws import ws sockets.register_blueprint(ws) @app.before_request def init_global_vars(): g.start = request.args.get('start', type=int, default=0) g.limit = request.args.get('limit', type=int, default=20) @app.after_request def apply_caching(response): # TODO: remove the code response.headers[ 'Access-Control-Allow-Origin'] = 'http://localhost:3000' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers[ 'Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie' response.headers[ 'Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE,OPTIONS' return response @app.errorhandler(422) def handle_unprocessable_entity(err): # webargs attaches additional metadata to the `data` attribute exc = getattr(err, 'exc') if exc: # Get validations from the ValidationError object messages = exc.messages else: messages = ['Invalid request'] return jsonify({ 'messages': messages, }), 422 @app.before_first_request def prepare_k8s(): # placeholder to prepare environment pass return app
# -*- coding: utf-8 import os from flask import Flask, jsonify from flasgger import Swagger app = Flask(__name__) app.config['SWAGGER'] = {'doc_dir': './docs'} swag = Swagger( app, template_file=os.path.join( os.getcwd(), 'docs', 'colors.yml'), parse=True) @app.route('/colors/<palette>/') def colors(palette): """ 返回颜色组 """ all_colors = { 'cmyk': ['cian', 'magenta', 'yellow', 'black'], 'rgb': ['red', 'green', 'blue'] } if palette == 'all': result = all_colors else: result = {palette: all_colors.get(palette)} return jsonify(result)
import torch import yaml from model import BiLSTMCRF from utils import * import warnings import numpy as np from flask import Flask, request from flasgger import Swagger warnings.filterwarnings("ignore") device = torch.device("cpu") app = Flask(__name__) swagger = Swagger(app) def load_params(path: str): """ Load the parameters (data) """ with open(path + "data.pkl", "rb") as fopen: data_map = pickle.load(fopen) return data_map def strQ2B(ustring): rstring = "" for uchar in ustring: inside_code=ord(uchar)
scheduler.add_job(func=hit_config_refresh_endpoint, trigger="interval", seconds=3_600) scheduler.start() global model model = joblib.load(MODEL_PATH) return app app = initialize_app() Talisman(app) app.secret_key = FLASK_SECRET dashboard.bind(app) swag = Swagger(app) @app.before_request def set_session_uid(): """ Sets a UID for each session """ uid = str(uuid.uuid4()) session["uid"] = uid @app.route("/", methods=["POST", "GET"]) def home(): """ Home route that will confirm if the app is healthy
from app import create_app enviroment = config['development'] app = create_app(enviroment) CORS(app) # app.config["SQLALCHEMY_ECHO"] = True app.config["SWAGGER"] = { "swagger_version": "2.0", "title": "Sales API", "specs": [{ "version": "0.0.1", "title": "Sales", "endpoint": "spec", "route": "/app/spec", "rule_filter": lambda rule: True, # all in }], "static_url_path": "/apidocs", } Swagger(app) if __name__ == '__main__': # serve(app, listen='*:8080') serve(app, host='0.0.0.0', port=8080) #app.run()
# 'headers': [], # 'specs':[ # { # 'endpoint': 'apispec', # 'route': '/apispec.json' # } # ], # 'components':{ # 'securitySchemes':{ # 'BearerAuth':{ # 'type': 'http', # 'scheme': 'bearer', # 'bearerFormat': 'JWT', # 'in': 'header' # } # } # } # } api.register_blueprint(test_api) api.register_blueprint(user_api) api.register_blueprint(product_api) #swag = Swagger(api, config=swagger_config) swag = Swagger(api) @api.route('/', methods=['GET', 'POST']) def default(): return jsonify('Python 3.x API default route -> boring :)')
from flask_json import FlaskJSON, as_json, json_response from pathalchemy import PathAlchemy from configparser import ConfigParser from flasgger import Swagger, swag_from app = Flask(__name__) FlaskJSON(app) Swagger(app, template={ "swagger": "2.0", "info": { "title": "PathQL API", "description": "PathQL API for my data", "version": "0.9.1" }, "securityDefinitions": { "basicAuth": { "type": "basic" } }, "security": [{ "basicAuth": [] } ] }) app.config['JSON_ADD_STATUS'] = False config = None cwd = getcwd() @app.route('/pathql', methods=['POST']) @swag_from(cwd+'/pathql.yml')
def spec(): from cert_viewer import app return jsonify(Swagger(app))