How to use the typesystem.Schema function in typesystem

To help you get started, we’ve selected a few typesystem examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github encode / typesystem / tests / test_json_schema.py View on Github external
def test_schema_to_json_schema():
    class BookingSchema(typesystem.Schema):
        start_date = typesystem.Date(title="Start date")
        end_date = typesystem.Date(title="End date")
        room = typesystem.Choice(
            title="Room type",
            choices=[
                ("double", "Double room"),
                ("twin", "Twin room"),
                ("single", "Single room"),
            ],
        )
        include_breakfast = typesystem.Boolean(title="Include breakfast", default=False)

    schema = to_json_schema(BookingSchema)

    assert schema == {
        "type": "object",
github rsinger86 / drf-typed-views / test_project / testapp / views.py View on Github external
"""


class BagOptions(str, Enum):
    paper = "paper"
    plastic = "plastic"


class SuperUser(BaseModel):
    id: int
    name = "John Doe"
    signup_ts: datetime = None
    friends: List[int] = []


class Booking(typesystem.Schema):
    start_date = typesystem.Date()
    end_date = typesystem.Date()
    room = typesystem.Choice(
        choices=[
            ("double", "Double room"),
            ("twin", "Twin room"),
            ("single", "Single room"),
        ]
    )
    include_breakfast = typesystem.Boolean(title="Include breakfast", default=False)


@typed_api_view(["POST"])
def create_user(user: SuperUser):
    return Response(dict(user))
github encode / typesystem / tests / tokenize / test_validate_yaml.py View on Github external
with pytest.raises(ValidationError) as exc_info:
        validate_yaml(text, validator=validator)

    exc = exc_info.value
    assert exc.messages() == [
        Message(
            text="Must be a number.",
            code="type",
            index=["b"],
            start_position=Position(line_no=2, column_no=4, char_index=10),
            end_position=Position(line_no=2, column_no=6, char_index=12),
        )
    ]

    class Validator(Schema):
        a = Integer()
        b = Integer()

    text = "a: 123\nb: abc\n"

    with pytest.raises(ValidationError) as exc_info:
        validate_yaml(text, validator=Validator)

    exc = exc_info.value
    assert exc.messages() == [
        Message(
            text="Must be a number.",
            code="type",
            index=["b"],
            start_position=Position(line_no=2, column_no=4, char_index=10),
            end_position=Position(line_no=2, column_no=6, char_index=12),
github encode / typesystem / tests / test_schemas.py View on Github external
def test_nested_schema_to_json_schema():
    class Artist(typesystem.Schema):
        name = typesystem.String(max_length=100)

    class Album(typesystem.Schema):
        title = typesystem.String(max_length=100)
        release_date = typesystem.Date()
        artist = typesystem.Reference(Artist)

    schema = typesystem.to_json_schema(Album)

    assert schema == {
        "type": "object",
        "properties": {
            "title": {"type": "string", "minLength": 1, "maxLength": 100},
            "release_date": {"type": "string", "minLength": 1, "format": "date"},
            "artist": {"$ref": "#/definitions/Artist"},
        },
        "required": ["title", "release_date", "artist"],
        "definitions": {
            "Artist": {
github encode / typesystem / tests / test_definitions.py View on Github external
)
    assert value == ExampleC(field_on_c=123, example_d=[ExampleD(field_on_d=456)])

    class ExampleE(typesystem.Schema, definitions=definitions):
        field_on_e = typesystem.Integer()
        example_f = typesystem.Array(items=[typesystem.Reference("ExampleF")])

    class ExampleF(typesystem.Schema, definitions=definitions):
        field_on_f = typesystem.Integer()

    value = ExampleE.validate(
        {"field_on_e": "123", "example_f": [{"field_on_f": "456"}]}
    )
    assert value == ExampleE(field_on_e=123, example_f=[ExampleF(field_on_f=456)])

    class ExampleG(typesystem.Schema, definitions=definitions):
        field_on_g = typesystem.Integer()
        example_h = typesystem.Object(
            properties={"h": typesystem.Reference("ExampleH")}
        )

    class ExampleH(typesystem.Schema, definitions=definitions):
        field_on_h = typesystem.Integer()

    value = ExampleG.validate(
        {"field_on_g": "123", "example_h": {"h": {"field_on_h": "456"}}}
    )
    assert value == ExampleG(field_on_g=123, example_h={"h": ExampleH(field_on_h=456)})
github encode / typesystem / tests / test_schemas.py View on Github external
def test_schema_time_serialization():
    class MealSchedule(typesystem.Schema):
        guest_id = typesystem.Integer()
        breakfast_at = typesystem.Time()
        dinner_at = typesystem.Time(allow_null=True)

    guest_id = 123
    breakfast_at = datetime.time(hour=10, minute=30)
    schedule = MealSchedule(guest_id=guest_id, breakfast_at=breakfast_at)

    assert typesystem.formats.TIME_REGEX.match(schedule["breakfast_at"])
    assert schedule["guest_id"] == guest_id
    assert schedule["breakfast_at"] == breakfast_at.isoformat()
    assert schedule["dinner_at"] is None
github encode / typesystem / tests / test_definitions.py View on Github external
def test_string_references():
    definitions = typesystem.SchemaDefinitions()

    class ExampleA(typesystem.Schema, definitions=definitions):
        field_on_a = typesystem.Integer()
        example_b = typesystem.Reference("ExampleB")

    class ExampleB(typesystem.Schema, definitions=definitions):
        field_on_b = typesystem.Integer()

    value = ExampleA.validate({"field_on_a": "123", "example_b": {"field_on_b": "456"}})
    assert value == ExampleA(field_on_a=123, example_b=ExampleB(field_on_b=456))

    class ExampleC(typesystem.Schema, definitions=definitions):
        field_on_c = typesystem.Integer()
        example_d = typesystem.Array(items=typesystem.Reference("ExampleD"))

    class ExampleD(typesystem.Schema, definitions=definitions):
        field_on_d = typesystem.Integer()

    value = ExampleC.validate(
        {"field_on_c": "123", "example_d": [{"field_on_d": "456"}]}
    )
    assert value == ExampleC(field_on_c=123, example_d=[ExampleD(field_on_d=456)])
github erm / guitarlette / backend / project / schema.py View on Github external
import typesystem


class SongSchema(typesystem.Schema):
    title = typesystem.String(max_length=255)
    content = typesystem.Text()

    def __str__(self) -> str:
        return self.title
github rsinger86 / drf-typed-views / rest_typed_views / utils.py View on Github external
def parse_complex_type(annotation) -> Tuple[bool, Optional[str]]:
    if hasattr(settings, "DRF_TYPED_VIEWS"):
        enabled = settings.DRF_TYPED_VIEWS.get("schema_packages", [])
    else:
        enabled = []

    if "pydantic" in enabled:
        from pydantic import BaseModel as PydanticBaseModel

        if inspect.isclass(annotation) and issubclass(annotation, PydanticBaseModel):
            return True, "pydantic"

    if "typesystem" in enabled:
        from typesystem import Schema as TypeSystemSchema

        if inspect.isclass(annotation) and issubclass(annotation, TypeSystemSchema):
            return True, "typesystem"

    if "marshmallow" in enabled:
        from marshmallow import Schema as MarshmallowSchema

        if inspect.isclass(annotation) and issubclass(annotation, MarshmallowSchema):
            return True, "marshmallow"
    return False, None
github encode / hostedapi / source / datasource.py View on Github external
self.search_term = None
        self.sort_func = None
        self.sort_reverse = False

        if columns is not None:
            fields = {}
            for column in columns:
                if column["datatype"] == "string":
                    fields[column["identity"]] = typesystem.String(
                        title=column["name"], max_length=100
                    )
                elif column["datatype"] == "integer":
                    fields[column["identity"]] = typesystem.Integer(
                        title=column["name"]
                    )
            self.schema = type("Schema", (typesystem.Schema,), fields)