Exemplo n.º 1
0
class ServerlessOpenAPI:
    def __init__(self, app: Flask) -> None:
        app.config.update({
            'APISPEC_SPEC': make_apispec(title='Flask API', version='v1'),
            'APISPEC_SWAGGER_URL': '/swagger/',
        })
        self.apispec = FlaskApiSpec(app)

    def register_all(self):
        """Generate documentation.

        Call after all views loaded.
        """
        self.apispec.register_existing_resources()
Exemplo n.º 2
0
    def test_apispec_config(self, app):
        app.config['APISPEC_TITLE'] = 'test-extension'
        app.config['APISPEC_VERSION'] = '2.1'
        docs = FlaskApiSpec(app)

        assert docs.spec.info == {
            'title': 'test-extension',
            'version': '2.1',
        }
Exemplo n.º 3
0
    def test_apispec_config(self, app):
        app.config['APISPEC_TITLE'] = 'test-extension'
        app.config['APISPEC_VERSION'] = '2.1'
        app.config['APISPEC_OAS_VERSION'] = '2.0'
        docs = FlaskApiSpec(app)

        assert docs.spec.title == 'test-extension'
        assert docs.spec.version == '2.1'
        assert docs.spec.openapi_version == '2.0'
Exemplo n.º 4
0
def setup_swagger(app):
    app.config.update({
        'APISPEC_SPEC':
        APISpec(title='Flask Template',
                version='v1',
                plugins=['apispec.ext.marshmallow'],
                securityDefinitions={
                    "json-web-token": {
                        "in": "header",
                        "name": "Authorization",
                        "type": "apiKey"
                    }
                },
                tags=[]),
        'APISPEC_SWAGGER_URL':
        '/swagger.json'
    })
    docs = FlaskApiSpec(app)
    docs.register_existing_resources()
Exemplo n.º 5
0
def init_app(app):
    """Register API resources on the provided Flask application."""
    def register(path, resource):
        app.add_url_rule(path, view_func=resource.as_view(resource.__name__))
        docs.register(resource, endpoint=resource.__name__)

    docs = FlaskApiSpec(app)
    register("/submit", Submit)
    register("/status/<string:uuid>", Status)
    register("/report/<string:uuid>", Report)
Exemplo n.º 6
0
def init_app(app):
    """Register API resources on the provided Flask application."""
    def register(path, resource):
        app.add_url_rule(path, view_func=resource.as_view(resource.__name__))
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            docs.register(resource, endpoint=resource.__name__)

    docs = FlaskApiSpec(app)
    app.add_url_rule('/healthz', healthz.__name__, healthz)
    register('/designs', DesignsResource)
    register('/designs/<int:design_id>', DesignResource)
Exemplo n.º 7
0
def create_app():
    if os.environ.get("environment") == "production":
        config = ProductionConfig()
    else:
        config = DevelopmentConfig()
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    CORS(app)
    app.config.from_object(config)

    # sqlalchemy db setup
    app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.init_app(app)
    # this needs to be called sometime before you interact with the database
    # with app.app_context():
    #     db.create_all()

    # register blueprints
    app.register_blueprint(hello.blueprint)

    # apispec
    app.config.update({
        "APISPEC_SPEC":
        APISpec(
            title="savegroup",
            version="v1",
            plugins=[MarshmallowPlugin()],
            openapi_version="3.0.2",
        ),
        "APISPEC_SWAGGER_URL":
        "/swagger/",
    })

    # swagger docs
    docs = FlaskApiSpec(app)
    docs.register(hello.hello, blueprint="hello_page")

    return app
Exemplo n.º 8
0
def init_app(app):
    """Register API resources on the provided Flask application."""
    def register(path, resource):
        app.add_url_rule(path, view_func=resource.as_view(resource.__name__))
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            docs.register(resource, endpoint=resource.__name__)

    docs = FlaskApiSpec(app)
    register("/predictions", PredictionJobsResource)
    register("/predictions/<int:job_id>", PredictionJobResource)
    register("/predictions/export/<int:job_id>", JobExportResource)
    register("/products", ProductsResource)
Exemplo n.º 9
0
def init_app(app):
    """Register API resources on the provided Flask application."""
    def register(path, resource):
        app.add_url_rule(path, view_func=resource.as_view(resource.__name__))
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            docs.register(resource, endpoint=resource.__name__)

    docs = FlaskApiSpec(app)
    app.add_url_rule("/healthz", view_func=healthz)
    register("/reactions", ReactionResource)
    register("/reactions/batch", ReactionBatchResource)
    register("/metabolites", MetaboliteResource)
    register("/metabolites/batch", MetaboliteBatchResource)
Exemplo n.º 10
0
def register_docs(app):
    app.config.update({
        'APISPEC_SPEC':
        APISpec(
            title='RESTful API for oneapi.cc backend',
            version='v1',
            openapi_version="2.0.0",
            plugins=[MarshmallowPlugin()],
        ),
        'APISPEC_SWAGGER_URL':
        '/swagger/',
    })
    docs = FlaskApiSpec(app)
    docs.register(register_user, endpoint="register_user", blueprint="user")
    docs.register(login_user, blueprint="user")
    docs.register(get_profile, blueprint="profiles")
Exemplo n.º 11
0
 def init_docs(self):
     """method to bind docs with api instance."""
     self.app.config.update({
         'APISPEC_SPEC':
         APISpec(title=self.title,
                 version=self.version,
                 info={'description': self.spec_description()},
                 plugins=self.plugins,
                 openapi_version='2.0'),
         'APISPEC_SWAGGER_URL':
         self.swagger_json_url,
         'APISPEC_SWAGGER_UI_URL':
         self.swagger_url,
     })
     return FlaskApiSpec(self.app)
Exemplo n.º 12
0
    def init_doc(self):
        """Config and init auto-docs for api version"""
        self.app.config.update({
            'APISPEC_SPEC': APISpec(
                title=self.title,
                version=self.version,
                info={'description': self.spec_description()},
                plugins=self.plugins,
                openapi_version='2.0'
            ),
            'APISPEC_SWAGGER_URL': self.swagger_json_url,
            'APISPEC_SWAGGER_UI_URL': self.swagger_url,
        })

        return FlaskApiSpec(self.app)
Exemplo n.º 13
0
def init_app(app):
    """Register API resources on the provided Flask application."""
    app.add_url_rule("/healthz", view_func=healthz)
    app.add_url_rule("/metrics", view_func=metrics)

    app.add_url_rule("/models/<int:model_id>/modify",
                     view_func=model_modify,
                     methods=["POST"])
    app.add_url_rule("/simulate", view_func=model_simulate, methods=["POST"])
    app.add_url_rule("/community/simulate",
                     view_func=model_community_simulate,
                     methods=["POST"])

    docs = FlaskApiSpec(app)
    docs.register(model_modify, endpoint=model_modify.__name__)
    docs.register(model_simulate, endpoint=model_simulate.__name__)
    docs.register(model_community_simulate,
                  endpoint=model_community_simulate.__name__)
Exemplo n.º 14
0
def docs_config(app):

    app.config.update({
        'APISPEC_SPEC':
        APISpec(title='API Tren',
                version='v1',
                plugins=[MarshmallowPlugin()],
                openapi_version='2.0.0'),
        'APISPEC_SWAGGER_URL':
        '/swagger/',  # URI to access API Doc JSON 
        'APISPEC_SWAGGER_UI_URL':
        '/docs/'  # URI to access UI of API Doc
    })

    docs = FlaskApiSpec(app)

    return docs
def init_app(app):
    """Register API resources on the provided Flask application."""

    def register(path, resource):
        app.add_url_rule(path, view_func=resource.as_view(resource.__name__))
        with warnings.catch_warnings():
            # Silence the following warning:
            #   apispec/ext/marshmallow/common.py:145: UserWarning: Multiple
            #   schemas resolved to the name Organism. The name has been
            #   modified. Either manually add each of the schemas with a
            #   different name or provide a custom schema_name_resolver.
            # This happens due to `exclude` usage in the schema which makes
            # apispec create a new model, and that's the correct behaviour.
            warnings.simplefilter("ignore")
            docs.register(resource, endpoint=resource.__name__)

    docs = FlaskApiSpec(app)
    app.add_url_rule("/healthz", view_func=healthz)
    register("/hello", HelloResource)
Exemplo n.º 16
0
 def swagger_setup(self,
                   app,
                   title: str = 'Serverless App',
                   version: str = 'v1'):
     """Add swagger documentation."""
     from flask_apispec.extension import FlaskApiSpec
     from apispec import APISpec
     # swagger
     app.config.update({
         'APISPEC_SPEC':
         APISpec(
             title=title,
             version=version,
             plugins=[MarshmallowPlugin()],
         ),
         'APISPEC_SWAGGER_URL':
         '/swagger/',
     })
     FlaskApiSpec(app)
Exemplo n.º 17
0
def init_app(app):
    """Register API resources on the provided Flask application."""
    def register(path, resource):
        app.add_url_rule(path, view_func=resource.as_view(resource.__name__))
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            docs.register(resource, endpoint=resource.__name__)

    docs = FlaskApiSpec(app)
    app.add_url_rule('/healthz', healthz.__name__, healthz)
    app.add_url_rule('/metrics', metrics.__name__, metrics)
    register("/authenticate/local", LocalAuthResource)
    register("/authenticate/firebase", FirebaseAuthResource)
    register("/refresh", RefreshResource)
    register("/keys", PublicKeysResource)
    register("/projects", ProjectsResource)
    register("/projects/<project_id>", ProjectResource)
    register("/user", UserResource)
    register("/user", UserRegisterResource)
    register("/consent", ConsentResource)
    register("/password/reset-request", ResetRequestResource)
    register("/password/reset/<token>", PasswordResetResource)
Exemplo n.º 18
0
    def test_deferred_register(self, app):
        blueprint = Blueprint('test', __name__)
        docs = FlaskApiSpec()

        @doc(tags=['band'])
        class BandResource(MethodResource):
            def get(self, **kwargs):
                return 'slowdive'

        blueprint.add_url_rule('/bands/<band_id>/',
                               view_func=BandResource.as_view('band'))
        docs.register(BandResource, endpoint='band', blueprint=blueprint.name)

        app.register_blueprint(blueprint)
        docs.init_app(app)

        assert '/bands/{band_id}/' in docs.spec._paths
Exemplo n.º 19
0
def create_app():
    app = Flask(__name__)
    app.config['JWT_SECRET_KEY'] = JWT_SECRET_KEY
    JWTManager(app)

    app.config.update({
        'APISPEC_SPEC':
        APISpec(
            title='Wishlist API',
            version='v1',
            plugins=[MarshmallowPlugin()],
            openapi_version='2.0.0',
            info={
                'description':
                'REST API to manage customers and their wishlists.'
            },
            securityDefinitions={
                'JWT': {
                    'type': 'apiKey',
                    'in': 'header',
                    'name': 'Authorization'
                }
            },
        ),
        'APISPEC_SWAGGER_URL':
        '/swagger/',
    })
    docs = FlaskApiSpec(app)

    start_mappers()

    register_urls(app, docs)

    app.register_error_handler(Exception, handle_exception)

    return app
Exemplo n.º 20
0
# Setup API docs and Swagger
from .core import app
from .auth import add_auth_to_swagger
from apispec import APISpec
from flask_apispec.extension import FlaskApiSpec
import webargs as wa
from apispec.ext.marshmallow import MarshmallowPlugin

file_plugin = MarshmallowPlugin()
spec = APISpec(
    title='neuroscout',
    version='v1',
    plugins=[file_plugin],
    openapi_version='2.0'
)
app.config.update({
    'APISPEC_SPEC': spec})
add_auth_to_swagger(spec)

docs = FlaskApiSpec(app)


@file_plugin.map_to_openapi_type('file', None)
class FileField(wa.fields.Raw):
    pass
Exemplo n.º 21
0
app = Flask(__name__)
CORS(app)
cache = Cache(app, config={"CACHE_TYPE": "simple"})
app.config.update(
    {
        "APISPEC_SPEC": APISpec(
            title="DGDS backend",
            openapi_version="2.0.0",
            version="1.0",
            plugins=[MarshmallowPlugin()],
        ),
        "APISPEC_SWAGGER_URL": "/swagger/",
    }
)
docs = FlaskApiSpec(app)

# Configuration load
app.config.from_object("dgds_backend.default_settings")
try:
    app.config.from_envvar("DGDS_BACKEND_SETTINGS")
except (RuntimeError, FileNotFoundError) as e:
    print(
        "Could not load config from environment variables"
    )  # logging not set yet [could not read config]

# only catch error if we're not in debug mode
if not app.debug:
    app.register_blueprint(error_handler.error_handler)

# Logging setup
    db.create_all()

login_manager = LoginManager()
# login_manager.login_view = 'auth.login'
login_manager.init_app(app)


@login_manager.user_loader
def load_user(user_id):
    # since the user_id is just the primary key of our user table, use it in the query for the user
    return User.query.get(int(user_id))


from api import *

docs = FlaskApiSpec(app)
api_bp = Blueprint('api', __name__)
api = Api(api_bp)

cross_origin(['http://localhost:8080'])
socketio = SocketIO(app, cors_allowed_origins="*", cors_credentials=True)
CORS(app, supports_credentials=True)

api.add_resource(ProfileAPI, '/', endpoint="profile", methods=['GET'])
api.add_resource(ProfileAPI,
                 '/id/<id>',
                 endpoint="profile_id",
                 methods=['GET'])
api.add_resource(ProfileAPI,
                 '/api/profile/reset/',
                 endpoint="reset_password",
Exemplo n.º 23
0
def docs(app):
    return FlaskApiSpec(app)
Exemplo n.º 24
0
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from .schemas import UserSchema


app = Flask(__name__)
app.config.update({
    "APISPEC_SPEC": APISpec(title="bank",
                            version="v1",
                            openapi_version="2.0",
                            plugins=[MarshmallowPlugin()]),
    "APISPEC_SWAGGER_URL": "/swagger/"
})

docs = FlaskApiSpec()

client = app.test_client()

engine = create_engine("sqlite:///bank/db.sqlite")
session = scoped_session(sessionmaker(autocommit=False,
                                      autoflush=False,
                                      bind=engine))

Base = declarative_base()
Base.query = session.query_property()
# importing here because of circular import error
from .models import *
Base.metadata.create_all(bind=engine)

# place for future
Exemplo n.º 25
0
 def test_serve_swagger_custom_url(self, app, client):
     app.config['APISPEC_SWAGGER_URL'] = '/swagger.json'
     docs = FlaskApiSpec(app)
     res = client.get('/swagger.json')
     assert res.json == docs.spec.to_dict()
Exemplo n.º 26
0
 def test_serve_swagger_ui_custom_url(self, app, client):
     app.config['APISPEC_SWAGGER_UI_URL'] = '/swagger-ui.html'
     FlaskApiSpec(app)
     client.get('/swagger-ui.html')
Exemplo n.º 27
0
    return "users {}".format(kwargs)

# resources

class MethodResourceMeta(ResourceMeta, flask.views.MethodViewType):
    pass

class MethodResource(six.with_metaclass(MethodResourceMeta, flask.views.MethodView)):
    methods = None

class UserResource(MethodResource):

    def get(self, _id):
        return 'get'

    @use_kwargs({'_id': fields.Str()})
    def post(self, **kwargs):
        return Pet(**kwargs)

    @use_kwargs({'_id': fields.Str()})
    def put(self, _id, **kwargs):
        return 'put'

    def delete(self, _id):
        return make_response('delete', 204)

docs = FlaskApiSpec(app)
docs.register(list_users)
docs.register(UserResource) # this fails to be found
# see http://0.0.0.0:5000/swagger/
Exemplo n.º 28
0
app.config.update({
    'APISPEC_SPEC': APISpec(
        title='pets',
        version='v1',
        info=dict(
            description='A minimal user API',
            **kwargs
        ),
        tags=[
            {
                "name": "crawl",
                "description": "Operations about crawl"
            },
        ],
    # openapi_version='3.0.1',
    plugins=[MarshmallowPlugin()],
    ),
    'APISPEC_SWAGGER_URL': '/swagger/',
    'APISPEC_SWAGGER_UI_URL' : None
})
docs = FlaskApiSpec(app)

# app.add_url_rule('/pet/<name>', view_func=PetResource.as_view('PetResource'))
print(app.url_map._rules_by_endpoint)
'''
endpoint must equal as_view name 
e.g: PetResource.as_view('pet') => as_view name: pet == endpoint="pet"
'''
docs.spec.definition('User', schema=CrawlSchema)
docs.register(AllResource, blueprint="api_crawl", endpoint="crawl")
# docs.register(get_pets, blueprint="api_v1")
Exemplo n.º 29
0
api = Api(app)

@app.route('/pets')
@use_kwargs({'category': fields.Str(), 'size': fields.Str()})
def get_pets(**kwargs):
    return {'something': 'here', 'size': kwargs['size'], 'category': kwargs['category']}

class UserResource(MethodResource):
    def get(self, id):
        return 'asdf'
    def put(self, id):
        return 'asdf'
    def delete(self, id):
        return 'asdf'

app.config.update({
    'APISPEC_SPEC': APISpec(
        title='pets',
        version='v1',
        plugins=['apispec.ext.marshmallow'],
    ),
    'APISPEC_SWAGGER_URL': '/swagger/',
})

docs = FlaskApiSpec(app)
docs.register(get_pets)
# docs.register(UserResource)

if __name__ == '__main__':
    app.run(debug=True)
Exemplo n.º 30
0
import requests

app = Flask(__name__)  # Flask app instance initiated
api = Api(app)  # Flask restful wraps Flask app around it.
app.config.update({
    'APISPEC_SPEC':
    APISpec(title='current account Api',
            version='v1',
            plugins=[MarshmallowPlugin()],
            openapi_version='2.0'),
    'APISPEC_SWAGGER_URL':
    '/swagger/',  # URI to access API Doc JSON
    'APISPEC_SWAGGER_UI_URL':
    '/swagger-ui/'  # URI to access UI of API Doc
})
docs = FlaskApiSpec(app)


class ExpensesResponseSchema(Schema):
    name = fields.String()
    amount = fields.Float()
    categoryId = fields.Number()


class BalanceDataSchema(Schema):
    bank_id = fields.String()
    account_id = fields.String()
    balance = fields.Float()
    expenses = fields.Nested(ExpensesResponseSchema, many=True)

Exemplo n.º 31
0
app = Flask(__name__)
app.config.from_object(Config)

client = app.test_client()

engine = create_engine('sqlite:///db.sqlite')

session = scoped_session(
    sessionmaker(autocommit=False, autoflush=False, bind=engine))

Base = declarative_base()
Base.query = session.query_property()

jvt = JWTManager(app)

docs = FlaskApiSpec()
docs.init_app(app)

app.config.update({
    'APISPEC_SPEC':
    APISpec(
        title='videoblog',
        version='v1',
        openapi_version='2.0',
        plugins=[MarshmallowPlugin()],
    ),
    'APISPEC_SWAGGER_URL':
    '/swagger/'
})
from models import *
Exemplo n.º 32
0
app.config['SQLALCHEMY_DATABASE_URI'] = settings.DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config.update({
    'APISPEC_SPEC': APISpec(
        title=settings.API_TITLE,
        version=settings.API_VERSION,
        plugins=[MarshmallowPlugin()],
        openapi_version='2.0.0'
    ),
    'APISPEC_SWAGGER_URL': settings.SWAGGER_API_URL,   # URI to access API Doc JSON
    'APISPEC_SWAGGER_UI_URL': settings.SWAGGER_UI_URL  # URI to access UI of API Doc
})

api = Api(app)
docs = FlaskApiSpec(app)
db.init_app(app)


# If not, create all tables in the database
@app.before_first_request
def create_tables():
    db.create_all()


# JWT Config
app.config['JWT_SECRET_KEY'] = 'wallace'
app.config['JWT_BLACKLIST_ENABLED'] = True                        # enable blacklist feature
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']  # allow blacklisting for access and refresh tokens
jwt = JWTManager(app)                                             # URI to generate token in /login
Exemplo n.º 33
0
app = Flask(__name__)
api = Api(app)

app.config["DEBUG"] = True
# Swagger setting
app.config.update({
    'APISPEC_SPEC':
    APISpec(title='Awesome Project',
            version='v1',
            plugins=[MarshmallowPlugin()],
            openapi_version='2.0.0'),
    'APISPEC_SWAGGER_URL':
    '/swagger/',  # URI to access API Doc JSON
    'APISPEC_SWAGGER_UI_URL':
    '/swagger-ui/'  # URI to access UI of API Doc
})
docs = FlaskApiSpec(app)

api.add_resource(Brand_volume, '/search_brand')
docs.register(Brand_volume)
api.add_resource(Corp_volume, '/search_corp')
docs.register(Corp_volume)
api.add_resource(Platform_volume, '/search_platform')
docs.register(Platform_volume)
api.add_resource(Search_Branch_volume, '/search_branch')
docs.register(Search_Branch_volume)
api.add_resource(Search_comment, '/search_comment')
docs.register(Search_comment)

if __name__ == '__main__':
    app.run()