Exemple #1
0
def create_app():
    # ---------- App Configuration ----------
    app = Flask(__name__)
    app.config.from_object(
        'config.Config')  # Load configurations from Config class

    # Init SQLAlchemy and Marshmallow
    db.init_app(app)
    ma.init_app(app)

    # Register Flask Blueprints
    app.register_blueprint(candidate_blueprint, url_prefix='/api/')
    app.register_blueprint(job_blueprint, url_prefix='/api/')
    app.register_blueprint(skill_blueprint, url_prefix='/api/')

    # ---------- Swagger ----------

    # Create an APISpec
    spec = APISpec(title='CandidateFinder REST API',
                   version='1.0',
                   openapi_version='2.0',
                   plugins=[FlaskPlugin(), MarshmallowPlugin()])
    template = spec.to_flasgger(app, definitions=[CandidateSchema, JobSchema])

    # Set the UIVERSION to 3
    app.config['SWAGGER'] = {'uiversion': 3}

    # Start Flasgger using a template from APISpec
    swag = Swagger(app, template=template)

    return app
def create_app():
    # ---------- App Configuration ----------
    app = Flask(__name__)
    app.config.from_object(
        'config.Config')  # Load configurations from Config class

    # Init SQLAlchemy and Marshmallow
    db.init_app(app)
    ma.init_app(app)

    # Register Flask Blueprints
    app.register_blueprint(user_blueprint, url_prefix='/api/')
    app.register_blueprint(message_blueprint, url_prefix='/api/')

    # ---------- Swagger ----------
    # Create an APISpec
    spec = APISpec(title='MessagingSystem REST API',
                   version='1.0',
                   openapi_version='2.0',
                   plugins=[FlaskPlugin(), MarshmallowPlugin()])
    template = spec.to_flasgger(app, definitions=[UserSchema, MessageSchema])
    # Start Flasgger using a template from APISpec
    swag = Swagger(app, template=template)

    # Make Swagger the main page
    @app.route("/")
    def index():
        return redirect('/apidocs/')

    return app
Exemple #3
0
def create_app():

    app = Flask(__name__)
    app.config.from_object("backend.config.cfg")
    register_extensions(app)

    # register blueprints
    app.register_blueprint(player_blueprint)

    # define swagger
    spec = APISpec(
    title=cfg.APISPEC['title'],
    version=cfg.APISPEC['version'],
    openapi_version=cfg.APISPEC['openapi_version'],
    plugins=[FlaskPlugin(), MarshmallowPlugin()]
    )

    template = spec.to_flasgger(
        app=app,
        definitions=[PlayerSchema],
        paths=[get_players]
    )

    swag = Swagger(app, template=template)

    return app
Exemple #4
0
def setup_swagger(app):
    spec = APISpec(title='dodo',
                   version='0.0.1',
                   plugins=['apispec.ext.flask', 'apispec.ext.marshmallow'])
    template = spec.to_flasgger(app,
                                definitions=[ProductSchema, ItemSchema],
                                paths=[get_items, get_products])
    swag = Swagger(app, template=template)
Exemple #5
0
def fetch_flasgger_template(app):
    # Create an APISpec
    title = settings.APP_NAME.replace("-", " ")
    version = settings.VERSION
    spec = APISpec(title=title, version=version, openapi_version="3.0", plugins=[MarshmallowPlugin()])

    template = spec.to_flasgger(app, definitions=[], paths=[])
    return template
Exemple #6
0
def register_extensions(app: Flask) -> None:
    api.init_app(app)
    mongodb.init_app(app)
    swagger.init_app(app)
    spec = APISpec(
        title=app.config['SWAGGER']['title'],
        version='1.0.0',
        openapi_version=app.config['SWAGGER']['openapi'],
        plugins=[FlaskPlugin()],
    )
    swagger.template = spec.to_flasgger(app)
Exemple #7
0
def swag_init(app):
    # Create an APISpec
    spec = APISpec(title='Messaging App',
                   version='1.0',
                   openapi_version='2.0',
                   plugins=[FlaskPlugin(), MarshmallowPlugin()])

    template = spec.to_flasgger(
        app,
        definitions=[MessageSchema],
    )

    # set the UIVERSION to 3
    app.config['SWAGGER'] = {'uiversion': 3}

    # start Flasgger using a template from apispec
    swag = Swagger(app, template=template)
    return swag
Exemple #8
0
def configure_openapi_with_flask(app: Flask):
    spec = APISpec(
        title="Python API",  # noqa
        version=__version__,  # noqa
        openapi_version="2.0",  # noqa
        plugins=[  # noqa
            FlaskPlugin(),
            MarshmallowPlugin(),
        ],
    )

    template = spec.to_flasgger(
        app,
        definitions=[
            LivenessSchema,
            HealthCheckSchema,
            UserSchema,
        ],
    )

    Swagger(app, template=template)
def configure_spec(app):
    ma.init_app(app)
    app.config['SWAGGER'] = {'uiversion': 3}
    spec = APISpec(
        title='Private Identity Server',
        version='0.0.0',
        openapi_version='2.0',
        plugins=[
            FlaskPlugin(),
            MarshmallowPlugin(),
        ],
    )
    template = spec.to_flasgger(app, definitions=definitions)
    template['securityDefinitions'] = {
        'basicAuth': {
            'type': 'basic'
        },
        'Bearer': {
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header'
        }
    }
    Swagger(app, template=template)
"""
Example using marshmallow APISpec as base template for Flasgger specs
"""
# coding: utf-8
from flask import Flask, jsonify

from flasgger import APISpec, Schema, Swagger, fields

# Create an APISpec
spec = APISpec(
    title='Flasger Petstore',
    version='1.0.10',
    plugins=[
        'apispec.ext.flask',
        'apispec.ext.marshmallow',
    ],
)

app = Flask(__name__)


# Optional marshmallow support
class CategorySchema(Schema):
    id = fields.Int()
    name = fields.Str(required=True)


class PetSchema(Schema):
    category = fields.Nested(CategorySchema, many=True)
    name = fields.Str()
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    csrf.init_app(app)
    oauth.init_app(app)
    RQ(app)
    api = Api(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .api.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from app.api.docs import docs as docs_blueprint
    app.register_blueprint(docs_blueprint)

    from flasgger import APISpec, Schema, Swagger, fields

    spec = APISpec(
        title='REST API',
        version='1.0.0',
        plugins=[
            'apispec.ext.flask',
            'apispec.ext.marshmallow',
        ],
    )

    app.config['SWAGGER'] = {'title': 'REST API', 'uiversion': 3}

    swagger = Swagger(app,
                      template={
                          'swagger': '3.0',
                          'info': {
                              'title': 'REST API',
                              'version': '1.0'
                          }
                      })

    from app.api.v1.building import Building, BuildingList

    building_view = Building.as_view('Building')
    app.add_url_rule('/v1/buildings/<int:building_id>',
                     view_func=building_view)

    building_list_view = BuildingList.as_view('BuildingList')
    app.add_url_rule('/v1/buildings', view_func=building_list_view)

    with app.test_request_context():
        spec.add_path(view=building_view)
        spec.add_path(view=building_list_view)

    return app
Exemple #12
0
from app.settings import create_app, db
from core.urls import core_urls, api
from core.schema import UserSchema, AuthSchema
from search.urls import search_urls
from search.schema import ProductSchema

# Load environment file
load_dotenv('.env')

# Create an APISpec
spec = APISpec(
    title='Price Comparison Extension',
    version='0.0.1',
    openapi_version='2.0',
    plugins=[
        FlaskPlugin(),
        MarshmallowPlugin(),
    ],
)

app = create_app(os.getenv('FLASK_APP_ENV') or 'dev')

# Import module URLs
app.register_blueprint(core_urls)
app.register_blueprint(search_urls)

# # Config swagger
# template = {
#     "swagger": "2.0",
#     "info": {
Exemple #13
0
Example using marshmallow APISpec as base template for Flasgger specs
and using the Swagger UI new style layout version 3
"""
# coding: utf-8
from flask import Flask, jsonify

from flasgger import APISpec, Schema, Swagger, fields
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin

# Create an APISpec
spec = APISpec(
    title='Flasger Petstore',
    version='1.0.10',
    openapi_version='2.0',
    plugins=[
        FlaskPlugin(),
        MarshmallowPlugin(),
    ],
)

app = Flask(__name__)


# Optional marshmallow support
class CategorySchema(Schema):
    id = fields.Int()
    name = fields.Str(required=True)


class PetSchema(Schema):
Exemple #14
0
def create_docs(app):

    # Create an APISpec
    # info: {
    spec = APISpec(
        title="ClassClock API",
        version="0.1",
        openapi_version='2.0',
        plugins=[
            FlaskPlugin(),
            MarshmallowPlugin(),
        ],
        # options= {
        #     "description": "The development version of the ClassClock API",
        #     "servers": [
        #         {
        #             "url": "https://api.classclock.app/v0",
        #             "description": "ClassClock API Server"
        #         },
        #         {
        #             "url": "https://*****:*****@me.com",
        #             # "url": "www.me.com",
        #         },
        #         "termsOfService": "http://me.com/terms",
        # }
    )

    template = spec.to_flasgger(app,
                                definitions=[SchoolSchema, BellScheduleSchema],
                                paths=[get_school, get_bellschedule])

    # config={
    #     "headers": [
    #     ],
    # "specs": [
    #     {
    #         "endpoint": 'apispec_v1',
    #         "route": '/apispec_v1.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": "/v0/docs/",
    #     "basePath": "/docs",
    #     "host": "api.classclock.app",  # overrides localhost:500
    #     "schemes": [
    #         "https"
    #     ],
    #     "securityDefinitions": {
    #         "ApiKeyAuth": {
    #             "type": "apiKey",
    #             "in": "header",
    #             "name": "Authentication"
    #         }
    #     }
    # },

    # template["basePath"] = "/docs"
    swagger = Swagger(app, template=template)
    return swagger
Exemple #15
0
def create_app(config_name):
    app = Flask(__name__, static_folder='static')
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    csrf.init_app(app)
    oauth.init_app(app)
    oauthclient.init_app(app)
    RQ(app)

    db.app = app

    cors = CORS(app,
                resources={
                    r"/api/v1/*": {
                        "origins": "*"
                    },
                    r"/auth/oauth/*": {
                        "origins": "*"
                    }
                })
    api = Api(app)
    babel.init_app(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not os.environ.get('SSL_DISABLE'):
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .api.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from app.api.docs import docs as docs_blueprint
    app.register_blueprint(docs_blueprint)

    from flasgger import APISpec, Schema, Swagger, fields

    spec = APISpec(
        title='Bhagavad Gita API',
        version='1.0.0',
        plugins=[
            'apispec.ext.flask',
            'apispec.ext.marshmallow',
        ],
    )

    app.config['SWAGGER'] = {'title': 'Bhagavad Gita API', 'uiversion': 3}

    swagger = Swagger(app,
                      template={
                          'swagger': '2.0',
                          'info': {
                              'title': 'Bhagavad Gita API',
                              'version': '1.0'
                          }
                      })

    from app.api.v1.verse import VerseList, VerseListByChapter, VerseByChapter
    from app.api.v1.chapter import Chapter, ChapterList

    verse_list_view = VerseList.as_view('VerseList')
    app.add_url_rule('/api/v1/verses', view_func=verse_list_view)

    verse_list_chapter_view = VerseListByChapter.as_view('VerseListChapter')
    app.add_url_rule('/api/v1/chapters/<int:chapter_number>/verses',
                     view_func=verse_list_chapter_view)

    verse_chapter_view = VerseByChapter.as_view('VerseChapter')
    app.add_url_rule(
        '/api/v1/chapters/<int:chapter_number>/verses/<string:verse_number>',
        view_func=verse_chapter_view)

    chapter_view = Chapter.as_view('Chapter')
    app.add_url_rule('/api/v1/chapters/<int:chapter_number>',
                     view_func=chapter_view)

    chapter_list_view = ChapterList.as_view('ChapterList')
    app.add_url_rule('/api/v1/chapters', view_func=chapter_list_view)

    def _force_https():
        if not app.debug:
            from flask import _request_ctx_stack
            if _request_ctx_stack is not None:
                reqctx = _request_ctx_stack.top
                reqctx.url_adapter.url_scheme = 'https'

    app.before_request(_force_https)

    with app.test_request_context():
        spec.add_path(view=verse_list_view)
        spec.add_path(view=verse_list_chapter_view)
        spec.add_path(view=verse_chapter_view)
        spec.add_path(view=chapter_view)
        spec.add_path(view=chapter_list_view)

    return app
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.flask import FlaskPlugin
from flasgger import APISpec, Swagger
from flask import Flask, redirect, request, jsonify
from marshmallow import ValidationError

import db
from schema import get_all_schemas, UserSchema

spec = APISpec(
    title="marshmallow-with-flasgger",
    version="0.1.0",
    openapi_version="2.0",
    plugins=[FlaskPlugin(), MarshmallowPlugin()],
)

flask_app = Flask(__name__)
flask_app.config["JSON_AS_ASCII"] = False
flask_app.config["SWAGGER"] = {"uiversion": 3}
flask_app.config["SECRET_KEY"] = "secret key"

_template = spec.to_flasgger(flask_app, definitions=get_all_schemas())
_swag = Swagger(flask_app, template=_template)


@flask_app.route("/", methods=["GET"])
def index():
    return redirect("apidocs")


@flask_app.route("/users", methods=["GET"])
def create_app():
    """Application factory based on:
    https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/#basic-factories
    https://flask.palletsprojects.com/en/1.1.x/tutorial/factory/#the-application-factory
    """
    app = Flask(__name__,
                static_url_path='/static/css',
                static_folder='./static/css')
    CORS(app)

    # ---
    # CONFIGURATION
    # ---
    app.config.from_object(os.environ['APP_SETTINGS'])
    app.config['JSON_SORT_KEYS'] = False
    app.config['SESSION_TYPE'] = 'filesystem'  # Flask-Session
    Session(app)

    # ---
    # MODELS
    # ---
    from tcm_app.models import db
    db.init_app(app)
    migrate = Migrate(app, db)

    # ---
    # AUTHORIZATION
    # ---
    from tcm_app import auth
    app.register_blueprint(auth.bp)
    auth.oauth.init_app(app)

    # ---
    # API ENDPOINTS
    # ---
    from tcm_app import api
    app.register_blueprint(api.bp)

    # ---
    # SWAGGER
    # ---
    spec = APISpec(
        title='Trade Compliance Monitor',
        version='0.0.1',
        openapi_version='3.0.2',
        plugins=[
            FlaskPlugin(),
            MarshmallowPlugin(),
        ],
        tags=[{
            'name': 'trades',
        }],
        components={
            'securitySchemes': {
                #  https://swagger.io/docs/specification/authentication/
                'bearerAuth': {
                    'type': 'http',
                    'scheme': 'bearer',
                    'bearerFormat': 'JWT'
                },
                # Alternative authorization. Requires pasting Client Id as well
                # as checking boxes for scope, but applies the token
                # automatically.
                'implicitFlow': {
                    'type': 'oauth2',
                    'flows': {
                        'implicit': {
                            'authorizationUrl':
                            ('{}/authorize?audience={}'.format(
                                app.config['AUTH0_API_BASE_URL'],
                                app.config['AUTH0_AUDIENCE'])),
                            'scopes': {
                                'openid': '',
                                'email': ''
                            }
                        }
                    }
                },

                # # Currently not implemented
                # # Alternative authorization. Requires pasting Client Id and
                # # Secret as well as checking boxes for scope, but applies the
                # # token automatically.
                # 'authorizationCodeFlow': {
                #     'type': 'oauth2',
                #     'flows': {
                #         'authorizationCode': {
                #             'authorizationUrl': (
                #                 '{}/authorize?audience={}'.format(
                #                     app.config['AUTH0_API_BASE_URL'],
                #                     app.config['AUTH0_AUDIENCE']
                #                 )
                #             ),
                #             'tokenUrl': '{}/oauth/token'.format(
                #                 app.config['AUTH0_API_BASE_URL']
                #             ),
                #             'scopes': {
                #                 'openid': '',
                #                 'email': ''
                #             }
                #         }
                #     }
                # }
            }
        },
        security=[
            {
                'bearerAuth': [],
            },
            {
                'implicitFlow': []
            },
            # # Currently not implemented
            # {
            #     'authorizationCodeFlow': []
            # }
        ])
    swagger_template = spec.to_flasgger(app, definitions=[TradeSchema])

    app.config['SWAGGER'] = {
        'uiversion': '3',
        'openapi': '3.0.2',
        'ui_params': {
            # Needed for implicitFlow
            'oauth2RedirectUrl':
            '{}/oauth2-redirect'.format(app.config['SWAGGER_BASE_URL']),
            'tagsSorter':
            'alpha'
        }
    }

    Swagger(app, template=swagger_template)

    return app
Exemple #18
0
from gravitate.context import Context
from gravitate import schemas

# Firebase Admin SDK
# Deprecated: Moved to be invoked by app engine cron on '/groupAll'
# sched = BackgroundScheduler(daemon=True)
# sched.add_job(refreshGroupAll, 'interval', minutes=1)
# sched.start()

# Flasgger docs
# Create an APISpec
spec = APISpec(
    title='Gravitate REST API',
    version='0.0.1',
    openapi_version='2.0',
    plugins=[
        FlaskPlugin(),
        MarshmallowPlugin(),
    ],
)

# Initialize Flask
firebase_request_adapter = requests.Request()
app = Flask(__name__)

db = Context.db
parser = reqparse.RequestParser()


class EndpointTestService(Resource):
    method_decorators = [authenticate]
from flasgger import APISpec, Swagger
from flask import Flask, request, jsonify
from werkzeug.exceptions import NotFound, BadRequest

from backend import initializer
from backend.model.availablegrading import AvailableGrading
from backend.schemas import AvailableGradingSchema

OEVGK18_METADATA_PATH = 'data/oevgk18_metadata.json'

app = Flask(__name__)

spec = APISpec(
    title='OeVGK18 Backend',
    version='1.0',
    plugins=[
        'apispec.ext.flask',
        'apispec.ext.marshmallow',
    ],
)


@app.route('/api/typesOfDays', methods=['GET'])
def get_available_days():
    """
    file: api_schemas/typesOfDays.yml
    """
    unique_days = set([grading.type_of_day for grading in available_gradings])

    return jsonify({'days': list(unique_days)})

Exemple #20
0
from flasgger import APISpec
from .calls import create_call, get_bill
from .schemas import CallStartEndSchema, BillSchema, BillDetailSchema

spec = APISpec(
    title="Olist Technical Challenge - REST api",
    version='1.0',
    plugins=[
        'apispec.ext.flask',
        'apispec.ext.marshmallow',
    ],
    contact={
        "name": "André Felipe Dias",
        "url": "https://pronus.io",
        "email": "*****@*****.**",
    },
    route='/v1/spec',
)

definitions = [CallStartEndSchema, BillSchema, BillDetailSchema]
paths = [create_call, get_bill]
Exemple #21
0
        200:
            description: List of all regions
            schema:
              $ref: '#/definitions/RegionsResponse'
    """
    options = openproject.get_custom_field_options(
        FACILITY_REGION_FIELD_ID_NUM)
    return RegionsResponseSchema.from_options(options)


# noinspection PyArgumentList
spec = APISpec(
    title='WorkPackage Manager',
    version='1.0',
    openapi_version='2.0',
    plugins=[
        FlaskPlugin(),
        MarshmallowPlugin(),
    ],
)

app.register_blueprint(api)

template = spec.to_flasgger(
    app,
    definitions=[HCPRequestSchema, RegionsResponseSchema],
    paths=[hcp_request_post, regions_get])

swagger_config = Swagger.DEFAULT_CONFIG.copy()
swagger_config['specs_route'] = '{}/apidocs/'.format(BASE_URL)
swag = Swagger(app, template=template, config=swagger_config)
Exemple #22
0
from .config import app_config
from .models import db, bcrypt
from .models.UserModel import UserSchema
from .models.LocationModel import LocationSchema
from .views.UserView import user_api as user_blueprint
from .views import UserView #UserView import create, login, get_all, get_a_user, get_me, update, delete
from .views import LocationView
from .views.LocationView import location_api as location_blueprint
from flasgger import Swagger, APISpec

# noinspection PyArgumentList

spec = APISpec(
    title='Location App',
    version='1.0.0',
    plugins=[
        'apispec.ext.flask',
        'apispec.ext.marshmallow'
    ]
)

def create_app(env_name):
    """
    Create the app
    """

    # app initialization
    app = Flask(__name__)
    app.config.from_object(app_config[env_name])

    # initializing bcrypt
    bcrypt.init_app(app)