Example #1
0
def app():
    app = Sanic('sanic_test_app')

    # App Handlers
    async def hello_world(request):
        return HTTPResponse(body="Hello World")

    @describe(paths="/api/v1/user/{user}", methods="GET")
    async def get_path_parameters(request, user: str) -> str:
        return user

    @describe(paths="/api/v1/group/", methods="GET")
    async def get_path_parameters_list(request, group: [str] = None) -> str:
        if not group:
            group = []
        group = sorted(group)
        return ",".join(group)

    @describe(paths="/api/v1/env/", methods="GET")
    async def get_parameters_optional(request, exist: bool = False) -> bool:
        return exist

    @describe(paths="/multiply")
    async def get_query_parameters(request, left: int, right: int) -> int:
        return left * right

    @describe(paths="/killme")
    async def handle_exceptions(request) -> User:
        raise ServerError("Something bad happened", status_code=500)

    @describe(paths="/api/v1/user/missing")
    async def handle_api_exception(request) -> User:
        raise APIException("Something bad happened", code=404)

    @describe(paths="/api/v1/headers/",
              response_types={
                  200: {
                      "type": str,
                      "description": "success",
                      "headers": {
                          "location": {
                              "description": "url to the location",
                              "type": str
                          }
                      }
                  }
              })
    async def get_headers(request):
        return Response(
            "headers",
            headers={"location": "foooo"},
        )

    @describe(paths="/body_and_header",
              methods="POST",
              body_parameters=["body"],
              header_parameters=["header"])
    async def body_and_header_params(request, body: str, header: str) -> bool:
        return body == header

    # Routes
    app.add_route(hello_world, "/", methods=["GET"])
    add_route(app, get_path_parameters)
    add_route(app, get_parameters_optional)
    add_route(app, get_path_parameters_list)
    add_route(app, get_query_parameters)
    add_route(app, handle_exceptions)
    add_route(app, handle_api_exception)
    add_route(app, get_headers)
    add_route(app, body_and_header_params)

    # Blueprints
    @describe(paths="/multiply")
    async def get_blueprint_params(request, left: int, right: int) -> str:
        res = left * right
        return "{left}*{right}={res}".format(left=left, right=right, res=res)

    bp = Blueprint("test_blueprints", url_prefix="/blueprint")
    add_route(bp, get_blueprint_params)
    app.blueprint(bp)

    # Swagger
    add_swagger(app, "/api/v1/swagger.json", "/api/v1/")

    return app
Example #2
0
web_app.blueprint(api_blueprint_group)
web_app.error_handler.add(BaseError, sanic_error_handler(400))
web_app.error_handler.add(NotFound, sanic_error_handler(404))
web_app.error_handler.add(InvalidUsage, sanic_error_handler(400))
web_app.error_handler.add(Exception, sanic_error_handler(500))


# web_app.blueprint(swagger_blueprint)
# web_app.config.API_VERSION = '1.0.0'
# web_app.config.API_TITLE = 'Summer Sanic'
# web_app.config.API_DESCRIPTION = 'Summer Sanic'
# web_app.config.API_PRODUCES_CONTENT_TYPES = ['application/json']


add_swagger(web_app, "/swagger.json", "swagger")


# doc.route_specs[1].description = 'olololo'
# print(f"doc.route_specs: {doc.route_specs}")

# SWAGGER_ATTR_NAME = "_tranmute_swagger"
#
# if not hasattr(web_app, SWAGGER_ATTR_NAME):
#     setattr(web_app, SWAGGER_ATTR_NAME, SwaggerSpec())
#
# app._tranmute_swagger.add_path('/ttt/users', )

if __name__ == "__main__":
    web_app.run(host="0.0.0.0", port=8080, debug=True, auto_reload=False)
Example #3
0
    raise ServerError("Something bad happened", status_code=500)


@describe(paths="/api/v1/user/missing")
async def handle_api_exception(request) -> User:
    """
    API Description: Handle APIException. This will show in the swagger page (localhost:8000/api/v1/).
    """
    raise APIException("Something bad happened", code=404)


@describe(paths="/multiply")
async def get_blueprint_params(request, left: int, right: int) -> str:
    """
    API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/).
    """
    res = left * right
    return "{left}*{right}={res}".format(left=left, right=right, res=res)


if __name__ == "__main__":
    add_route(app, test_transmute_get)
    add_route(app, test_transmute_post)
    add_route(app, handle_exception)
    add_route(app, handle_api_exception)
    # register blueprints
    add_route(bp, get_blueprint_params)
    app.blueprint(bp)
    # add swagger
    add_swagger(app, "/api/v1/swagger.json", "/api/v1/")
    app.run(host="0.0.0.0", port=8000)
Example #4
0
def create_app(**kwargs):
    app = Sanic(__name__)
    app.blueprint(api)
    add_swagger(app, "/api/swagger.json", "/api/docs")
    return app