예제 #1
0
class AnyAttribute(AnnotationBase):
    """
    Model representation of a schema xs:anyAttribute element.

    :param namespace: ##any | ##other) | List of anyURI | (##targetNamespace | ##local)
    :param process_contents: (lax | skip | strict) : strict
    """

    namespace: str = attribute(default="##any")
    process_contents: Optional[ProcessType] = attribute(name="processContents")

    def __post_init__(self):
        self.namespace = " ".join(unique_sequence(self.namespace.split()))

    @property
    def is_attribute(self) -> bool:
        return True

    @property
    def raw_namespace(self) -> Optional[str]:
        return self.namespace

    @property
    def real_name(self) -> str:
        clean_ns = "_".join(map(clean_uri, self.namespace.split()))
        return f"{clean_ns}_attributes"

    @property
    def real_type(self) -> str:
        return self.data_type_ref(DataType.ANY_TYPE)
예제 #2
0
class Choice(AnnotationBase):
    """
    Model representation of a schema xs:choice element.

    :param min_occurs: nonNegativeInteger : 1
    :param max_occurs: (nonNegativeInteger | unbounded)  : 1
    :param elements:
    :param groups:
    :param choices:
    :param sequences:
    :param any:
    """

    min_occurs: int = attribute(default=1, name="minOccurs")
    max_occurs: UnionType[int, str] = attribute(default=1, name="maxOccurs")
    elements: Array["Element"] = array_element(name="element")
    groups: Array["Group"] = array_element(name="group")
    choices: Array["Choice"] = array_element(name="choice")
    sequences: Array[Sequence] = array_element(name="sequence")
    any: Array["Any"] = array_element()

    def get_restrictions(self) -> Dict[str, Anything]:
        min_occurs = self.min_occurs if self.min_occurs > 1 else 0
        max_occurs = sys.maxsize if self.max_occurs == "unbounded" else self.max_occurs

        return {
            "choice": str(id(self)),
            "min_occurs": min_occurs,
            "max_occurs": max_occurs,
        }
예제 #3
0
class Alternative(AnnotationBase):
    """
    Model representation of a schema xs:alternative element.

    :param type: QName
    :param test: an XPath expression
    :param simple_type:
    :param complex_type:
    """

    type: Optional[str] = attribute()
    test: Optional[str] = attribute()
    simple_type: Optional[SimpleType] = element(name="simpleType")
    complex_type: Optional[ComplexType] = element(name="complexType")

    @property
    def real_name(self) -> str:
        if self.test:
            return text.snake_case(self.test)
        if self.id:
            return self.id
        return DEFAULT_ATTR_NAME

    @property
    def bases(self) -> Iterator[str]:
        if self.type:
            yield self.type
예제 #4
0
class Part(WsdlElement):
    """
    :param type:
    :param element:
    """

    type: Optional[str] = attribute()
    element: Optional[str] = attribute()
예제 #5
0
class Import:
    """
    :param location:
    :param namespace:
    """

    location: Optional[str] = attribute()
    namespace: Optional[str] = attribute()
예제 #6
0
class ExplicitTimezone(AnnotationBase):
    """
    Model representation of a schema xs:explicitTimezone element.

    :param value: NCName
    :param fixed: default false
    """

    value: str = attribute()
    fixed: bool = attribute(default=False)
예제 #7
0
class Import(SchemaLocation):
    """
    Model representation of a schema xs:import element.

    :param namespace: anyURI
    :param schema_location: anyURI
    """

    namespace: Optional[str] = attribute()
    schema_location: Optional[str] = attribute(name="schemaLocation")
예제 #8
0
class Notation(AnnotationBase):
    """
    Model representation of a schema xs:notation element.

    :param name: NCName
    :param public: token
    :param system: anyURI
    """

    name: Optional[str] = attribute()
    public: Optional[str] = attribute()
    system: Optional[str] = attribute()
예제 #9
0
class OpenContent(AnnotationBase):
    """
    Model representation of a schema xs:openContent element.

    :param applies_to_empty: default false
    :param mode: (none | interleave | suffix) : interleave
    :param any:
    """

    applies_to_empty: bool = attribute(default=False, name="appliesToEmpty")
    mode: Mode = attribute(default=Mode.INTERLEAVE)
    any: Any = element()
예제 #10
0
class Key(AnnotationBase):
    """
    Model representation of a schema xs:key element.

    :param name: NCName
    :param ref: QName
    :param selector:
    :param fields:
    """

    name: Optional[str] = attribute()
    ref: Optional[str] = attribute()
    selector: Optional[Selector] = element()
    fields: Array[Selector] = array_element(name="field")
예제 #11
0
class NameConvention:
    """
    Name convention model.

    :param case: Naming scheme, eg camelCase, snakeCase
    :param safe_prefix: A prefix to be prepended into names that match
        one of the reserved words: and, except, lambda, with, as,
        finally, nonlocal, while, assert, false, none, yield, break,
        for, not, class, from, or, continue, global, pass, def, if,
        raise, del, import, return, elif, in, true, else, is, try,
        str, int, bool, float, list, optional, dict, field
    """

    case: NameCase = attribute(optional=False)
    safe_prefix: str = attribute(optional=False)
예제 #12
0
class Attribute(AnnotationBase):
    """
    Model representation of a schema xs:attribute element.

    :param default: string
    :param fixed: string
    :param form: qualified | unqualified
    :param name: NCName
    :param ref: QName
    :param type: QName
    :param target_namespace: anyURI
    :param simple_type:
    :param use: (optional | prohibited | required) : optional
    """

    default: Optional[str] = attribute()
    fixed: Optional[str] = attribute()
    form: Optional[FormType] = attribute()
    name: Optional[str] = attribute()
    ref: Optional[str] = attribute()
    type: Optional[str] = attribute()
    target_namespace: Optional[str] = attribute(name="targetNamespace")
    simple_type: Optional[SimpleType] = element(name="simpleType")
    use: Optional[UseType] = attribute(default=UseType.OPTIONAL)

    @property
    def is_attribute(self) -> bool:
        return True

    @property
    def real_type(self) -> str:
        if self.simple_type:
            return self.simple_type.real_type
        if self.type:
            return self.type
        if self.ref:
            return self.ref

        return ""

    def get_restrictions(self) -> Dict[str, Anything]:
        restrictions = {}
        if self.use == UseType.REQUIRED:
            restrictions.update({
                "min_occurs": 1,
                "max_occurs": 1,
                "required": True
            })
        elif self.use == UseType.PROHIBITED:
            restrictions.update({"prohibited": True})

        if self.simple_type:
            restrictions.update(self.simple_type.get_restrictions())

        if self.type and self.type in self.token_types:
            restrictions["tokens"] = True

        return restrictions
예제 #13
0
class GeneratorOutput:
    """
    Main generator output options.

    :param max_line_length: Maximum line length
    :param package: Package name eg foo.bar.models
    :param format: Code generator output format name
    :param structure: Select an output structure
    :param docstring_style: Select a docstring style
    :param compound_fields: Use compound fields for repeating choices.
        Enable if elements ordering matters for your case.
    """

    max_line_length: int = attribute(default=79)
    package: str = element(default="generated")
    format: str = element(default="dataclasses")
    structure: OutputStructure = element(default=OutputStructure.FILENAMES)
    docstring_style: DocstringStyle = element(default=DocstringStyle.RST)
    compound_fields: bool = element(default=False)

    def __post_init__(self):
        if self.format == "pydata":
            warnings.warn(
                "Output format 'pydata' renamed to 'dataclasses'",
                DeprecationWarning,
            )
            self.format = "dataclasses"
예제 #14
0
class Extension(AnnotationBase):
    """
    Model representation of a schema xs:extension element.

    :param base: QName
    :param group:
    :param all:
    :param choice:
    :param sequence:
    :param any_attribute: any attributes with non-schema namespace
    :param open_content:
    :param attributes:
    :param attribute_groups:
    :param assertions:
    """

    base: Optional[str] = attribute()
    group: Optional[Group] = element()
    all: Optional[All] = element()
    choice: Optional[Choice] = element()
    sequence: Optional[Sequence] = element()
    any_attribute: Optional[AnyAttribute] = element(name="anyAttribute")
    open_content: Optional[OpenContent] = element(name="openContent")
    attributes: Array[Attribute] = array_element(name="attribute")
    attribute_groups: Array[AttributeGroup] = array_element(
        name="attributeGroup")
    assertions: Array[Assertion] = array_element(name="assert")

    @property
    def extensions(self) -> Iterator[str]:
        if self.base:
            yield self.base
예제 #15
0
class List(AnnotationBase):
    """
    Model representation of a schema xs:list element.

    :param simple_type:
    :param item_type: QName
    """

    simple_type: Optional[SimpleType] = element(name="simpleType")
    item_type: str = attribute(name="itemType", default="")

    @property
    def is_attribute(self) -> bool:
        return True

    @property
    def real_name(self) -> str:
        return "value"

    @property
    def real_type(self) -> str:
        return self.item_type

    def get_restrictions(self) -> Dict[str, Anything]:
        return {"tokens": True}
예제 #16
0
class FractionDigits(AnnotationBase):
    """
    Model representation of a schema xs:fractionDigits element.

    :param value: nonNegativeInteger
    """

    value: int = attribute()
예제 #17
0
class Field(AnnotationBase):
    """
    Model representation of a schema xs:field element.

    :param xpath: a subset of XPath expression
    """

    xpath: Optional[str] = attribute()
예제 #18
0
class ComplexContent(SimpleContent):
    """
    Model representation of a schema xs:complexContent element.

    :param fixed:
    """

    mixed: bool = attribute(default=False)
예제 #19
0
class Assertion(AnnotationBase):
    """
    Model representation of a schema xs:assertion element.

    :param test: an XPath expression
    """

    test: Optional[str] = attribute()
예제 #20
0
class WhiteSpace(AnnotationBase):
    """
    Model representation of a schema xs:whiteSpace element.

    :param value: (collapse | preserve | replace)
    """

    value: str = attribute()
예제 #21
0
class Include(SchemaLocation):
    """
    Model representation of a schema xs:include element.

    :param schema_location: anyURI
    """

    schema_location: Optional[str] = attribute(name="schemaLocation")
예제 #22
0
class Pattern(AnnotationBase):
    """
    Model representation of a schema xs:pattern element.

    :param value: string
    """

    value: str = attribute()
예제 #23
0
class MinInclusive(AnnotationBase):
    """
    Model representation of a schema xs:minInclusive element.

    :param value: anySimpleType
    """

    value: str = attribute()
예제 #24
0
class MinLength(AnnotationBase):
    """
    Model representation of a schema xs:minLength element.

    :param value: nonNegativeInteger
    """

    value: int = attribute()
예제 #25
0
class TotalDigits(AnnotationBase):
    """
    Model representation of a schema xs:totalDigits element.

    :param value: positiveInteger
    """

    value: int = attribute()
예제 #26
0
class GeneratorAlias:
    """
    Define an alias for a module, package, class and field Alias definition
    model.

    Each alias has a source attribute that refers to the original name
    in the schema definition and the target attribute for output name.
    For package and module aliases the source refers to the schema
    filename or target namespace depending the selected output
    structure.

    :param source: The source name from schema definition
    :param target: The target name of the object.
    """

    source: str = attribute(required=True)
    target: str = attribute(required=True)
예제 #27
0
class WsdlElement:
    """
    :param name:
    :param documentation:
    """

    name: str = attribute()
    documentation: Optional[Documentation] = element()
    ns_map: Dict = field(default_factory=dict, init=False)
예제 #28
0
class Attribute(AnnotationBase):
    """
    Model representation of a schema xs:attribute element.

    :param default: string
    :param fixed: string
    :param form: qualified | unqualified
    :param name: NCName
    :param ref: QName
    :param type: QName
    :param target_namespace: anyURI
    :param simple_type:
    :param use: (optional | prohibited | required) : optional
    """

    default: Optional[str] = attribute()
    fixed: Optional[str] = attribute()
    form: Optional[FormType] = attribute()
    name: Optional[str] = attribute()
    ref: Optional[str] = attribute()
    type: Optional[str] = attribute()
    target_namespace: Optional[str] = attribute(name="targetNamespace")
    simple_type: Optional[SimpleType] = element(name="simpleType")
    use: Optional[UseType] = attribute(default=UseType.OPTIONAL)

    @property
    def bases(self) -> Iterator[str]:
        if self.type:
            yield self.type

    @property
    def is_attribute(self) -> bool:
        return True

    @property
    def attr_types(self) -> Iterator[str]:
        if self.simple_type:
            yield from self.simple_type.attr_types
        elif self.type:
            yield self.type
        elif self.ref:
            yield self.ref

    def get_restrictions(self) -> Dict[str, Anything]:
        restrictions = {}
        if self.use == UseType.REQUIRED:
            restrictions.update({"required": True})
        elif self.use == UseType.PROHIBITED:
            restrictions.update({"prohibited": True})

        if self.simple_type:
            restrictions.update(self.simple_type.get_restrictions())

        return restrictions
예제 #29
0
class GeneratorConfig:
    """
    Generator configuration binding model.

    :cvar version: xsdata version number the config was created/updated
    :param output: output options
    :param conventions: generator conventions
    :param aliases: generator aliases
    """
    class Meta:
        name = "Config"
        namespace = "http://pypi.org/project/xsdata"

    version: str = attribute(init=False,
                             default=get_distribution("xsdata").version)
    output: GeneratorOutput = element(default_factory=GeneratorOutput)
    conventions: GeneratorConventions = element(
        default_factory=GeneratorConventions)
    aliases: GeneratorAliases = element(default_factory=GeneratorAliases)

    @classmethod
    def create(cls) -> "GeneratorConfig":
        obj = cls()
        obj.aliases.class_name.append(GeneratorAlias("fooType", "Foo"))
        obj.aliases.class_name.append(
            GeneratorAlias("ABCSomething", "ABCSomething"))
        obj.aliases.field_name.append(
            GeneratorAlias("ChangeofGauge", "change_of_gauge"))
        obj.aliases.package_name.append(
            GeneratorAlias("http://www.w3.org/1999/xhtml", "xtml"))
        obj.aliases.module_name.append(GeneratorAlias("2010.1", "2020a"))
        return obj

    @classmethod
    def read(cls, path: Path) -> "GeneratorConfig":
        ctx = XmlContext(
            element_name_generator=text.pascal_case,
            attribute_name_generator=text.camel_case,
        )
        config = ParserConfig(fail_on_unknown_properties=False)
        parser = XmlParser(context=ctx, config=config)
        return parser.from_path(path, cls)

    @classmethod
    def write(cls, output: TextIO, obj: "GeneratorConfig"):
        ctx = XmlContext(
            element_name_generator=text.pascal_case,
            attribute_name_generator=text.camel_case,
        )
        config = SerializerConfig(pretty_print=True)
        serializer = XmlSerializer(context=ctx,
                                   config=config,
                                   writer=XmlEventWriter)
        serializer.write(output,
                         obj,
                         ns_map={None: "http://pypi.org/project/xsdata"})
예제 #30
0
class Documentation(ElementBase):
    """
    Model representation of a schema xs:documentation element.

    :param lang: language
    :param source: anyURI
    :param elements: ({any})*
    :param attributes: any attributes with non-schema namespace
    """

    lang: Optional[str] = attribute()
    source: Optional[str] = attribute()
    elements: Array[object] = array_any_element(mixed=True)
    attributes: Optional["AnyAttribute"] = element()

    def tostring(self) -> Optional[str]:
        xml = docstring_serializer.render(Docstring(self.elements)).split(
            "\n", 1)
        return textwrap.dedent(clean_html(xml[1])[5:-7]).strip()