Python flasgger.Swagger() Examples

The following are 8 code examples of flasgger.Swagger(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flasgger , or try the search function .
Example #1
Source File: definition_object_test.py    From flasgger with MIT License 6 votes vote down vote up
def return_test(size):
    """
    another test return
    ---
    properties:
      result:
        type: string
        description: The test
        default: 'test2'
    """
    size = int(size)

    return {"result": "test2" * size}


# Flask endpoints with flasgger docstrings are automatically registered.
# The first line of the docstring is used as the summary/
# The following lines (before '---') are used as the description.
# YAML after '---' defines the Swagger path schema. 
Example #2
Source File: __init__.py    From recon-ng with GNU General Public License v3.0 5 votes vote down vote up
def create_app():

    # setting the static_url_path to blank serves static files from the web root
    app = Flask(__name__, static_url_path='')
    app.config.from_object(__name__)

    Swagger(app, template_file='definitions.yaml')

    app.redis = Redis.from_url(app.config['REDIS_URL'])
    app.task_queue = rq.Queue('recon-tasks', connection=app.redis)

    @app.after_request
    def disable_cache(response):
        response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        return response

    @app.route('/')
    def index():
        return render_template('index.html', workspaces=recon._get_workspaces())

    from recon.core.web.api import resources
    app.register_blueprint(resources)

    return app 
Example #3
Source File: decorators_in_init_app.py    From flasgger with MIT License 5 votes vote down vote up
def requires_basic_auth(f):
    """Decorator to require HTTP Basic Auth for your endpoint."""

    def check_auth(username, password):
        return username == "guest" and password == "secret"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @wraps(f)
    def decorated(*args, **kwargs):
        # NOTE: This example will require Basic Auth only when you run the
        # app directly. For unit tests, we can't block it from getting the
        # Swagger specs so we just allow it to go thru without auth.
        # The following two lines of code wouldn't be needed in a normal
        # production environment.
        if __name__ != "__main__":
            return f(*args, **kwargs)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated 
Example #4
Source File: parsed_view_func.py    From flasgger with MIT License 5 votes vote down vote up
def get(self):
        """
        If we set "parse" is True in Flasgger app, we will get parsed and
        validated data stored in "flask.request.parsed_data".

        In "parsed_data", different location's var stored in different key,
        there is a map between RequestParser's location and swagger
        doc's "in" parameter, eg: 'query' -> 'args'.See
        "Swagger.SCHEMA_LOCATIONS" for more locations
        """
        return jsonify(
            [{'name': 'test', 'id': 1,
              'type': request.parsed_data['args']['type']},
             {'name': 'test2', 'id': 2,
              'type': request.parsed_data['args']['type']}]) 
Example #5
Source File: basic_auth.py    From flasgger with MIT License 5 votes vote down vote up
def requires_basic_auth(f):
    """Decorator to require HTTP Basic Auth for your endpoint."""

    def check_auth(username, password):
        return username == "guest" and password == "secret"

    def authenticate():
        return Response(
            "Authentication required.", 401,
            {"WWW-Authenticate": "Basic realm='Login Required'"},
        )

    @wraps(f)
    def decorated(*args, **kwargs):
        # NOTE: This example will require Basic Auth only when you run the
        # app directly. For unit tests, we can't block it from getting the
        # Swagger specs so we just allow it to go thru without auth.
        # The following two lines of code wouldn't be needed in a normal
        # production environment.
        if __name__ != "__main__":
            return f(*args, **kwargs)

        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated 
Example #6
Source File: conftest.py    From flasgger with MIT License 5 votes vote down vote up
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)
    specs_route = None
    specs_data = {}
    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
    else:
        try:
            flasgger_config = mod.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 
Example #7
Source File: api_doc.py    From ijust_server with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, app=None):
        self.app = app
        self.swagger = Swagger()

        if app:
            self.init_app(app) 
Example #8
Source File: http.py    From bert-as-service with MIT License 4 votes vote down vote up
def create_flask_app(self):
        try:
            from flask import Flask, request
            from flask_compress import Compress
            from flask_cors import CORS
            from flask_json import FlaskJSON, as_json, JsonError
            from bert_serving.client import ConcurrentBertClient
            from flasgger import Swagger
        except ImportError:
            raise ImportError('BertClient or Flask or its dependencies are not fully installed, '
                              'they are required for serving HTTP requests.'
                              'Please use "pip install -U bert-serving-server[http]" to install it.')

        # support up to 10 concurrent HTTP requests
        bc = ConcurrentBertClient(max_concurrency=self.args.http_max_connect,
                                  port=self.args.port, port_out=self.args.port_out,
                                  output_fmt='list', ignore_all_checks=True)
        app = Flask(__name__)
        app.config['SWAGGER'] = {
          'title': 'Colors API',
          'uiversion': 3,
          'openapi': '3.0.2'
        }
        swag = Swagger(app, template_file='bertApi.openapi.yaml')

        logger = set_logger(colored('PROXY', 'red'))

        @app.route('/status/server', methods=['GET'])
        @as_json
        def get_server_status():
            return bc.server_status

        @app.route('/status/client', methods=['GET'])
        @as_json
        def get_client_status():
            return bc.status

        @app.route('/encode', methods=['POST'])
        @as_json
        def encode_query():
            data = request.form if request.form else request.json
            try:
                logger.info('new request from %s' % request.remote_addr)
                return {'id': data['id'],
                        'result': bc.encode(data['texts'], is_tokenized=bool(
                            data['is_tokenized']) if 'is_tokenized' in data else False)}

            except Exception as e:
                logger.error('error when handling HTTP request', exc_info=True)
                raise JsonError(description=str(e), type=str(type(e).__name__))

        CORS(app, origins=self.args.cors)
        FlaskJSON(app)
        Compress().init_app(app)
        return app