Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 11 additions & 2 deletions jsonmodels/builders.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Builders to generate in memory representation of model and fields tree."""

import warnings
from collections import defaultdict

from . import errors
Expand Down Expand Up @@ -79,7 +80,15 @@ def type_name(self):
module_name = f"{self.type.__module__}.{self.type.__name__}"
return module_name.replace(".", "_").lower()

def build_definition(self, add_defintitions=True, nullable=False):
def build_definition(self, add_definitions=True, nullable=False, **kwargs):
if "add_defintitions" in kwargs:
warnings.warn(
"The 'add_defintitions' parameter is a typo and will be removed in "
"version 3.0; use 'add_definitions' instead.",
DeprecationWarning,
stacklevel=2,
)
add_definitions = kwargs.pop("add_defintitions")
properties = {
name: self.maybe_build(value) for name, value in self.properties.items()
}
Expand All @@ -90,7 +99,7 @@ def build_definition(self, add_defintitions=True, nullable=False):
}
if self.required:
schema["required"] = self.required
if self.definitions and add_defintitions:
if self.definitions and add_definitions:
schema["definitions"] = {
builder.type_name: builder.build_definition(False, False)
for builder in self.definitions
Expand Down
37 changes: 24 additions & 13 deletions jsonmodels/fields.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import re
import warnings
from weakref import WeakKeyDictionary

from dateutil.parser import parse
Expand Down Expand Up @@ -95,8 +96,9 @@ def _validate_against_types(self, value):
def _check_types(self):
if self.types is None:
raise ValidationError(
'Field "{type}" is not usable, try '
"different field type.".format(type=type(self).__name__)
'Field "{type}" is not usable, try different field type.'.format(
type=type(self).__name__
)
)

def to_struct(self, value):
Expand Down Expand Up @@ -136,9 +138,19 @@ def _validate_name(self):
if not re.match(r"^[A-Za-z_](([\w\-]*)?\w+)?$", self.name):
raise ValueError("Wrong name", self.name)

def structue_name(self, default):
def structure_name(self, default):
return self.name if self.name is not None else default

def structue_name(self, default):
"""Deprecated alias for structure_name. Will be removed in version 3.0."""
warnings.warn(
"'structue_name' is a typo and will be removed in version 3.0; "
"use 'structure_name' instead.",
DeprecationWarning,
stacklevel=2,
)
return self.structure_name(default)


class StringField(BaseField):
"""String field."""
Expand Down Expand Up @@ -241,8 +253,7 @@ def validate_single_value(self, value):

if not isinstance(value, self.items_types):
raise ValidationError(
"All items must be instances "
'of "{types}", and not "{type}".'.format(
'All items must be instances of "{types}", and not "{type}".'.format(
types=", ".join([t.__name__ for t in self.items_types]),
type=type(value).__name__,
)
Expand Down Expand Up @@ -275,11 +286,11 @@ def _finish_initialization(self, owner):
super()._finish_initialization(owner)

types = []
for type in self.items_types:
if isinstance(type, _LazyType):
types.append(type.evaluate(owner))
for type_ in self.items_types:
if isinstance(type_, _LazyType):
types.append(type_.evaluate(owner))
else:
types.append(type)
types.append(type_)
self.items_types = tuple(types)

def _elem_to_struct(self, value):
Expand Down Expand Up @@ -315,11 +326,11 @@ def _finish_initialization(self, owner):
super()._finish_initialization(owner)

types = []
for type in self.types:
if isinstance(type, _LazyType):
types.append(type.evaluate(owner))
for type_ in self.types:
if isinstance(type_, _LazyType):
types.append(type_.evaluate(owner))
else:
types.append(type)
types.append(type_)
self.types = tuple(types)

def validate(self, value):
Expand Down
12 changes: 6 additions & 6 deletions jsonmodels/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ def validate_fields(attributes):
}
taken_names = set()
for name, field in fields.items():
structue_name = field.structue_name(name)
if structue_name in taken_names:
raise ValueError("Name taken", structue_name, name)
taken_names.add(structue_name)
structure_name = field.structure_name(name)
if structure_name in taken_names:
raise ValueError("Name taken", structure_name, name)
taken_names.add(structure_name)


class Base(metaclass=JsonmodelMeta):
Expand Down Expand Up @@ -83,12 +83,12 @@ def iterate_over_fields(cls):
def iterate_with_name(cls):
"""Iterate over fields, but also give `structure_name`.

Format is `(attribute_name, structue_name, field_instance)`.
Format is `(attribute_name, structure_name, field_instance)`.
Structure name is name under which value is seen in structure and
schema (in primitives) and only there.
"""
for attr_name, field in cls.iterate_over_fields():
structure_name = field.structue_name(attr_name)
structure_name = field.structure_name(attr_name)
yield attr_name, structure_name, field

def to_struct(self):
Expand Down
10 changes: 5 additions & 5 deletions jsonmodels/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,17 @@ def _parse_list(field, parent_builder):
builder = builders.ListBuilder(
parent_builder, field.nullable, default=field._default
)
for type in field.items_types:
builder.add_type_schema(build_json_schema(type, builder))
for type_ in field.items_types:
builder.add_type_schema(build_json_schema(type_, builder))
return builder.build()


def _parse_embedded(field, parent_builder):
builder = builders.EmbeddedBuilder(
parent_builder, field.nullable, default=field._default
)
for type in field.types:
builder.add_type_schema(build_json_schema(type, builder))
for type_ in field.types:
builder.add_type_schema(build_json_schema(type_, builder))
return builder.build()


Expand All @@ -96,7 +96,7 @@ def _create_primitive_field_schema(field):
obj_type = "object"
else:
raise errors.FieldNotSupported(
f"Field {type(field).__class__.__name__} is not supported!"
f"Field {type(field).__name__} is not supported!"
)

if field.nullable:
Expand Down
2 changes: 1 addition & 1 deletion jsonmodels/utilities.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re
from collections import namedtuple

SCALAR_TYPES = tuple(list((str,)) + [int, float, bool])
SCALAR_TYPES = (str, int, float, bool)

ECMA_TO_PYTHON_FLAGS = {
"i": re.I,
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@ dev = [
"flake8",
"flake8-pyproject",
"invoke",
"importlib-metadata==4.13.0",
"isort",
"mccabe",
"pep8",
"py",
"pyflakes",
"pytest",
"pytest-cov",
Expand Down
Loading