-
-
Save pelzhaus/553225900aba8348a4e5fdb8c9067601 to your computer and use it in GitHub Desktop.
Taking advantage of abstraction and Pydantic's rich schema modification features, simple inheritance is enough to add hidden field functionality to all our schemas.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABC | |
from typing import List, Dict, Type, Any | |
from pydantic import BaseModel, Field | |
from pinwheel import settings | |
class PinwheelPublicBaseModel(BaseModel, ABC): | |
_hide_fields_from_public_docs: List[str] | |
class Config: | |
@staticmethod | |
def schema_extra( | |
schema: Dict[str, Any], model: Type["PinwheelPublicBaseModel"] | |
) -> None: | |
""" | |
Custom JSON schema modifications for Pydantic models. | |
https://pydantic-docs.helpmanual.io/usage/schema/ | |
""" | |
if settings.ENV == "production": | |
properties = schema.get("properties", {}) | |
for field in model._hide_fields_from_public_docs: | |
properties.pop(field, None) | |
class PublicModel(PinwheelPublicBaseModel): | |
foo: str | |
bar: int | |
secret_beta_feature: str | |
_hide_fields_from_public_docs = ["secret_beta_feature"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment