Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor of examples folder #99

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
130 changes: 130 additions & 0 deletions examples/api/02-data_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import http
from pydantic import BaseModel, validator

import flama
from flama.http import APIResponse
from flama.types import Schema


class Puppy(BaseModel):
id: int
name: str
age: int

@validator("age")
def minimum_age_validation(cls, v):
"""Validates that the age is not negative."""
if v < 0:
raise ValueError("Age must be positive")

return v


PUPPIES = [
{"id": 1, "name": "Bobby", "age": 3},
{"id": 2, "name": "Rex", "age": 5},
{"id": 3, "name": "Toby", "age": 2},
]


app = flama.Flama(
title="My 🔥 API",
version="1.0",
description="My API with schema validation",
docs="/docs/",
schema="/schema/",
)


@app.route("/puppy/", methods=["GET"])
def list_puppies(name: str = None):
"""
tags:
- puppy
summary:
List puppies.
description:
List the collection of puppies. There is an optional query parameter that
specifies a name for filtering the collection based on it.
responses:
200:
description: List puppies.
"""
if name is None:
return PUPPIES

puppies = [puppy for puppy in PUPPIES if puppy["name"] == name]

if not puppies:
return APIResponse(status_code=http.HTTPStatus.NOT_FOUND) # type: ignore

return puppies


@app.route("/puppy/", methods=["POST"])
def create_puppy(puppy: Schema[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.
"""
if puppy["id"] in [p["id"] for p in PUPPIES]:
return APIResponse(status_code=http.HTTPStatus.CONFLICT) # type: ignore

PUPPIES.append(puppy)
return puppy


@app.route("/puppy/{id:int}/", methods=["GET"])
def get_puppy(id: int) -> Puppy:
"""
tags:
- puppy
summary:
Get a puppy.
description:
Get a puppy from the collection.
responses:
200:
description: Puppy retrieved successfully.
"""
puppies = [puppy for puppy in PUPPIES if puppy["id"] == id]
if not puppies:
return APIResponse(status_code=http.HTTPStatus.NOT_FOUND) # type: ignore

return puppies[0]


@app.route("/puppy/{id:int}/", methods=["DELETE"])
def delete_puppy(id: int):
"""
tags:
- puppy
summary:
Delete a puppy.
description:
Delete a puppy from the collection.
responses:
200:
description: Puppy deleted successfully.
"""
puppies = [puppy for puppy in PUPPIES if puppy["id"] == id]
if not puppies:
return APIResponse(status_code=http.HTTPStatus.NOT_FOUND)

for puppy in puppies:
PUPPIES.remove(puppy)
return APIResponse(status_code=http.HTTPStatus.OK)


app.schema.register_schema("Puppy", Puppy)

if __name__ == "__main__":
flama.run(flama_app=app, server_host="0.0.0.0", server_port=8000)
88 changes: 88 additions & 0 deletions examples/api/03-pagination.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import string
import typing

from pydantic import BaseModel, validator

import flama


class Puppy(BaseModel):
id: int
name: str
age: int

@validator("age")
def minimum_age_validation(cls, v):
"""Validates that the age is not negative."""
if v < 0:
raise ValueError("Age must be positive")

return v


PUPPIES = [
{"id": 1, "name": "Canna", "age": 7},
{"id": 2, "name": "Sandy", "age": 12},
{"id": 3, "name": "Bobby", "age": 3},
{"id": 4, "name": "Rex", "age": 5},
{"id": 5, "name": "Toby", "age": 2},
]


app = flama.Flama(
title="My 🔥 API",
version="1.0",
description="My API with pagination",
docs="/docs/",
schema="/schema/",
)


@app.route("/puppy/", methods=["GET"])
@app.paginator.page_number(schema_name="Puppy")
def puppies(name: str = None, **kwargs) -> typing.List[Puppy]:
"""
tags:
- puppy
summary:
List puppies.
description:
List the puppies collection. There is an optional query parameter that
specifies a name for filtering the collection based on it.
responses:
200:
description: List puppies.
"""
result = PUPPIES
if name:
result = filter(lambda x: x["name"] == name, result)

return result


@app.route("/puppy-offset/", methods=["GET"])
@app.paginator.limit_offset(schema_name="Puppy")
def puppies_offset(name: str, **kwargs) -> typing.List[Puppy]:
"""
tags:
- puppy
summary:
List puppies with offset pagination.
description:
List the puppies collection using offset pagination, so that
the client can specify the number of items to skip and the
number of items to return.

responses:
200:
description: List puppies.
"""
result = PUPPIES
if name:
return filter(lambda x: x["name"] == name, result)

return result


if __name__ == "__main__":
flama.run(flama_app=app, server_host="0.0.0.0", server_port=8000)
73 changes: 0 additions & 73 deletions examples/data_schema.py

This file was deleted.

90 changes: 0 additions & 90 deletions examples/pagination.py

This file was deleted.