| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import dataclasses |
| 4 |
import datetime |
| 5 |
from typing import Any, Iterable, Union, cast, get_args, get_origin |
| 6 |
|
| 7 |
from django import forms |
| 8 |
|
| 9 |
from allauth.account.fields import EmailField |
| 10 |
|
| 11 |
|
| 12 |
FIELD_MAPPING = { |
| 13 |
forms.CharField: {"type": "string"}, |
| 14 |
forms.IntegerField: {"type": "integer"}, |
| 15 |
forms.FloatField: {"type": "number"}, |
| 16 |
forms.BooleanField: {"type": "boolean"}, |
| 17 |
forms.DateField: {"type": "string", "format": "date"}, |
| 18 |
forms.DateTimeField: {"type": "string", "format": "date-time"}, |
| 19 |
forms.EmailField: {"type": "string", "format": "email"}, |
| 20 |
EmailField: {"type": "string", "format": "email"}, |
| 21 |
forms.URLField: {"type": "string", "format": "uri"}, |
| 22 |
forms.DecimalField: { |
| 23 |
"type": "string", |
| 24 |
"format": "decimal", |
| 25 |
"pattern": r"^\d+(\.\d+)?$", |
| 26 |
}, |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
def _choice_values(field: forms.ChoiceField) -> list[Any]: |
| 31 |
values: list[Any] = [] |
| 32 |
choices = cast(Iterable[tuple[Any, Any]], field.choices) |
| 33 |
for value, label in choices: |
| 34 |
if isinstance(label, (list, tuple)): |
| 35 |
# Grouped choices (optgroups): label is a list of (value, label). |
| 36 |
values.extend(subvalue for subvalue, _ in label) |
| 37 |
else: |
| 38 |
values.append(value) |
| 39 |
return values |
| 40 |
|
| 41 |
|
| 42 |
def spec_for_field(field: forms.Field) -> dict[str, Any]: |
| 43 |
field_spec: dict[str, Any] |
| 44 |
if isinstance(field, forms.MultipleChoiceField): |
| 45 |
item_spec: dict[str, Any] = {"type": "string"} |
| 46 |
values = _choice_values(field) |
| 47 |
if values: |
| 48 |
item_spec["enum"] = values |
| 49 |
field_spec = {"type": "array", "items": item_spec} |
| 50 |
elif isinstance(field, forms.ChoiceField): |
| 51 |
field_spec = {"type": "string"} |
| 52 |
values = _choice_values(field) |
| 53 |
if values: |
| 54 |
field_spec["enum"] = values |
| 55 |
else: |
| 56 |
field_spec = dict(FIELD_MAPPING.get(type(field), {"type": "string"})) |
| 57 |
if hasattr(field, "max_length") and field.max_length: |
| 58 |
field_spec["maxLength"] = field.max_length |
| 59 |
if hasattr(field, "min_length") and field.min_length: |
| 60 |
field_spec["minLength"] = field.min_length |
| 61 |
if hasattr(field, "help_text") and field.help_text: |
| 62 |
field_spec["description"] = field.help_text |
| 63 |
return field_spec |
| 64 |
|
| 65 |
|
| 66 |
def unwrap_optional_type(typ) -> tuple: |
| 67 |
if get_origin(typ) is not Union: |
| 68 |
return typ, True |
| 69 |
args = get_args(typ) |
| 70 |
if len(args) != 2 or type(None) not in args: |
| 71 |
return typ, True |
| 72 |
return args[0], False |
| 73 |
|
| 74 |
|
| 75 |
def spec_for_dataclass(dc) -> tuple[dict, dict]: |
| 76 |
example = {} |
| 77 |
props = {} |
| 78 |
required = [] |
| 79 |
for field_id, field in dc.__dataclass_fields__.items(): |
| 80 |
descriptor = {} |
| 81 |
if description := field.metadata.get("description"): |
| 82 |
descriptor["description"] = description |
| 83 |
if exa := field.metadata.get("example"): |
| 84 |
descriptor["example"] = exa |
| 85 |
example[field_id] = exa |
| 86 |
field_type, req = unwrap_optional_type(field.type) |
| 87 |
if req: |
| 88 |
required.append(field_id) |
| 89 |
if field_type is str: |
| 90 |
descriptor.update({"type": "string"}) |
| 91 |
elif field_type is int: |
| 92 |
descriptor.update({"type": "integer"}) |
| 93 |
elif field_type is float: |
| 94 |
descriptor.update({"type": "number", "format": "float"}) |
| 95 |
elif field_type is bool: |
| 96 |
descriptor.update({"type": "boolean"}) |
| 97 |
elif field_type is datetime.datetime: |
| 98 |
descriptor.update({"type": "string", "format": "date-time"}) |
| 99 |
elif field_type is datetime.date: |
| 100 |
descriptor.update({"type": "string", "format": "date"}) |
| 101 |
elif field_type is list: |
| 102 |
descriptor.update({"type": "array"}) |
| 103 |
elif field_type is dict: |
| 104 |
descriptor.update({"type": "object"}) |
| 105 |
elif dataclasses.is_dataclass(field_type): |
| 106 |
nested_schema, nested_exmple = spec_for_dataclass(field_type) |
| 107 |
descriptor.update(nested_schema) |
| 108 |
descriptor["example"] = nested_exmple |
| 109 |
else: |
| 110 |
descriptor.update({"type": "string"}) |
| 111 |
props[field_id] = descriptor |
| 112 |
schema = {"type": "object", "properties": props, "required": required} |
| 113 |
return schema, example |