Skip to content
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

Fixing Pydantic Extension #1021

Merged
merged 2 commits into from
Jul 9, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fixing pydantic extension
  • Loading branch information
sydney-runkle authored Jul 6, 2023
commit f31c7a6f5198f591416f72fd70cdefe0289f6a23
21 changes: 7 additions & 14 deletions docs/blueprints/pydantic.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,29 @@
from drf_spectacular.extensions import OpenApiSerializerExtension
from drf_spectacular.plumbing import ResolvedComponent

from pydantic import model_schema
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved


class PydanticExtension(OpenApiSerializerExtension):
target_class = 'pydantic.BaseModel'
target_class = "pydantic.BaseModel"
match_subclasses = True

def get_name(self, auto_schema, direction):
return self.target.__name__

def map_serializer(self, auto_schema, direction):
def translate_refs(obj, key=None):
if isinstance(obj, dict):
return {k: translate_refs(v, k) for k, v in obj.items()}
elif isinstance(obj, list):
return [translate_refs(i) for i in obj]
elif key == '$ref':
return obj.replace('#/definitions/', '#/components/schemas/')
else:
return obj

# let pydantic generate a JSON schema
schema = self.target.schema()
schema = model_schema(self.target, ref_prefix="#/components/schemas/")

# pull out potential sub-schemas and put them into component section
for sub_name, sub_schema in schema.pop('definitions', {}).items():
for sub_name, sub_schema in schema.pop("definitions", {}).items():
component = ResolvedComponent(
name=sub_name,
type=ResolvedComponent.SCHEMA,
object=sub_name,
schema=translate_refs(sub_schema),
schema=sub_schema,
)
auto_schema.registry.register_on_missing(component)

return translate_refs(schema)
return schema