Esempio n. 1
0
    def app(self):
        app_ = Flama()

        @app_.route("/product", methods=["POST"])
        def product_identity(product: Product) -> Product:
            return product

        @app_.route("/reviewed-product", methods=["POST"])
        def reviewed_product_identity(reviewed_product: ReviewedProduct) -> ReviewedProduct:
            return reviewed_product

        @app_.route("/place", methods=["POST"])
        def place_identity(place: Place) -> Place:
            return place

        @app_.route("/many-products", methods=["GET"])
        def many_products() -> Product(many=True):
            return [
                {
                    "name": "foo",
                    "rating": 0,
                    "created": datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),
                },
                {
                    "name": "bar",
                    "rating": 1,
                    "created": datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc),
                },
            ]

        @app_.route("/serialization-error")
        def serialization_error() -> Product:
            return {"rating": "foo", "created": "bar"}

        return app_
Esempio n. 2
0
    def app(self):
        app_ = Flama(title="Foo", version="0.1", description="Bar", schema="/schema/")

        @app_.route("/page-number/", methods=["GET"])
        @Paginator.page_number
        def page_number(**kwargs) -> OutputSchema(many=True):
            return [{"value": i} for i in range(25)]

        return app_
Esempio n. 3
0
    def app(self):
        app_ = Flama(title="Foo", version="0.1", description="Bar", schema="/schema/")

        @app_.route("/limit-offset/", methods=["GET"])
        @Paginator.limit_offset
        def limit_offset(**kwargs) -> OutputSchema(many=True):
            return [{"value": i} for i in range(25)]

        return app_
Esempio n. 4
0
    def test_unhandled_component(self):
        with pytest.raises(
                ConfigurationError,
                match=
                r'Component "UnhandledComponent" must include a return annotation on the `resolve\(\)` method, '
                "or override `can_handle_parameter`",
        ):
            app_ = Flama(components=[UnhandledComponent()])

            @app_.route("/")
            def foo(unknown: Unknown):
                return JSONResponse({"foo": "bar"})

            client = TestClient(app_)

            client.get("/")
Esempio n. 5
0
    def app(self):
        app_ = Flama(
            components=[],
            title="Foo",
            version="0.1",
            description="Bar",
            schema="/schema/",
            docs="/docs/",
            redoc="/redoc/",
        )

        @app_.route("/endpoint/", methods=["GET"])
        class PuppyEndpoint(HTTPEndpoint):
            async def get(self) -> Puppy:
                """
                description: Custom component.
                responses:
                  200:
                    description: Component.
                """
                return {"name": "Canna"}

        @app_.route("/custom-component/", methods=["GET"])
        async def get(self) -> Puppy:
            """
            description: Custom component.
            responses:
              200:
                description: Component.
            """
            return {"name": "Canna"}

        @app_.route("/many-custom-component/", methods=["GET"])
        async def many_custom_component() -> Puppy(many=True):
            """
            description: Many custom component.
            responses:
              200:
                description: Components.
            """
            return [{"name": "Canna"}, {"name": "Sandy"}]

        @app_.route("/query-param/", methods=["GET"])
        async def query_param(param: str = "Foo"):
            """
            description: Query param.
            responses:
              200:
                description: Param.
            """
            return {"name": param}

        @app_.route("/path-param/{param:int}/", methods=["GET"])
        async def path_param(param: int):
            """
            description: Path param.
            responses:
              200:
                description: Param.
            """
            return {"name": param}

        @app_.route("/body-param/", methods=["POST"])
        async def body_param(param: BodyParam):
            """
            description: Body param.
            responses:
              200:
                description: Param.
            """
            return {"name": param["name"]}

        @app_.route("/default-response/", methods=["GET"])
        async def default_response():
            """
            description: Default response.
            """
            return {"name": "Canna"}

        router = Router()
        router.add_route("/custom-component/", endpoint=get, methods=["GET"])
        app_.mount("/mount", router)

        return app_
Esempio n. 6
0
 def app(self):
     return Flama(schema=None, docs=None)
Esempio n. 7
0
)


class PuppyResource(metaclass=CRUDListResource):
    database = database

    name = "puppy"
    verbose_name = "Puppy"

    model = PuppyModel
    schema = PuppySchema


app = Flama(
    title="Puppy Register",  # API title
    version="0.1",  # API version
    description="A register of puppies",  # API description
)

app.add_resource("/", PuppyResource)


@app.on_event("startup")
async def startup():
    engine = create_engine(DATABASE_URL)
    metadata.create_all(engine)  # Create the tables.
    await database.connect()


@app.on_event("shutdown")
async def shutdown():
Esempio n. 8
0
    def app(self, request):
        app_ = Flama(components=[PuppyComponent()], schema=None, docs=None)

        if request.param:

            @app_.route("/return_string/")
            class FooEndpoint(HTTPEndpoint):
                def get(self, data: http.RequestData) -> str:
                    return "example content"

            @app_.route("/return_html/")
            class FooEndpoint(HTTPEndpoint):
                def get(self, data: http.RequestData) -> HTMLResponse:
                    return HTMLResponse(
                        "<html><body>example content</body></html>")

            @app_.route("/return_data/")
            class FooEndpoint(HTTPEndpoint):
                def get(self, data: http.RequestData) -> dict:
                    return {"example": "content"}

            @app_.route("/return_response/")
            class FooEndpoint(HTTPEndpoint):
                def get(self, data: http.RequestData) -> http.Response:
                    return http.JSONResponse({"example": "content"})

            @app_.route("/return_unserializable_json/")
            class FooEndpoint(HTTPEndpoint):
                def get(self) -> dict:
                    class Dummy:
                        pass

                    return {"dummy": Dummy()}

            @app_.route("/return-schema/", methods=["GET"])
            class ReturnSchemaHTTPEndpoint(HTTPEndpoint):
                async def get(self) -> BodyParam:
                    return {"name": "Canna"}

            @app_.route("/return-schema-many/", methods=["GET"])
            class ReturnSchemaManyHTTPEndpoint(HTTPEndpoint):
                async def get(self) -> BodyParam(many=True):
                    return [{"name": "Canna"}, {"name": "Sandy"}]

            @app_.route("/return-schema-empty/", methods=["GET"])
            class ReturnSchemaEmptyHTTPEndpoint(HTTPEndpoint):
                async def get(self) -> BodyParam:
                    return None

        else:

            @app_.route("/return_string/")
            def return_string(data: http.RequestData) -> str:
                return "example content"

            @app_.route("/return_html/")
            def return_html(data: http.RequestData) -> HTMLResponse:
                return HTMLResponse(
                    "<html><body>example content</body></html>")

            @app_.route("/return_data/")
            def return_data(data: http.RequestData) -> dict:
                return {"example": "content"}

            @app_.route("/return_response/")
            def return_response(data: http.RequestData) -> http.Response:
                return http.JSONResponse({"example": "content"})

            @app_.route("/return_unserializable_json/")
            def return_unserializable_json() -> dict:
                class Dummy:
                    pass

                return {"dummy": Dummy()}

            @app_.route("/return-schema/", methods=["GET"])
            async def return_schema() -> BodyParam:
                return {"name": "Canna"}

            @app_.route("/return-schema-many/", methods=["GET"])
            async def return_schema_many() -> BodyParam(many=True):
                return [{"name": "Canna"}, {"name": "Sandy"}]

            @app_.route("/return-schema-empty/", methods=["GET"])
            async def return_schema_empty() -> BodyParam:
                return None

        return app_
Esempio n. 9
0
from flama import exceptions
from flama.applications import Flama
from flama.validation import output_validation

utc = datetime.timezone.utc


class Product(Schema):
    name = fields.String(validate=validate.Length(max=10), required=True)
    rating = fields.Integer(missing=None,
                            validate=validate.Range(min=0, max=100))
    created = fields.DateTime()


app = Flama()


@app.route("/product", methods=["GET"])
@output_validation()
def validate_product() -> Product:
    return {
        "name":
        "foo",
        "rating":
        0,
        "created":
        datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)
    }

Esempio n. 10
0
 def app(self, resource):
     app_ = Flama()
     app_.add_resource("/", resource)
     return app_
Esempio n. 11
0
    def resolve(self) -> Puppy:
        return Puppy()


class UnhandledComponent(Component):
    def resolve(self):
        pass


class UnknownParamComponent(Component):
    def resolve(self, foo: Unknown) -> Foo:
        pass


app = Flama(components=[PuppyComponent(),
                        UnknownParamComponent()],
            title="Puppies")


@app.route("/http-view/")
async def puppy_http_view(puppy: Puppy):
    return JSONResponse({"puppy": puppy.name})


@app.route("/http-endpoint/", methods=["GET"])
class PuppyHTTPEndpoint(HTTPEndpoint):
    async def get(self, puppy: Puppy):
        return JSONResponse({"puppy": puppy.name})


@app.websocket_route("/websocket-view/")
Esempio n. 12
0
    def app(self):
        app_ = Flama(schema=None, docs=None)

        @app_.route("/method/", methods=["GET", "POST"])
        def get_method(method: http.Method):
            return {"method": str(method)}

        @app_.route("/url/")
        def get_url(url: http.URL):
            return {"url": str(url), "components": url.components}

        @app_.route("/scheme/")
        def get_scheme(scheme: http.Scheme):
            return {"scheme": scheme}

        @app_.route("/host/")
        def get_host(host: http.Host):
            return {"host": host}

        @app_.route("/port/")
        def get_port(port: http.Port):
            return {"port": port}

        @app_.route("/path/")
        def get_path(path: http.Path):
            return {"path": path}

        @app_.route("/query_string/")
        def get_query_string(query_string: http.QueryString):
            return {"query_string": query_string}

        @app_.route("/query_params/")
        def get_query_params(query_string: http.QueryString,
                             query_params: http.QueryParams):
            return {"query_params": dict(query_params)}

        @app_.route("/page_query_param/")
        def get_page_query_param(page: http.QueryParam):
            return {"page": page}

        @app_.route("/headers/", methods=["GET", "POST"])
        def get_headers(headers: http.Headers):
            return {"headers": dict(headers)}

        @app_.route("/accept_header/")
        def get_accept_header(accept: http.Header):
            return {"accept": accept}

        @app_.route("/missing_header/")
        def get_missing_header(missing: http.Header):
            return {"missing": missing}

        @app_.route("/body/", methods=["GET", "POST"])
        def get_body(body: http.Body):
            return {"body": body.decode("utf-8")}

        @app_.route("/request/")
        async def get_request(request: http.Request):
            return {
                "method": str(request.method),
                "url": str(request.url),
                "headers": dict(request.headers),
                "body": (await request.body()).decode("utf-8"),
            }

        @app_.websocket_route("/websocket/")
        async def get_websocket(websocket: websockets.WebSocket):
            await websocket.accept()
            await websocket.send_json({
                "url":
                str(websocket.url),
                "headers":
                dict(websocket.headers),
                "state":
                str(websocket.client_state.name),
            })
            await websocket.close()

        return app_
Esempio n. 13
0
def create_puppy(puppy: Puppy) -> Puppy:
    """
    tags:
        - puppy
    summary:
        Create a new puppy.
    description:
        Create a new puppy using data validated from request body and add it
        to the collection.
    responses:
        200:
            description: Puppy created successfully.
    """
    ...


app = Flama(
    title="Puppy Register",  # API title
    version="0.1",  # API version
    description="A register of puppies",  # API description
    schema="/schema/",  # Path to expose OpenAPI schema
    docs="/docs/",  # Path to expose SwaggerUI application
    redoc="/redoc/",  # Path to expose ReDoc application
)

app.add_route("/puppy/", list_puppies, methods=["GET"])
app.add_route("/puppy/", create_puppy, methods=["POST"])

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
Esempio n. 14
0
    def app(self):
        app_ = Flama()

        @app_.route("/str_path_param/{param}/")
        def str_path_param(param: str):
            return {"param": param}

        @app_.route("/int_path_param/{param}/")
        def int_path_param(param: int):
            return {"param": param}

        @app_.route("/float_path_param/{param}/")
        def float_path_param(param: float):
            return {"param": param}

        @app_.route("/bool_path_param/{param}/")
        def bool_path_param(param: bool):
            return {"param": param}

        @app_.route("/str_query_param/")
        def str_query_param(param: str):
            return {"param": param}

        @app_.route("/int_query_param/")
        def int_query_param(param: int):
            return {"param": param}

        @app_.route("/float_query_param/")
        def float_query_param(param: float):
            return {"param": param}

        @app_.route("/bool_query_param/")
        def bool_query_param(param: bool):
            return {"param": param}

        @app_.route("/str_query_param_with_default/")
        def str_query_param_with_default(param: str = ""):
            return {"param": param}

        @app_.route("/int_query_param_with_default/")
        def int_query_param_with_default(param: int = None):
            return {"param": param}

        @app_.route("/float_query_param_with_default/")
        def float_query_param_with_default(param: float = None):
            return {"param": param}

        @app_.route("/bool_query_param_with_default/")
        def bool_query_param_with_default(param: bool = False):
            return {"param": param}

        @app_.route("/str_query_param_optional/")
        def str_query_param_optional(param: typing.Optional[str] = None):
            return {"param": param}

        @app_.route("/int_query_param_optional/")
        def int_query_param_optional(param: typing.Optional[int] = None):
            return {"param": param}

        @app_.route("/float_query_param_optional/")
        def float_query_param_optional(param: typing.Optional[float] = None):
            return {"param": param}

        @app_.route("/bool_query_param_optional/")
        def bool_query_param_optional(param: typing.Optional[bool] = None):
            return {"param": param}

        @app_.route("/empty/", methods=["POST"])
        def empty(foo):
            return {}

        return app_
Esempio n. 15
0
def app():
    return Flama(components=[PuppyComponent()], schema=None, docs=None)
Esempio n. 16
0
class Unknown(Puppy):
    pass


class PuppyComponent(Component):
    def resolve(self) -> Puppy:
        return Puppy()


class UnhandledComponent(Component):
    def resolve(self):
        pass


app = Flama(components=[PuppyComponent()])


@app.route("/http-view")
async def puppy_http_view(puppy: Puppy):
    return JSONResponse({"puppy": puppy.name})


@app.route("/http-endpoint", methods=["GET"])
class PuppyHTTPEndpoint(HTTPEndpoint):
    async def get(self, puppy: Puppy):
        return JSONResponse({"puppy": puppy.name})


@app.websocket_route("/websocket-view")
async def puppy_websocket_view(session: WebSocket, puppy: Puppy):