Skip to main content

Pydantic view helper decorator

License: MIT

Installation

pip install pydantic_view

Usage

In [1]: from pydantic import BaseModel, Field
   ...: from pydantic_view import view
   ...: 
   ...: 
   ...: class User(BaseModel):
   ...:     id: int
   ...:     username: str
   ...:     password: str
   ...:     address: str
   ...: 
   ...: @view("Create", exclude={"id"})
   ...: class UserCreate(User):
   ...:     pass
   ...:
   ...: @view("Update")
   ...: class UserUpdate(User):
   ...:     pass
   ...:
   ...: @view("Patch")
   ...: class UserPatch(User):
   ...:     username: str = None
   ...:     password: str = None
   ...:     address: str = None
   ...:
   ...: @view("Out", exclude={"password"})
   ...: class UserOut(User):
   ...:     pass

In [2]: user = User(id=0, username="human", password="iamaman", address="Earth")
   ...: user.Out()
   ...: 
Out[2]: UserOut(id=0, username='human', address='Earth')

In [3]: User.Update(id=0, username="human", password="iamasuperman", address="Earth")
   ...: 
Out[3]: UserUpdate(id=0, username='human', password='iamasuperman', address='Earth')

In [4]: User.Patch(id=0, address="Mars")
   ...: 
Out[4]: UserPatch(id=0, username=None, password=None, address='Mars')

FastAPI example

from typing import Optional

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field

from pydantic_view import view, view_field_validator


class UserSettings(BaseModel):
    model_config = ConfigDict(extra="forbid")

    public: Optional[str] = None
    secret: Optional[str] = None


@view("Out", exclude={"secret"})
class UserSettingsOut(UserSettings):
    pass


@view("Create")
class UserSettingsCreate(UserSettings):
    pass


@view("Update")
class UserSettingsUpdate(UserSettings):
    pass


@view("Patch")
class UserSettingsPatch(UserSettings):
    public: str = None
    secret: str = None


class User(BaseModel):
    model_config = ConfigDict(extra="forbid")

    id: int
    username: str
    password: str = Field(default_factory=lambda: "password")
    settings: UserSettings

    @view_field_validator({"Create", "Update", "Patch"}, "username")
    @classmethod
    def validate_username(cls, v):
        if len(v) < 3:
            raise ValueError
        return v


@view("Out", exclude={"password"})
class UserOut(User):
    pass


@view("Create", exclude={"id"})
class UserCreate(User):
    settings: UserSettings = Field(default_factory=UserSettings)


@view("Update", exclude={"id"})
class UserUpdate(User):
    pass


@view("Patch", exclude={"id"})
class UserPatch(User):
    username: str = None
    password: str = None
    settings: UserSettings = None


app = FastAPI()

db = {}


@app.get("/users/{user_id}", response_model=User.Out)
async def get(user_id: int) -> User.Out:
    return db[user_id]


@app.post("/users", response_model=User.Out)
async def post(user: User.Create) -> User.Out:
    user_id = 0  # generate_user_id()
    db[0] = User(id=user_id, **user.model_dump())
    return db[0]


@app.put("/users/{user_id}", response_model=User.Out)
async def put(user_id: int, user: User.Update) -> User.Out:
    db[user_id] = User(id=user_id, **user.model_dump())
    return db[user_id]


@app.patch("/users/{user_id}", response_model=User.Out)
async def patch(user_id: int, user: User.Patch) -> User.Out:
    db[user_id] = User(**{**db[user_id].model_dump(), **user.model_dump(exclude_unset=True)})
    return db[user_id]


def test_fastapi():
    client = TestClient(app)

    # POST
    response = client.post(
        "/users",
        json={
            "username": "admin",
            "password": "admin",
        },
    )
    assert response.status_code == 200, response.text
    assert response.json() == {
        "id": 0,
        "username": "admin",
        "settings": {"public": None},
    }

    # GET
    response = client.get("/users/0")
    assert response.status_code == 200, response.text
    assert response.json() == {
        "id": 0,
        "username": "admin",
        "settings": {"public": None},
    }

    # PUT
    response = client.put(
        "/users/0",
        json={
            "username": "superadmin",
            "password": "superadmin",
            "settings": {"public": "foo", "secret": "secret"},
        },
    )
    assert response.status_code == 200, response.text
    assert response.json() == {
        "id": 0,
        "username": "superadmin",
        "settings": {"public": "foo"},
    }

    # PATCH
    response = client.patch(
        "/users/0",
        json={
            "username": "guest",
            "settings": {"public": "bar"},
        },
    )
    assert response.status_code == 200, response.text
    assert response.json() == {
        "id": 0,
        "username": "guest",
        "settings": {"public": "bar"},
    }

Release files for pydantic-view 2.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydantic-view 2.0.1
File Size Uploaded
pydantic_view-2.0.1.tar.gz 5.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-view 2.0.1
File Interpreter ABI Platform
pydantic_view-2.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 11.4 kB

Release files / pydantic_view-2.0.1.tar.gz

Download URL pydantic_view-2.0.1.tar.gz
Size 5.4 kB
Tags Source
SHA-256 checksum
How to use checksums
e3b3cd3a079b5a977f2168b157aa599ba205a458dace128a15c45d02fc9778b3
BLAKE2b-256 checksum
How to use checksums
15ea21092800171d05350416222981038dbfcbbb4240c01385b4e2a08b3d8975
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.11.9 Darwin/23.5.0

Release files / pydantic_view-2.0.1-py3-none-any.whl

Download URL pydantic_view-2.0.1-py3-none-any.whl
Size 6.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2c5d1e5caa6ff87c0d060cb370b0c23c27d43e829596ebe69245ce7189fb77dc
BLAKE2b-256 checksum
How to use checksums
a5c920656e45feab1c718e6c517b0eaae16e83637669e892497855bc6d0b328e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.11.9 Darwin/23.5.0
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page