-
-
Notifications
You must be signed in to change notification settings - Fork 6.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow multiple levels of custom root models #4428
Open
andyhasit
wants to merge
6
commits into
tiangolo:master
Choose a base branch
from
andyhasit:allow-multiple-levels-of-custom-root-models
base: master
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
6c10d7d
Add .pyton-version to gitignore for those who use pyenv
andyhasit e2e81fa
Enables nested models with custom roots
andyhasit fc2de5b
Merge branch 'master' into allow-multiple-levels-of-custom-root-models
andyhasit 5dbd3fa
Merge branch 'master' into allow-multiple-levels-of-custom-root-models
tiangolo f9681ba
Merge branch 'master' into allow-multiple-levels-of-custom-root-models
tiangolo 1f8c7f2
Merge branch 'master' into allow-multiple-levels-of-custom-root-models
tiangolo File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
.idea | ||
.ipynb_checkpoints | ||
.mypy_cache | ||
.python-version | ||
.vscode | ||
__pycache__ | ||
.pytest_cache | ||
|
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from typing import Dict | ||
|
||
from fastapi import FastAPI | ||
from fastapi.testclient import TestClient | ||
from pydantic import BaseModel | ||
|
||
app = FastAPI() | ||
|
||
|
||
class Level2(BaseModel): | ||
__root__: str | ||
|
||
|
||
class Level1(BaseModel): | ||
__root__: Dict[str, Level2] | ||
|
||
|
||
class Level0(BaseModel): | ||
__root__: Dict[str, Level1] | ||
|
||
|
||
@app.get("/items/valid", response_model=Level0) | ||
def get_valid(): | ||
cat = Level2(__root__="cat") | ||
mammal = Level1(__root__={"mammal": cat}) | ||
animal = Level0(__root__={"animal": mammal}) | ||
return animal | ||
|
||
|
||
client = TestClient(app) | ||
|
||
|
||
def test_valid(): | ||
response = client.get("/items/valid") | ||
response.raise_for_status() | ||
assert response.json() == {"animal": {"mammal": "cat"}} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the reason behind using try-except block here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
response_content is not necessarily a dictionary. If you remove the try catch some tests fail.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Then why don't you check the variable data type instead?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For two reasons:
I didn't follow the code far enough to see what all could get passed, but we're dealing with Pydantic models upstream and it's perfectly possible to implement this dict functionality in a model (see my comment on #911).
Though to be consistent I note I'm breaking EAFP inside the try catch, so I could be doing:
But I think the intention is slightly less clear.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually, there's already an
if isinstance(res, BaseModel)
check in_prepare_response_content
that might be a better place for this code, because presumably it should apply if (and only if) it's dealing with a PydanticBaseModel
instance.Somewhat relatedly, it looks like Pydantic itself does something similar in the
BaseModel.json()
method, where it notices that the model has a custom__root__
and then extracts the nested value:.. where
ROOT_KEY == "__root__"
, andself.__custom_root_type__
is a property of allpydantic.BaseModel
s (possibly None, but defined either way).So putting all of this together - combining the logic from
BaseModel.json
with the approach in this PR, applied to @cikay's feedback:... or something like that (I haven't been able to try running this yet).
The fact that
pydantic.BaseModel
does basically the same exact thing might be a sign that it's a valid, non-crazy approach here to have well-defined behavior around types with custom__root__
.