Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
def create_app():
    app=Flask(__name__)
    template = dict(swaggerUiPrefix=LazyString(lambda : request.environ.get('HTTP_X_FORWARDED_PREFIX', '')))
    swagger = Swagger(app, template=template)
    app.wsgi_app = ReverseProxied(app.wsgi_app)
    app.json_encoder = CustomJSONEncoder
    cache.init_app(app, config={'CACHE_TYPE': 'simple'})
#    CORS(app)
    return app
Ejemplo n.º 3
0
def init_swagger(app: Flask):
    """This function handles all the logic for adding Swagger automated
    documentation to the application instance.

    Args:
        app: A Flask application instance.
    """
    from flasgger import Swagger
    from flasgger import LazyString
    from flask import url_for

    swagger_config = {
        'headers': [],
        'specs': [
            {
                'endpoint': 'flagging_api',
                'route': '/api/flagging_api.json',
                'rule_filter': lambda rule: True,  # all in
                'model_filter': lambda tag: True,  # all in
            },
        ],
        'static_url_path':
        '/flasgger_static',
        # 'static_folder': '/static/flasgger',
        'swagger_ui':
        True,
        'specs_route':
        '/api/docs'
    }
    template = {
        'info': {
            'title':
            'CRWA Public Flagging API',
            'description':
            "API for the Charles River Watershed Association's predictive "
            'models, and the data used for those models.',
            'contact': {
                'x-responsibleOrganization':
                'Charles River Watershed Association',
                'x-responsibleDeveloper': 'Code for Boston',
            },
            'version':
            '1.0',
        }
    }
    app.config['SWAGGER'] = {
        'uiversion':
        3,
        'favicon':
        LazyString(lambda: url_for('static', filename='favicon/favicon.ico'))
    }

    Swagger(app, config=swagger_config, template=template)
Ejemplo n.º 4
0
class Config:
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True
    SECRET_KEY = env_var("SECRET_KEY")

    CACHE_TYPE = 'RedisCache'
    CACHE_DEFAULT_TIMEOUT = TWO_HOURS
    CACHE_KEY_PREFIX = f'Analytics-{APP_ENV}'
    CACHE_REDIS_HOST = env_var('REDIS_SERVER')
    CACHE_REDIS_PORT = env_var('REDIS_PORT')
    CACHE_REDIS_URL = f"redis://{env_var('REDIS_SERVER')}:{env_var('REDIS_PORT')}"

    CLARITY_API_BASE_URL = env_var("CLARITY_API_BASE_URL")
    CLARITY_API_KEY = env_var("CLARITY_API_KEY")

    SWAGGER = {
        "swagger": "2.0",
        "info": {
            "title": "Analytics API",
            "description": "API docs for analytics AirQO microservice",
            "version": "0.0.1"
        },
        "schemes": ["http", "https"],
        'footer_text':
        LazyString(lambda: f'© AirQo. {datetime.now().year}'),
        'head_text': '<style>.top_text{color: red;}</style>',
        'doc_expansion': "list",
        'ui_params': {
            'apisSorter': 'alpha',
            'operationsSorter': 'alpha',
        },
        'ui_params_text': '''{
            "operationsSorter" : (a, b) => a.get("path").localeCompare(b.get("path"))
        }''',
        "url_prefix": f"{BASE_URL}"
    }
Ejemplo n.º 5
0
                environ['PATH_INFO'] = path_info[len(script_name):]

        scheme = environ.get('HTTP_X_SCHEME', '')
        if scheme:
            environ['wsgi.url_scheme'] = scheme
        return self.app(environ, start_response)


app = Flask(__name__)
app.json_encoder = LazyJSONEncoder

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)


class ClassifyNewWD(Resource):
    def post(self):
        """
       Classifies input text to argument structure (Essays model, fasttext - big dataset)
       ---
       consumes:
         - text/plain
       parameters:
Ejemplo n.º 6
0
    "info": {
        "title": "ROBOKOP Builder",
        "description":
        "An API connecting questions with biomedical knowledge services",
        "contact": {
            "responsibleOrganization": "CoVar Applied Technologies",
            "responsibleDeveloper": "*****@*****.**",
            "email": "*****@*****.**",
            "url": "www.covar.com",
        },
        "termsOfService": "<url>",
        "version": "0.0.1"
    },
    "schemes": ["http", "https"],
    'swaggerUiPrefix':
    LazyString(lambda: request.environ.get('HTTP_X_SWAGGER_PREFIX', ''))
}
app.json_encoder = LazyJSONEncoder

app.config['SWAGGER'] = {'title': 'ROBOKOP Builder API', 'uiversion': 3}
swagger_config = {
    "headers": [],
    "specs": [{
        "endpoint": 'apispec_1',
        "route": '/builder/spec',
        "rule_filter": lambda rule: True,  # all in
        "model_filter": lambda tag: True,  # all in
    }],
    "swagger_ui":
    True,
    "specs_route":
Ejemplo n.º 7
0
import requests
from flask import Flask, request
from flasgger import Swagger, LazyString, LazyJSONEncoder
from flasgger import swag_from

app = Flask(__name__)
app.json_encoder = LazyJSONEncoder
swagger_template = dict(info={
    'title':
    LazyString(lambda: 'Hanabi Stats API Documentation'),
    'version':
    LazyString(lambda: '0.1')
},
                        host=LazyString(lambda: request.host))
swagger = Swagger(app, template=swagger_template)


@swag_from("export.yml", methods=['GET'])
@app.route("/export/<game_id>")
def export_game(game_id):
    print(game_id)
    url = f'https://hanab.live/export/{game_id}'
    response = requests.get(url)
    return response.json()


@swag_from("history_pagination.yml", methods=['GET'])
@app.route("/api/v1/history/<players>")
def get_history_page(players):
    players = players.replace(",", "/")
    filters = ''
Ejemplo n.º 8
0
 'template': {
     "swagger":
     "2.0",
     "info": {
         "title": "HyperTube API",
         "description": "API for HyperTube project, 42 ecole",
         "contact": {
             "responsibleOrganization": "ME",
             "responsibleDeveloper": "Me",
             "email": "*****@*****.**",
             "url": "www.me.com",
         },
         "version": "0.1"
     },
     "host":
     LazyString(lambda: request.host),
     "basePath":
     "/",
     "schemes":
     [LazyString(lambda: 'https' if request.is_secure else 'http')],
     "tags": [
         {
             "name": "Movies",
             "description": "Actions with movies"
         },
         {
             "name": "Persons",
             "description": "Actions with persons"
         },
         {
             "name": "Genres",
Ejemplo n.º 9
0
# coding=utf-8

from flask import request

from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flasgger import Swagger, LazyString

db = SQLAlchemy()
cors = CORS()

template = dict(host=LazyString(lambda: request.host),
                base_url=LazyString(lambda: request.base_url))
swagger = Swagger(template=template)
Ejemplo n.º 10
0
        '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)
Ejemplo n.º 11
0
        "title": "ROBOKOP Ranker",
        "description": "An API for answering biomedical questions",
        "contact": {
            "responsibleOrganization": "CoVar Applied Technologies",
            "responsibleDeveloper": "*****@*****.**",
            "email": "*****@*****.**",
            "url": "www.covar.com",
        },
        "termsOfService": "<url>",
        "version": "0.0.1"
    },
    "schemes": [
        "http",
        "https"
    ],
    'swaggerUiPrefix': LazyString (lambda : request.environ.get('HTTP_X_SWAGGER_PREFIX', ''))
}
app.json_encoder = LazyJSONEncoder
app.config['SWAGGER'] = {
    'title': 'ROBOKOP Ranker API',
    'uiversion': 3
}
swagger_config = {
    "headers": [
    ],
    "specs": [
        {
            "endpoint": 'apispec_1',
            "route": '/ranker/spec',
            "rule_filter": lambda rule: True,  # all in
            "model_filter": lambda tag: True,  # all in
Ejemplo n.º 12
0
"""

from flask import Flask, jsonify, request

from flasgger import Swagger, LazyString, LazyJSONEncoder

app = Flask(__name__)

# Set the LAzyString JSON Encoder
app.json_encoder = LazyJSONEncoder

app.config['SWAGGER'] = {'uiversion': 2}

template = dict(
    info={
        'title': LazyString(lambda: 'Lazy Title'),
        'version': LazyString(lambda: '99.9.9'),
        'description': LazyString(lambda: 'Hello Lazy World'),
        'termsOfService': LazyString(lambda: '/there_is_no_tos')
    },
    host=LazyString(lambda: request.host),
    schemes=[LazyString(lambda: 'https' if request.is_secure else 'http')],
    foo=LazyString(lambda: "Bar"))

Swagger(app, template=template)


@app.route('/colors/<palette>/')
def colors(palette):
    """Example endpoint return a list of colors by palette
    This is using docstring for specifications
Ejemplo n.º 13
0
def create_app(test_config=None):
    # generate a random token used by workers
    alphabet = string.ascii_letters + string.digits + string.punctuation
    token = ''.join(secrets.choice(alphabet) for _ in range(secrets.randbelow(30) + 50))

    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        WORKER_TOKEN=token,
        DATABASE=os.path.join(app.instance_path, 'db.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)

        # load environment variables
        app.config['DEBUG'] = bool(os.environ.get('DEBUG') or app.config.get('DEBUG', False))
        app.config['TESTING'] = bool(os.environ.get('TESTING') or app.config.get('TESTING', False))
        if os.environ.get('SECRET_KEY'):
            app.config['SECRET_KEY'] = bytes(os.environ.get('SECRET_KEY'), encoding='utf8')
        app.config['SERVER_NAME'] = os.environ.get('SERVER_NAME') or app.config.get('SERVER_NAME', None)
        app.config['TIMEZONE'] = os.environ.get('TIMEZONE') or app.config.get('TIMEZONE', 'Europe/Paris')

        app.config['RABBITMQ_HOST'] = os.environ.get('RABBITMQ_HOST') or app.config.get('RABBITMQ_HOST', 'localhost')
        app.config['RABBITMQ_PORT'] = int(os.environ.get('RABBITMQ_PORT') or app.config.get('RABBITMQ_PORT', 5672))
        app.config['RABBITMQ_QUEUE'] = os.environ.get('RABBITMQ_QUEUE') or app.config.get('RABBITMQ_QUEUE', 'tasks')

        app.config['API_ENABLE'] = bool(os.environ.get('API_ENABLE') or app.config.get('API_ENABLE', False))
        if os.environ.get('API_CORS_ALLOW_ORIGINS'):
            app.config['API_CORS_ALLOW_ORIGINS'] = os.environ.get('API_CORS_ALLOW_ORIGINS')
            if ',' in app.config['API_CORS_ALLOW_ORIGINS']:
                app.config['API_CORS_ALLOW_ORIGINS'] = app.config['API_CORS_ALLOW_ORIGINS'].split(',')

        app.config['SENTRY_DSN'] = bool(os.environ.get('SENTRY_DSN') or app.config.get('SENTRY_DSN', ''))
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    if not app.config['TIMEZONE'] in all_timezones:
        app.logger.error(gettext(u'ERROR: TIMEZONE is not filled properly'))
        sys_exit(1)
    if not app.config['SECRET_KEY']:
        app.logger.error(gettext(u'ERROR: SECRET_KEY is not filled properly'))
        sys_exit(1)

    CORS(app, resources={r"/api/*": {"origins": app.config.get("API_CORS_ALLOW_ORIGINS", "http://localhost")}})

    # init sentry
    sentry_dsn = app.config.get("SENTRY_DSN", "")
    if sentry_dsn:
        sentry_sdk.init(
            sentry_dsn,
            integrations=[FlaskIntegration()]
        )

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    babel = Babel(app, default_timezone=app.config['TIMEZONE'])

    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(['fr', 'en'], 'en')

    @app.template_filter('datetime')
    def jinja_format_datetime(dt, format='short'):
        if dt is None:
            return ""
        return format_datetime(dt, format=format)

    csrf_protect.init_app(app)

    db.init_app(app)
    admin.init_app(app)

    app.register_blueprint(auth.bp)
    app.register_blueprint(configuration_files.bp)
    app.register_blueprint(tasks.bp)
    app.register_blueprint(settings.bp)
    app.register_blueprint(admin.bp)
    app.register_blueprint(errors.bp)
    app.register_blueprint(csrf.bp)

    if app.config['API_ENABLE']:
        app.json_encoder = LazyJSONEncoder
        app.config['SWAGGER'] = {
            'title': 'ConfigurationsManagement API',
            'uiversion': 3
        }
        template = dict(
            info={
                'title': LazyString(lambda: 'ConfigurationsManagement API'),
                'version': LazyString(lambda: '1.0.0'),
                'description': LazyString(lambda: ''),
                'termsOfService': LazyString(lambda: ''),
                'license': {
                    'name': 'CeCILL v2.1'
                }
            },
            basePath='/',
            securityDefinitions={
                'APIKeyHeader': {
                    'type': 'apiKey',
                    'in': 'header',
                    'name': 'X-API-Key'
                }
            },
            security=[
                {'APIKeyHeader': []},
            ]
        )
        swagger_config = {
            "headers": [],
            "specs": [
                {
                    "endpoint": 'docs',
                    "route": '/api/docs.json',
                    "rule_filter": lambda rule: True,  # all in
                    "model_filter": lambda tag: True,  # all in
                }
            ],
            "static_url_path": "/flasgger_static",
            "swagger_ui": True,
            "specs_route": "/api/docs"
        }
        Swagger(app, template=template, config=swagger_config, decorators=[api_auth_required])

        app.register_blueprint(api.bp)
        csrf_protect.exempt(api.bp)

    @app.route("/ping")
    def hello():
        return "OK", 200

    @app.route('/')
    def index():
        return redirect(url_for('tasks.index'), code=302)

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')

    return app
Ejemplo n.º 14
0
            "responsibleDeveloper": "zhousl",
            "email": "*****@*****.**",
            "url": "www.golaxy.cn",
        },
        "termsOfService": "*****@*****.**",
        "version": "2.0.0"
    },
    "produces":
    "application/json",
    "consumes":
    "application/json",
    # "host": "127.0.0.1:8011",  # overrides localhost:500
    # "basePath": "/golaxy/nlp/wss/",  # base bash for blueprint registration
    "schemes": ["http", "https"],
    "swaggerUiPrefix":
    LazyString(lambda: request.environ.get("HTTP_X_SCRIPT_NAME", ""))
}

app.json_encoder = LazyJSONEncoder
swagger = Swagger(app, config=swagger_config,
                  template=template)  #, sanitizer=NO_SANITIZER)


def get_zh_predict(sentence):
    data = []
    data.append(sentence)
    output = segmenter.decode_text(data)[0]
    return output


@app.route("/wss/chinese/v1", methods=["POST"])
Ejemplo n.º 15
0
app.wsgi_app = ReverseProxied(app.wsgi_app)

app.config['SWAGGER'] = {
    'title': 'TARGER API',
    'favicon': "https://assets.webis.de/img/favicon.png",
    'uiversion': 3,
}

# Load Swagger base spec from YAML file.
schema_dir = Path(__file__).parent / "schema"
with (schema_dir / "base.yml").open("r") as stream:
    template = yaml.safe_load(stream)
# Update with properties only known at runtime.
template.update({
    "basePath":
    LazyString(lambda: request.environ.get('HTTP_X_SCRIPT_NAME', '')),
    "swaggerUiPrefix":
    LazyString(lambda: request.environ.get('HTTP_X_SCRIPT_NAME', '')),
})
swagger = Swagger(app, template=template)


@app.route('/tag-webd-glove', methods=['POST'])
@swag_from(str(schema_dir / "tag-webd-glove.yml"))
def tag_webd_glove():
    inputtext = request.get_data().decode('UTF-8')
    result = modelNewWD.label(inputtext)
    response = make_response(jsonify(result))
    response.headers['content-type'] = 'application/json'
    return response
    "specs": [{
        "endpoint": "apispec_1",
        "route": "/apispec_1.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/",
}

template = dict(swaggerUiPrefix=LazyString(
    lambda: request.environ.get("HTTP_X_SCRIPT_NAME", "")))

app.json_encoder = LazyJSONEncoder
swagger = Swagger(app, config=swagger_config, template=template)


@app.route("/")
def index():
    return "Add Employee"


@app.route("/Add Employee", methods=["POST"])
@swag_from("swagger_config.yml")
def add_emp():
    input_json = request.get_json()
    try:
Ejemplo n.º 17
0
from flask_restful import Api
from flasgger import Swagger, LazyString, LazyJSONEncoder
from flasgger.utils import swag_from
import bson.json_util

# Set up Flask
app = Flask(__name__)
app.json_encoder = LazyJSONEncoder
template = dict(
    info={
        'title': 'Awesome API',
        'version': '1.0.0',
        'description': 'Api de ejemplo',
        'termsOfService': '/terms'
    },
    host=LazyString(lambda: request.host),
    schemes=[LazyString(lambda: 'https' if request.is_secure else 'http')])
Swagger(app, template=template)

# Set up Mongo
client = MongoClient()  # defaults to localhost
db = client.data


@app.route("/executive/<string:name>", methods=['GET'])
@swag_from('executiveByName.yml')
def executive(name):
    executive = db.executives.find({"name": name}, {'_id': 0})
    return jsonify(list(executive))