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 get_users():
    """
    get users
    ---
    tags:
      - user
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 #3
0
    ride_requests_ref = db.collection(u'contextText')
    current_ride_request_ref = ride_requests_ref.document()
    current_ride_request_id = current_ride_request_ref.id
    current_ride_request_ref.set(current_ride_request_json)
    return current_ride_request_id, 200


@app.errorhandler(500)
def server_error(e):
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500


if __name__ == '__main__':
    # flasgger for hosting REST API docs
    template = spec.to_flasgger(
        app,
        definitions=[
            schemas.LuggageCollectionSchema, schemas.LuggageItemSchema
        ],
        # paths=[random_pet]
    )
    swagger = Swagger(app, template=template)
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)
    gradings = list(filter(lambda grading: grading.type_of_day == type_of_day, available_gradings))
    if not gradings:
        raise NotFound("No gradings for this type of day found")

    result_schema = AvailableGradingSchema(only=('id', 'due_date', 'type_of_day', 'tile_name', 'time_interval'))

    result = list([result_schema.dump(grading).data for grading in gradings])
    return jsonify(result)


available_gradings: List[AvailableGrading] = initializer.load_available_gradings(OEVGK18_METADATA_PATH)

template = spec.to_flasgger(
    app,
    definitions=[AvailableGradingSchema],
    paths=[get_available_gradings, get_available_days]
)

swagger_config = {
    "headers": [],
    "specs": [
        {
            "endpoint": 'apispec',
            "route": '/api/apispec.json',
            "rule_filter": lambda rule: True,  # all in
            "model_filter": lambda tag: True,  # all in
        }
    ],
    "static_url_path": "/apidocs/flasgger_static",
    "swagger_ui": True,
    A cute furry animal endpoint.
    Get a random pet
    ---
    description: Get a random pet
    responses:
        200:
            description: A pet to be returned
            schema:
                $ref: '#/definitions/Pet'
    """
    pet = {'category': [{'id': 1, 'name': 'rodent'}], 'name': 'Mickey'}
    return jsonify(PetSchema().dump(pet).data)


template = spec.to_flasgger(app,
                            definitions=[CategorySchema, PetSchema],
                            paths=[random_pet])
"""
optionally if using apisepc.APISpec from original module
you can do:

from flasgger.utils import apispec_to_template
template = apispec_to_template(
    app=app,
    spec=spec,
    definitions=[CategorySchema, PetSchema],
    paths=[random_pet]
)

"""
Exemple #6
0
    """
    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)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=config['server']['port'])