0

I'm trying to validate custom root types with pydantic as followed. My idea is to get a root validator for discriminated union of custom classes or literals.

Any idea how to get it working ?

# authorization.py

from typing import Union, Literal, Type
from pydantic import BaseModel
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base

Base: DeclarativeMeta = declarative_base()


class R1(Base):
  # ...


class R2(Base):
  # ...


class R(BaseModel):
  __root__: Union[Type[R1], Type[R2]]

  class Config:
    arbitrary_types_allowed = True


class A(BaseModel):
  __root__: Literal["read", "edit"]


async def get_authorized_resources(resource: R):
  # `resource` should be an instance of R1 or R2
  pass

async def is_allowed(resource: R, action: A):
  # `resource` should be an instance of R1 or R2
  # `action` should be either "read" or "right"
  pass

Usage of these functions should be :

# another_file.py
from authorization import R1, R2, is_allowed


# ignore the fact that it's not running in asyncio loop
await is_allowed(resource=R1, action="read")
mlisthenewcool
  • 539
  • 3
  • 14

0 Answers0