コード例 #1
0
def set_routes(app: Flask, bp: Blueprint, docs: FlaskApiSpec):
    # a list of resources
    resources = [
        (LocationResource, "/locations/<string:slug>/customers", "customers", ["POST"]),
    ]

    for resource, route, name, methods in resources:
        bp.add_url_rule(route, view_func=resource.as_view(name), methods=methods)

    app.register_blueprint(bp)

    for resource, route, name, methods in resources:
        docs.register(resource, blueprint=bp_name, endpoint=name)
コード例 #2
0
ファイル: docs.py プロジェクト: kodesmil/flask_products
 def __init__(self, app):
     app.config.update({
         'APISPEC_SPEC': APISpec(
             title='KodeSmil Flask',
             version='v1',
             openapi_version="3.0.2",
             info=dict(description='KodeSmil microservices API'),
             plugins=[MarshmallowPlugin()],
         ),
         'APISPEC_SWAGGER_UI_URL': '/docs/',
     })
     self.docs = FlaskApiSpec(app)
     self._initialize()
コード例 #3
0
def register_blueprints(app):
    app.register_blueprint(blueprints_blueprint,
                           url_prefix=API_BASE_URL + 'blueprints')
    app.register_blueprint(jobs_blueprint, url_prefix=API_BASE_URL + 'jobs')
    app.register_blueprint(operations_blueprint,
                           url_prefix=API_BASE_URL + 'operations')

    # Swagger
    docs = FlaskApiSpec(app)

    from .jobs.routes import get_job

    docs.register(get_job, blueprint="jobs")
コード例 #4
0
    def __init__(self, app, url, **config):
        app.config.update({
            'APISPEC_SPEC':
            APISpec(**config,
                    plugins=[MarshmallowPlugin()],
                    **self.__default_security_schema()),
            'APISPEC_SWAGGER_UI_URL':
            url,
            'APISPEC_SWAGGER_URL':
            url + '.json'
        })

        self.app = app
        self.doc = FlaskApiSpec(app)
        self.__register_security_schema()
コード例 #5
0
def set_routes(app: Flask, bp: Blueprint, docs: FlaskApiSpec):
    # a list of resources
    resources = [
        (ImageResource, "/search/", "img", ["GET"]),
        (ReverseImageResource, "/reverse_search/", "reverse_image", ["POST"]),
    ]

    for resource, route, name, methods in resources:
        bp.add_url_rule(route,
                        view_func=resource.as_view(name),
                        methods=methods)

    app.register_blueprint(bp)

    for resource, route, name, methods in resources:
        docs.register(resource, blueprint=bp_name, endpoint=name)
コード例 #6
0
def _register_openapi(app):
    from ursh.schemas import TokenSchema, URLSchema
    with app.app_context():
        spec = APISpec(
            openapi_version='3.0.2',
            title='ursh - URL Shortener',
            version='2.0',
            plugins=(
                FlaskPlugin(),
                MarshmallowPlugin(),
            ),
        )
        spec.components.schema('Token', schema=TokenSchema)
        spec.components.schema('URL', schema=URLSchema)
        app.config['APISPEC_SPEC'] = spec
        apispec = FlaskApiSpec(app)
        apispec.register_existing_resources()
コード例 #7
0
def set_routes(app: Flask, bp: Blueprint, docs: FlaskApiSpec):
    # a list of resources
    resources = [
        (UsersResource, "/users/", "users", ["GET", "POST"]),
        (UserResource, "/users/<string:user_id>", "user",
         ["GET", "PATCH", "DELETE"]),
    ]

    for resource, route, name, methods in resources:
        bp.add_url_rule(route,
                        view_func=resource.as_view(name),
                        methods=methods)

    app.register_blueprint(bp)

    for resource, route, name, methods in resources:
        docs.register(resource, blueprint=bp_name, endpoint=name)
コード例 #8
0
def register_blueprints(app: Flask):
    """Register Flask blueprints."""
    app.config.update({"APISPEC_SPEC": APISPEC_SPEC})
    docs = FlaskApiSpec(app)

    from blueprints.images import images_bp
    from blueprints.images import routes as image_routes

    image_routes.set_routes(app, images_bp, docs)
コード例 #9
0
def register_blueprints(app: Flask):
    """ Register Flask blueprints. """
    app.config.update({"APISPEC_SPEC": APISPEC_SPEC})
    docs = FlaskApiSpec(app)

    # example blueprint
    from blueprints.example import example_bp
    from blueprints.example import routes as example_routes

    example_routes.set_routes(app, example_bp, docs)
コード例 #10
0
def create_app(env_name):

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

    bcrypt.init_app(app)
    db.init_app(app)

    app.register_blueprint(user_blueprint, url_prefix='/garden/v1/users')
    app.register_blueprint(device_blueprint, url_prefix='/garden/v1/devices')

    docs = FlaskApiSpec(app)
    docs.register(devices.create, blueprint=device_blueprint)

    @app.route('/', methods=['GET'])
    def index():
        return 'blah blah blah'

    return app
コード例 #11
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("/models", Models)
    register("/models/<int:id>", IndvModel)
コード例 #12
0
def init_app(app: Flask):
    global FileField

    docs = FlaskApiSpec(document_options=False)
    ma = MarshmallowPlugin()
    spec = APISpec(
        title=app.config.get("APISPEC_TITLE", "API Docs"),
        version=app.config.get("APISPEC_VERSION", "v1"),
        openapi_version=app.config.get("APISPEC_OAS_VERSION", "2.0"),
        plugins=[ma],
        securityDefinitions=app.config.get("APISPEC_SECURITY_DEFINITIONS", {}),
    )

    @ma.map_to_openapi_type("file", None)
    class FileField(fields.Raw):
        pass

    app.config.update({"APISPEC_SPEC": spec})
    docs.init_app(app)
    app.extensions["apispec"] = docs
コード例 #13
0
ファイル: app.py プロジェクト: salmanmaq/inspire-classifier
def create_app():
    Flask.response_class = JsonResponse
    app = Flask(__name__)
    app.config['CLASSIFIER_BASE_PATH'] = app.instance_path
    app.config.from_object('inspire_classifier.config')
    docs = FlaskApiSpec(app)

    @app.route("/api/health")
    def date():
        """Basic endpoint that returns the date, used to check if everything is up and working."""
        now = datetime.datetime.now()
        return jsonify(now)

    docs.register(date)

    @app.route("/api/predict/coreness", methods=["POST"])
    @use_kwargs({
        'title': fields.Str(required=True),
        'abstract': fields.Str(required=True)
    })
    @marshal_with(serializers.ClassifierOutputSerializer)
    def core_classifier(**kwargs):
        """Endpoint for the CORE classifier."""

        return predict_coreness(kwargs['title'], kwargs['abstract'])

    docs.register(core_classifier)

    return app

    @app.errorhandler(404)
    def page_not_found(e):
        return {"errors": [str(e)]}, 404
コード例 #14
0
ファイル: app.py プロジェクト: FrancescElies/flask-bcolz
def create_app():
    app = Flask(__name__)
    app.config['PROPAGATE_EXCEPTIONS'] = True
    docs = FlaskApiSpec(app)

    app.add_url_rule('/data/<path:folder>/chunks',
                     view_func=DataResource.as_view('DataResource'))
    docs.register(DataResource, endpoint='DataResource')

    app.add_url_rule('/status', view_func=Status.as_view('Status'))
    docs.register(Status, endpoint='Status')

    return app
コード例 #15
0
 def __init__(self):
     app = Flask(__name__)
     add_flask_profiler(app)
     with app.app_context():
         log.info(
             f"starting {settings.APP_NAME} server on {settings.API.SERVER}"
         )
     CORS(app)
     self.app = app
     self.docs = FlaskApiSpec(app)
     self.lineProfiler = line_profiler()
     log.info(
         f"starting {settings.APP_NAME} mongo connector {settings.MONGO}")
     self.mongo = MongoConnector(settings.MONGO)
     log.info(
         f"starting {settings.APP_NAME} postgres connector {settings.POSTGRES}"
     )
     self.postgres = Postgres(settings.POSTGRES)
     """
         When worker fork's the parent process, the db engine & connection pool is included in that.
         But, the db connections should not be shared across processes, so we tell the engine
         to dispose of all existing connections, which will cause new ones to be opened in the child
         processes as needed.
         More info:
         https://docs.sqlalchemy.org/en/latest/core/pooling.html#using-connection-pools-with-multiprocessing
     """
     with app.app_context():
         self.postgres.get_engine().dispose()
     log.info(
         f"starting {settings.APP_NAME} redis connector {settings.REDIS}")
     self.redis = RedisConnector(settings.REDIS)
     log.info(
         f"starting {settings.APP_NAME} rq dashboard at http://"
         f"{settings.API.SERVER.url}:{settings.API.SERVER.port}{settings.API.VERSION}{settings.APP_NAME}/rq"
     )
     app.config["RQ_DASHBOARD_REDIS_URL"] = settings.REDIS.url
     log.info(f"starting {settings.APP_NAME} redis job queues")
     self.redisJobQueues = RedisJobQueues(self.redis.get_redis_conn())
     log.info(f"starting {settings.APP_NAME} redis job queues")
     self.redisJobQueues = RedisJobQueues(self.redis.get_redis_conn())
     log.info(
         f"started {settings.APP_NAME} server on {settings.API.SERVER}")
コード例 #16
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config.Config')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    app.config.update({
        'APISPEC_TITLE': 'Pylerplate',
        'APISPEC_VERSION': 'Pylerplate',
        'APISPEC_SWAGGER_URL': '/swagger/',
        'APISPEC_SWAGGER_UI_URL': None,
    })

    app.__docs__ = FlaskApiSpec(app)
    initialize_extensions(app)
    register_handlers(app)
    CORS(app)

    register_routes(app)

    return app
コード例 #17
0
def main():
    app = Flask('MySchemaApp')
    docs = FlaskApiSpec(app)

    parser = argparse.ArgumentParser()
    parser.add_argument('-x', dest='xvalue', type=str, help='the x value', default='hello')
    parser.add_argument('-y', dest='yvalue', type=int, help='the y value', default=10)

    MySchema = parser_to_schema(parser, 'MySchema')
    my_schema = MySchema()

    
    @docs.register
    @app.route('/api')
    @use_kwargs(MySchema, locations=['query'])
    def handler(**kwargs):
        obj = my_schema.load(kwargs)
        print('recv args: {}'.format(kwargs))
        print('recv obj: {}'.format(obj))
        return my_schema.dump(obj)

    return app
コード例 #18
0
def register_spec(app):
    app.config.update({
        "APISPEC_SPEC":
        APISpec(
            title="Flask VRFs API",
            version="0.0.1",
            openapi_version="2.0",
            plugins=[MarshmallowPlugin()],
        ),
        "APISPEC_SWAGGER_URL":
        "/api/docs/apispec.json",
        "APISPEC_SWAGGER_UI_URL":
        "/api/docs",
    })
    docs = FlaskApiSpec(app)
    from app.api.vrf.views import Vrf

    docs.register(Vrf, blueprint="api")
    from app.api.vrfs.views import Vrfs

    docs.register(Vrfs, blueprint="api")
コード例 #19
0
ファイル: __init__.py プロジェクト: homerzhm/SkinColorDetect
from flask import Flask, redirect
from flask_apispec import FlaskApiSpec
from .skin_detect import *
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
import cv2
from flask import jsonify

app = Flask(__name__)

docs = FlaskApiSpec(app)

app.add_url_rule('/skin_detect',
                 view_func=ImageEndPoint.as_view('skin_detect'))

docs.register(ImageEndPoint, endpoint="skin_detect")

import skin_detector

UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

コード例 #20
0
ファイル: main.py プロジェクト: petrishutin/flask_crud_api
app = Flask(__name__)
app.config.from_object(config)
app.url_map.strict_slashes = False
app.config.update({'APISPEC_SPEC': spec})

jwt = JWTAuth(app)

api = Api(app)
api.add_resource(Users, '/users')
api.add_resource(LogIn, '/login')
api.add_resource(LogOut, '/logout')
api.add_resource(ToDosGetAllPost, '/todos/<string:username>')
api.add_resource(ToDosGetByIdPutDelete,
                 '/todos/<string:username>/<int:todo_id>')

docs = FlaskApiSpec(app)
docs.register(Users)
docs.register(LogIn)
docs.register(LogOut)
docs.register(ToDosGetAllPost)
docs.register(ToDosGetByIdPutDelete)

fields_to_add_bearer_security_check = {
    '/logout': ('get', ),
    '/todos/{username}': ('get', 'post'),
    '/todos/{username}/{todo_id}': ('get', 'put', 'delete')
}
update_paths_with_bearer_security_check(spec,
                                        fields_to_add_bearer_security_check)

if __name__ == '__main__':
コード例 #21
0
ファイル: petstore.py プロジェクト: subhamagr/flask-apispec
        pass


class PetResource(CrudResource):
    schema = PetSchema


###

import flask
import flask.views

from flask_apispec import FlaskApiSpec

app = flask.Flask(__name__)
docs = FlaskApiSpec(app)


@app.route('/pets/<pet_id>')
@doc(params={'pet_id': {'description': 'pet id'}})
@marshal_with(PetSchema)
@use_kwargs({'breed': ma.fields.Str()})
def get_pet(pet_id):
    return Pet('calici', 'cat')


docs.register(get_pet)


class MethodResourceMeta(ResourceMeta, flask.views.MethodViewType):
    pass
コード例 #22
0
ファイル: rest.py プロジェクト: 18F/openFEC
)

api.add_resource(filings.FilingsList, '/filings/')

api.add_resource(download.DownloadView, '/download/<path:path>/')

api.add_resource(legal.UniversalSearch, '/legal/search/')
api.add_resource(legal.GetLegalCitation, '/legal/citation/<citation_type>/<citation>')
api.add_resource(legal.GetLegalDocument, '/legal/docs/<doc_type>/<no>')

app.config.update({
    'APISPEC_SWAGGER_URL': None,
    'APISPEC_SWAGGER_UI_URL': None,
    'APISPEC_SPEC': spec.spec,
})
apidoc = FlaskApiSpec(app)

apidoc.register(search.CandidateNameSearch, blueprint='v1')
apidoc.register(search.CommitteeNameSearch, blueprint='v1')
apidoc.register(candidates.CandidateView, blueprint='v1')
apidoc.register(candidates.CandidateList, blueprint='v1')
apidoc.register(candidates.CandidateSearch, blueprint='v1')
apidoc.register(candidates.CandidateHistoryView, blueprint='v1')
apidoc.register(committees.CommitteeView, blueprint='v1')
apidoc.register(committees.CommitteeList, blueprint='v1')
apidoc.register(committees.CommitteeHistoryView, blueprint='v1')
apidoc.register(reports.ReportsView, blueprint='v1')
apidoc.register(reports.CommitteeReportsView, blueprint='v1')
apidoc.register(reports.EFilingHouseSenateSummaryView, blueprint='v1')
apidoc.register(reports.EFilingPresidentialSummaryView, blueprint='v1')
apidoc.register(reports.EFilingPacPartySummaryView, blueprint='v1')
コード例 #23
0
ファイル: rest.py プロジェクト: nbedi/openFEC
api.add_resource(
    filings.FilingsView,
    '/committee/<committee_id>/filings/',
    '/candidate/<candidate_id>/filings/',
)
api.add_resource(filings.FilingsList, '/filings/')

api.add_resource(download.DownloadView, '/download/<path:path>/')

app.config.update({
    'APISPEC_SWAGGER_URL': None,
    'APISPEC_SWAGGER_UI_URL': None,
    'APISPEC_SPEC': spec.spec,
})
apidoc = FlaskApiSpec(app)

apidoc.register(search.CandidateNameSearch, blueprint='v1')
apidoc.register(search.CommitteeNameSearch, blueprint='v1')
apidoc.register(candidates.CandidateView, blueprint='v1')
apidoc.register(candidates.CandidateList, blueprint='v1')
apidoc.register(candidates.CandidateSearch, blueprint='v1')
apidoc.register(candidates.CandidateHistoryView, blueprint='v1')
apidoc.register(committees.CommitteeView, blueprint='v1')
apidoc.register(committees.CommitteeList, blueprint='v1')
apidoc.register(committees.CommitteeHistoryView, blueprint='v1')
apidoc.register(reports.ReportsView, blueprint='v1')
apidoc.register(totals.TotalsView, blueprint='v1')
apidoc.register(sched_a.ScheduleAView, blueprint='v1')
apidoc.register(sched_b.ScheduleBView, blueprint='v1')
apidoc.register(sched_e.ScheduleEView, blueprint='v1')
コード例 #24
0
ファイル: __init__.py プロジェクト: RahulPalve/openforms
import os
from flask import Flask
from flask_mongoengine import MongoEngine
from flask_restful import Api
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_apispec import FlaskApiSpec
from celery import Celery
from .tasks import make_celery
from .config import configs

env = os.environ.get("FLASK_ENV", "development")
db = MongoEngine()
rest_api = Api()
docs = FlaskApiSpec()
celery = Celery(
    __name__, broker=configs[env].CELERY_BROKER_URL, backend=configs[env].CELERY_RESULT_BACKEND
)


def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(configs[env])
    app.config.update({
            'APISPEC_SPEC': APISpec(
                title='openforms',
                version='v1',
                openapi_version='2.0',
                plugins=[MarshmallowPlugin()],
            ),
            'APISPEC_SWAGGER_URL': '/swagger/',
コード例 #25
0
        try:
            data = jwt.decode(token, os.environ['JWT_ENCODE'])
            current_user = '******'
        except:
            return jsonify({'message': 'token is invalid'})
        return f(current_user, *args, **kwargs)
    return decorator

# Retrieves a given user in path
@app.route('/user/<email_address>', methods=['GET'])
@token_required
@marshal_with(LoginResponseSchema, code=200)
@marshal_with(ErrorSchema, code=400)
def user_handle(email_address):
    body = {"email": email_address}
    user_object = User(body)
    result = user_object.get_user()
    if result['statusCode'] == 200:
        return result['response'], 200
    return result['response'], 400


# Perform auto-documentation
docs = FlaskApiSpec(app)
docs.register(login)
docs.register(user_handle)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
コード例 #26
0

# Restful api configuration
api = Api(app)
api.add_resource(PersonApiList, "/v1/person/")
api.add_resource(PersonApi, "/v1/person/<int:id>/")
# Swagger documentation configuration
app.config.update({
    'APISPEC_SPEC':
    APISpec(
        title='Test Chassis Service',
        version='1.0.0-b1',
        openapi_version="2.0",
        plugins=[MarshmallowPlugin()],
        info=dict(
            description="Flask resource chassis swagger documentation demo",
            license={
                "name": "Apache 2.0",
                "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
            })),
    'APISPEC_SWAGGER_URL':
    '/swagger/',
})

docs = FlaskApiSpec(app)
docs.register(PersonApiList)
docs.register(PersonApi)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5010)
コード例 #27
0
ファイル: app.py プロジェクト: proplaner/back-end
@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()


@app.after_request
def after_request(response):
    """Close the database connection after each request."""
    db_session.commit()
    return response


# Flask RESTful API
api = Api(app)
docs = FlaskApiSpec(app)

resources = {
    # Account resources
    '/api/account/api': ApiKey,
    '/api/account/available_algorithms': AvailableAlgorithms,
    '/api/account/available_exchanges': AvailableExchanges,
    '/api/account/balances': AccountBalances,
    '/api/account/save_email': SaveEmail,
    '/api/account/save_password': SavePassword,
    '/api/account/save_second_factor': SaveSecondFactor,
    '/api/account/second_factor_secret': SecondFactorSecret,
    '/api/account/save_setting': SaveUserSetting,
    '/api/account/user': UserResource,
    '/api/account/valuations': AccountValuations,
コード例 #28
0
from . import settings
from .middlewares import (
    HTTPMethodOverrideMiddleware, )
from .extensions import (
    Webpack, )
from . import commands

db = SQLAlchemy()
ds_client = None
cache = Cache()
user_datastore = None
security = None
mail = Mail()
babel = Babel()
marshmallow = Marshmallow()
api_spec = FlaskApiSpec()


def create_app(config_object=settings):
    app = Flask(__name__)
    app.config.from_object(config_object)

    global ds_client
    ds_client = datastore.Client()

    register_extensions(app)
    register_middlewares(app)
    register_commands(app)
    init_security(app)
    register_blueprints(app)
コード例 #29
0
ファイル: flask_raas.py プロジェクト: aspinuso/s-provenance
    app.run()
    # app.logger.info("Server running....")
 
from apispec import APISpec
app.config.update({
    'APISPEC_SPEC': APISpec(
        title='s-prov',
        version='v1',
        plugins=['apispec.ext.marshmallow'],
        schemes=['http','https'],
        description="S-ProvFlow provenance API - Provenance framework for storage and access of data-intensive streaming lineage. It offers a a web API and a range of dedicated visualisation tools and a provenance model (S-PROV) which utilises and extends PROV and ProvONE model"
    
    ),
    'APISPEC_SWAGGER_URL': '/swagger/',
    })
docs = FlaskApiSpec(app)


docs.register(insert_provenance)
docs.register(wfexec_description_edit)
docs.register(delete_workflow_run)

docs.register(get_workflow_info)
docs.register(get_workflowexecutions)
#docs.register(get_instances_monitoring)
docs.register(get_monitoring)
docs.register(get_invocation_details)
docs.register(get_instance_details)

docs.register(filter_on_ancestor)
docs.register(get_data_item)
コード例 #30
0
ファイル: __init__.py プロジェクト: MTES-MCT/mobilic-api
from app.helpers.request_parser import CustomRequestParser

app = Flask(__name__)
app.config.update({
    "APISPEC_SPEC":
    APISpec(
        title="Mobilic",
        version="v1",
        openapi_version="3.0.0",
        plugins=[MarshmallowPlugin()],
    ),
    "APISPEC_WEBARGS_PARSER":
    CustomRequestParser(),
})

docs = FlaskApiSpec(app)

env = os.environ.get("MOBILIC_ENV", "dev")
app.config.from_object(getattr(config, f"{env.capitalize()}Config"))

siren_api_client = SirenAPIClient(app.config["SIREN_API_KEY"])
mailer = Mailer(app)

if app.config["SENTRY_URL"]:
    sentry_sdk.init(
        dsn=app.config["SENTRY_URL"],
        integrations=[FlaskIntegration()],
        environment=env,
    )

db = SQLAlchemyWithStrongRefSession(
コード例 #31
0
ファイル: petstore.py プロジェクト: jmcarp/flask-apispec
    @marshal_with(None, code=204)
    def delete(self, id):
        pass

class PetResource(CrudResource):
    schema = PetSchema

###

import flask
import flask.views

from flask_apispec import FlaskApiSpec

app = flask.Flask(__name__)
docs = FlaskApiSpec(app)

@app.route('/pets/<pet_id>')
@doc(params={'pet_id': {'description': 'pet id'}})
@marshal_with(PetSchema)
@use_kwargs({'breed': ma.fields.Str()})
def get_pet(pet_id):
    return Pet('calici', 'cat')

docs.register(get_pet)

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

class MethodResource(six.with_metaclass(MethodResourceMeta, flask.views.MethodView)):
    methods = None
コード例 #32
0
def build_routes(app):
    """Register routes to given app instance."""
    app.config.update({
        'APISPEC_SPEC':
        APISpec(
            title=SERVICE_NAME,
            openapi_version=OPENAPI_VERSION,
            version=API_VERSION,
            plugins=[MarshmallowPlugin()],
        ),
        'APISPEC_SWAGGER_URL':
        API_SPEC_URL,
    })
    app.register_blueprint(cache_blueprint)
    app.register_blueprint(dataset_blueprint)

    swaggerui_blueprint = get_swaggerui_blueprint(
        SWAGGER_URL, API_SPEC_URL, config={'app_name': 'Renku Service'})
    app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

    docs = FlaskApiSpec(app)

    docs.register(upload_file_view, blueprint=CACHE_BLUEPRINT_TAG)
    docs.register(list_uploaded_files_view, blueprint=CACHE_BLUEPRINT_TAG)
    docs.register(project_clone, blueprint=CACHE_BLUEPRINT_TAG)
    docs.register(list_projects_view, blueprint=CACHE_BLUEPRINT_TAG)

    docs.register(create_dataset_view, blueprint=DATASET_BLUEPRINT_TAG)
    docs.register(add_file_to_dataset_view, blueprint=DATASET_BLUEPRINT_TAG)
    docs.register(list_datasets_view, blueprint=DATASET_BLUEPRINT_TAG)
    docs.register(list_dataset_files_view, blueprint=DATASET_BLUEPRINT_TAG)
コード例 #33
0
ファイル: demo02.py プロジェクト: johnny-cy/Demo_extensions
    def __init__(self, name, type):
        self.name = name
        self.type = type



class PetSchema(Schema):
    name = fields.Str()
    type = fields.Str()

pet_schema = PetSchema( only=['name', 'type'])

from flask import Flask, views
from flask_apispec import FlaskApiSpec


app = Flask(__name__)
docs = FlaskApiSpec(app)


@app.route("/pets/<pet_id>")
@doc(params={'pet_id': {'description': 'pet_id'}}) # swagger 
@marshal_with(pet_schema)
def get_pet(pet_id):
    return Pet('hehe', 'cat')

docs.register(get_pet) # register method get_pet to swagger

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)
コード例 #34
0
ファイル: petstore.py プロジェクト: Nobatek/flask-apispec
    @marshal_with(None, code=204)
    def delete(self, id):
        pass

class PetResource(CrudResource):
    schema = PetSchema

###

import flask
import flask.views

from flask_apispec import FlaskApiSpec

app = flask.Flask(__name__)
docs = FlaskApiSpec(app)

@app.route('/pets/<pet_id>')
@doc(params={'pet_id': {'description': 'pet id'}})
@marshal_with(PetSchema)
@use_kwargs({'breed': ma.fields.Str()})
def get_pet(pet_id):
    return Pet('calici', 'cat')

docs.register(get_pet)

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

class MethodResource(six.with_metaclass(MethodResourceMeta, flask.views.MethodView)):
    methods = None
コード例 #35
0
ファイル: rest.py プロジェクト: srinivasmalladi/openFEC
)

api.add_resource(
    filings.FilingsView,
    '/committee/<committee_id>/filings/',
    '/candidate/<candidate_id>/filings/',
)
api.add_resource(filings.FilingsList, '/filings/')


app.config.update({
    'APISPEC_SWAGGER_URL': None,
    'APISPEC_SWAGGER_UI_URL': None,
    'APISPEC_SPEC': spec.spec,
})
apidoc = FlaskApiSpec(app)

apidoc.register(CandidateNameSearch, blueprint='v1')
apidoc.register(CommitteeNameSearch, blueprint='v1')
apidoc.register(candidates.CandidateView, blueprint='v1')
apidoc.register(candidates.CandidateList, blueprint='v1')
apidoc.register(candidates.CandidateSearch, blueprint='v1')
apidoc.register(candidates.CandidateHistoryView, blueprint='v1')
apidoc.register(committees.CommitteeView, blueprint='v1')
apidoc.register(committees.CommitteeList, blueprint='v1')
apidoc.register(committees.CommitteeHistoryView, blueprint='v1')
apidoc.register(reports.ReportsView, blueprint='v1')
apidoc.register(totals.TotalsView, blueprint='v1')
apidoc.register(sched_a.ScheduleAView, blueprint='v1')
apidoc.register(sched_b.ScheduleBView, blueprint='v1')
apidoc.register(sched_e.ScheduleEView, blueprint='v1')