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

Add SCHEMA_GENERATION_CLASS to settings, Allow NinjaGenerateJsonSchema to be overridden #1047

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/docs/guides/custom-schema-generator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Custom Schema Generator

**Django Ninja** allows you to custom schema generator by change `NINJA_SCHEMA_GENERATOR_CLASS` in your settings.py

Example Full Qualified Schema Name:

```python
from ninja.schema import NinjaGenerateJsonSchema
from pydantic.json_schema import CoreModeRef, DefsRef


class CustomNinjaGenerateJsonSchema(NinjaGenerateJsonSchema):

def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
module_qualname_occurrence_mode = super().get_defs_ref(core_mode_ref)
name_choices = self._prioritized_defsref_choices[module_qualname_occurrence_mode]
name_choices.pop(0)
name_choices.pop(0)
self._prioritized_defsref_choices[module_qualname_occurrence_mode] = name_choices
return module_qualname_occurrence_mode
```

In your `settings.py`:

```python
NINJA_SCHEMA_GENERATOR_CLASS = 'path.to.CustomNinjaGenerateJsonSchema'
```
1 change: 1 addition & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ nav:
- guides/urls.md
- guides/async-support.md
- guides/versioning.md
- guides/custom-schema-generator.md
- Reference:
- NinjaAPI class: reference/api.md
- reference/csrf.md
Expand Down
13 changes: 13 additions & 0 deletions ninja/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from django.conf import settings as django_settings
from pydantic import BaseModel, Field
from pydantic.json_schema import JsonSchemaMode


class Settings(BaseModel):
Expand All @@ -17,6 +18,11 @@ class Settings(BaseModel):
The default page size. Defaults to `100`.
NINJA_PAGINATION_MAX_LIMIT (int):
The maximum number of results per page. Defaults to `inf`.
NINJA_SCHEMA_GENERATOR_CLASS (str):
The schema generation class to use. Defaults to
`ninja.schema.NinjaGenerateJsonSchema`.
NINJA_SCHEMA_MODE (str):
The schema mode to use. Defaults to `serialization`.
"""

PAGINATION_CLASS: str = Field(
Expand All @@ -25,6 +31,13 @@ class Settings(BaseModel):
PAGINATION_PER_PAGE: int = Field(100, alias="NINJA_PAGINATION_PER_PAGE")
PAGINATION_MAX_LIMIT: int = Field(inf, alias="NINJA_PAGINATION_MAX_LIMIT")

SCHEMA_GENERATOR_CLASS: str = Field(
"ninja.schema.NinjaGenerateJsonSchema", alias="NINJA_SCHEMA_GENERATOR_CLASS"
)
SCHEMA_MODE: JsonSchemaMode = Field(
"serialization", alias="NINJA_SCHEMA_MODE"
)

class Config:
from_attributes = True

Expand Down
10 changes: 7 additions & 3 deletions ninja/openapi/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
from http.client import responses
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Set, Tuple

from django.utils.module_loading import import_string

from ninja.conf import settings
from ninja.constants import NOT_SET
from ninja.operation import Operation
from ninja.params.models import TModel, TModels
from ninja.schema import NinjaGenerateJsonSchema
from ninja.types import DictStrAny
from ninja.utils import normalize_path

Expand Down Expand Up @@ -149,7 +151,8 @@ def _extract_parameters(self, model: TModel) -> List[DictStrAny]:

schema = model.model_json_schema(
ref_template=REF_TEMPLATE,
schema_generator=NinjaGenerateJsonSchema,
schema_generator=import_string(settings.SCHEMA_GENERATOR_CLASS),
mode=settings.SCHEMA_MODE
)

required = set(schema.get("required", []))
Expand Down Expand Up @@ -214,7 +217,8 @@ def _create_schema_from_model(
schema = model.model_json_schema(
ref_template=REF_TEMPLATE,
by_alias=by_alias,
schema_generator=NinjaGenerateJsonSchema,
schema_generator=import_string(settings.SCHEMA_GENERATOR_CLASS),
mode=settings.SCHEMA_MODE
).copy()

# move Schemas from definitions
Expand Down
15 changes: 13 additions & 2 deletions ninja/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,27 @@ def resolve_name(obj):
from django.db.models import Manager, QuerySet
from django.db.models.fields.files import FieldFile
from django.template import Variable, VariableDoesNotExist
from django.utils.module_loading import import_string
from pydantic import BaseModel, Field, ValidationInfo, model_validator, validator
from pydantic._internal._model_construction import ModelMetaclass
from pydantic.functional_validators import ModelWrapValidatorHandler
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue

from ninja.conf import settings
from ninja.signature.utils import get_args_names, has_kwargs
from ninja.types import DictStrAny

pydantic_version = list(map(int, pydantic.VERSION.split(".")[:2]))
assert pydantic_version >= [2, 0], "Pydantic 2.0+ required"

__all__ = ["BaseModel", "Field", "validator", "DjangoGetter", "Schema"]
__all__ = [
"BaseModel",
"Field",
"validator",
"DjangoGetter",
"Schema",
"NinjaGenerateJsonSchema",
]

S = TypeVar("S", bound="Schema")

Expand Down Expand Up @@ -223,7 +232,9 @@ def dict(self, *a: Any, **kw: Any) -> DictStrAny:

@classmethod
def json_schema(cls) -> DictStrAny:
return cls.model_json_schema(schema_generator=NinjaGenerateJsonSchema)
return cls.model_json_schema(
schema_generator=import_string(settings.SCHEMA_GENERATOR_CLASS)
)

@classmethod
def schema(cls) -> DictStrAny: # type: ignore
Expand Down
1 change: 1 addition & 0 deletions tests/test_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
def test_default_configuration():
assert settings.PAGINATION_CLASS == "ninja.pagination.LimitOffsetPagination"
assert settings.PAGINATION_PER_PAGE == 100
assert settings.SCHEMA_GENERATOR_CLASS == "ninja.schema.NinjaGenerateJsonSchema"
98 changes: 98 additions & 0 deletions tests/test_custom_schema_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import pytest
from pydantic.json_schema import CoreModeRef, DefsRef

from ninja import NinjaAPI
from ninja.conf import settings
from ninja.schema import Field, NinjaGenerateJsonSchema, Schema


class FullSchemaNameGenerator(NinjaGenerateJsonSchema):
def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
temp = super().get_defs_ref(core_mode_ref)
choices = self._prioritized_defsref_choices[temp]
choices.pop(0)
choices.pop(0)
self._prioritized_defsref_choices[temp] = choices
return temp


class Payload(Schema):
i: int
f: float


def to_camel(string: str) -> str:
return "".join(word.capitalize() for word in string.split("_"))


class Response(Schema):
i: int
f: float = Field(..., title="f title", description="f desc")

class Config(Schema.Config):
alias_generator = to_camel
populate_by_name = True


@pytest.fixture(scope="function")
def schema():
# setup up
settings.SCHEMA_GENERATOR_CLASS = (
"tests.test_custom_schema_generator.FullSchemaNameGenerator"
)
api = NinjaAPI()

@api.post("/test", response=Response)
def method(request, data: Payload):
return data.dict()

yield api.get_openapi_schema()
# reset
settings.SCHEMA_GENERATOR_CLASS = "ninja.schema.NinjaGenerateJsonSchema"


def test_full_name_schema(schema):
method = schema["paths"]["/api/test"]["post"]

assert method["requestBody"] == {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/test_custom_schema_generator__Payload"
}
}
},
"required": True,
}
assert method["responses"] == {
200: {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/test_custom_schema_generator__Response"
}
}
},
"description": "OK",
}
}
assert schema.schemas == {
"test_custom_schema_generator__Response": {
"title": "Response",
"type": "object",
"properties": {
"i": {"title": "I", "type": "integer"},
"f": {"description": "f desc", "title": "f title", "type": "number"},
},
"required": ["i", "f"],
},
"test_custom_schema_generator__Payload": {
"title": "Payload",
"type": "object",
"properties": {
"i": {"title": "I", "type": "integer"},
"f": {"title": "F", "type": "number"},
},
"required": ["i", "f"],
},
}