Code Monkey home page Code Monkey logo

Comments (4)

M3te0r avatar M3te0r commented on May 28, 2024 1

@vitalik Could reproduce with this minimal setup (taken out and reduced from actual project)

from typing import Annotated, Literal

from ninja import Schema
from pydantic import ConfigDict
from ninja import Field

from pydantic import RootModel

class ExtraForbidSchema(Schema):
    model_config = ConfigDict(extra="forbid")

class AbstractProfileIn(ExtraForbidSchema):
    first_name: str | None = None
    last_name: str | None = None

class NewUserBOIn(ExtraForbidSchema): # <==== If Schema it's good
    email: str
    role: str
    project_id: int | None = None

class AdminProfileIn(AbstractProfileIn):
    first_name: str
    last_name: str

class AdminBOIn(NewUserBOIn):
    site_ids: list[int] | None = Field(None, json_schema_extra={"deprecated": True})
    role: Literal["ADMIN"]
    profile: AdminProfileIn

class HCProfileIn(AbstractProfileIn):
    first_name: str
    last_name: str

class HCPBOIn(NewUserBOIn):
    role: Literal["HCP"]
    project_id: int
    profile: HCProfileIn

class NewUserBOUnionIn(Schema, RootModel):
    """
    Class to discriminate between different user roles with payload
    The solution : https://github.com/pydantic/pydantic/issues/3714#issuecomment-1051093100
    """

    root: Annotated[
        (HCPBOIn | AdminBOIn),
        Field(discriminator="role"),
    ]

    def __getattr__(self, attr):
        return getattr(self.root, attr)

    def __getitem__(self, item):
        return self.root[item]


user_data = {
    "email": "[email protected]",
    "project_id": "2",
    "role": "HCP",
    "profile": {"first_name": "FOO", "last_name": "BAR"}
}


user = NewUserBOUnionIn(**user_data)
print(user.email)


Full traceback :

Traceback (most recent call last):
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 66, in __getattr__
    value = getattr(self._obj, key)
            ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 62, in __getattr__
    raise AttributeError(key)
AttributeError: __dict__. Did you mean: '__dir__'?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/template/base.py", line 821, in __init__
    self.literal = int(var)
                   ^^^^^^^^
ValueError: invalid literal for int() with base 10: '__dict__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/template/base.py", line 832, in __init__
    self.literal = mark_safe(unescape_string_literal(var))
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/utils/functional.py", line 246, in wrapper
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/utils/text.py", line 482, in unescape_string_literal
    raise ValueError("Not a string literal: %r" % s)
ValueError: Not a string literal: '__dict__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 70, in __getattr__
    value = Variable(key).resolve(self._obj)
            ^^^^^^^^^^^^^
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/django/template/base.py", line 837, in __init__
    raise TemplateSyntaxError(
django.template.exceptions.TemplateSyntaxError: Variables and attributes may not begin with underscores: '__dict__'
thread '<unnamed>' panicked at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pyo3-0.21.1/src/err/mod.rs:1098:5:
Python API call failed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
--- PyO3 is resuming a panic after fetching a PanicException from Python. ---
Python stack trace below:
Traceback (most recent call last):
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 215, in _run_root_validator
    return handler(values)
           ^^^^^^^^^^^^^^^
pyo3_runtime.PanicException: Python API call failed
--- PyO3 is resuming a panic after fetching a PanicException from Python. ---
Python stack trace below:
Traceback (most recent call last):
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/ninja/schema.py", line 215, in _run_root_validator
    return handler(values)
           ^^^^^^^^^^^^^^^
pyo3_runtime.PanicException: Python API call failed
Traceback (most recent call last):
  File "/home/m3te0r/PycharmProjects/bepatient-server/ff.py", line 70, in <module>
    user = NewUserBOUnionIn(**user_data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/m3te0r/PycharmProjects/bepatient-server/.venv/lib/python3.12/site-packages/pydantic/root_model.py", line 71, in __init__
    self.__pydantic_validator__.validate_python(root, self_instance=self)
pyo3_runtime.PanicException: Python API call failed

I use combination of discriminated annotated unions schema + RootModel + Nested schemas with ConfigDict(extra="forbid")
If I remove the extra forbid from NewUserBOIn schema it works

from django-ninja.

vitalik avatar vitalik commented on May 28, 2024 1

Hi @M3te0r

Please check if latest pydantic (2.7.1) works for you

from django-ninja.

vitalik avatar vitalik commented on May 28, 2024

Hi @M3te0r

Maybe you have specific data that you pass to validation that is failing ? Please share you Schema class and data that you are passing

the latest full test run uses pydantic2.7 did not fail at any combination - https://github.com/vitalik/django-ninja/actions/runs/8661076227

from django-ninja.

M3te0r avatar M3te0r commented on May 28, 2024

Hi @vitalik
Minimal test code and actual project seems to work with pydantic v2.7.1 now
Many thanks !

from django-ninja.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.