Beispiel #1
0
def get_example_row_serializer_class(add_id=False):
    """
    Generates a serializer containing a field for each field type. It is only used for
    example purposes in the openapi documentation.

    :param add_id: Indicates whether the id field should be added. This could for
        example differ for request or response documentation.
    :type add_id: bool
    :return: Generated serializer containing a field for each field type.
    :rtype: Serializer
    """

    if not hasattr(get_example_row_serializer_class, 'cache'):
        get_example_row_serializer_class.cache = {}

    class_name = ('ExampleRowResponseSerializer'
                  if add_id else 'ExampleRowRequestSerializer')

    if class_name in get_example_row_serializer_class.cache:
        return get_example_row_serializer_class.cache[class_name]

    fields = {}

    if add_id:
        fields['id'] = serializers.IntegerField(
            read_only=True,
            help_text='The unique identifier of the row in the table.')

    field_types = field_type_registry.registry.values()

    if len(field_types) == 0:
        logger.warning(
            'The field types appear to be empty. This module is probably '
            'imported before the fields have been registered.')

    for i, field_type in enumerate(field_types):
        # In order to generate a serializer we need a model instance. This method is
        # called before Django has been loaded so it will result in errors when
        # creating an instance. Therefore we create an object containing the default
        # field values of the model. With the object we can generate the example
        # serializer.
        defaults = model_default_values(field_type.model_class)
        instance = dict_to_object(defaults)
        kwargs = {
            'help_text':
            f'This field represents the `{field_type.type}` field. The '
            f'number in field_{i + 1} is in a normal request or response '
            f'the id of the field. '
            f'{field_type.get_serializer_help_text(instance)}'
        }
        get_field_method = \
            'get_response_serializer_field' if add_id else 'get_serializer_field'
        serializer_field = getattr(field_type, get_field_method)(instance,
                                                                 **kwargs)
        fields[f'field_{i + 1}'] = serializer_field

    class_object = type(class_name, (serializers.Serializer, ), fields)
    get_example_row_serializer_class.cache[class_name] = class_object

    return class_object
Beispiel #2
0
def test_dict_to_object():
    d1 = {"a": "b", "c": "d"}
    o1 = dict_to_object(d1)

    assert o1.a == "b"
    assert o1.c == "d"
    assert not hasattr(o1, "b")
    assert not hasattr(o1, "d")
    assert not hasattr(o1, "e")
def test_dict_to_object():
    d1 = {'a': 'b', 'c': 'd'}
    o1 = dict_to_object(d1)

    assert o1.a == 'b'
    assert o1.c == 'd'
    assert not hasattr(o1, 'b')
    assert not hasattr(o1, 'd')
    assert not hasattr(o1, 'e')
Beispiel #4
0
def get_example_row_serializer_class(add_id=False):
    """
    Generates a serializer containing a field for each field type. It is only used for
    example purposes in the openapi documentation.

    :param add_id: Indicates whether the id field should be added. This could for
        example differ for request or response documentation.
    :type add_id: bool
    :return: Generated serializer containing a field for each field type.
    :rtype: Serializer
    """

    if not hasattr(get_example_row_serializer_class, "cache"):
        get_example_row_serializer_class.cache = {}

    class_name = ("ExampleRowResponseSerializer"
                  if add_id else "ExampleRowRequestSerializer")

    if class_name in get_example_row_serializer_class.cache:
        return get_example_row_serializer_class.cache[class_name]

    fields = {}

    if add_id:
        fields["id"] = serializers.IntegerField(
            read_only=True,
            help_text="The unique identifier of the row in the table.")
        fields["order"] = serializers.DecimalField(
            max_digits=40,
            decimal_places=20,
            required=False,
            help_text=
            "Indicates the position of the row, lowest first and highest "
            "last.",
        )

    field_types = field_type_registry.registry.values()

    if len(field_types) == 0:
        logger.warning(
            "The field types appear to be empty. This module is probably "
            "imported before the fields have been registered.")

    for i, field_type in enumerate(field_types):
        # In order to generate a serializer we need a model instance. This method is
        # called before Django has been loaded so it will result in errors when
        # creating an instance. Therefore we create an object containing the default
        # field values of the model. With the object we can generate the example
        # serializer.
        defaults = model_default_values(field_type.model_class)
        instance = dict_to_object(defaults)
        kwargs = {
            "help_text":
            f"This field represents the `{field_type.type}` field. The "
            f"number in field_{i + 1} is in a normal request or response "
            f"the id of the field. "
            f"{field_type.get_serializer_help_text(instance)}"
        }
        get_field_method = ("get_response_serializer_field"
                            if add_id else "get_serializer_field")
        serializer_field = getattr(field_type, get_field_method)(instance,
                                                                 **kwargs)
        fields[f"field_{i + 1}"] = serializer_field

    class_object = type(class_name, (serializers.Serializer, ), fields)
    get_example_row_serializer_class.cache[class_name] = class_object

    return class_object