Skip to content

Instantly share code, notes, and snippets.

@pelzhaus
Last active March 25, 2021 13:47
Show Gist options
  • Save pelzhaus/553225900aba8348a4e5fdb8c9067601 to your computer and use it in GitHub Desktop.
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.
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