當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Model方法代碼示例

本文整理匯總了Python中schematics.models.Model方法的典型用法代碼示例。如果您正苦於以下問題:Python models.Model方法的具體用法?Python models.Model怎麽用?Python models.Model使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在schematics.models的用法示例。


在下文中一共展示了models.Model方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_required

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_required():
    """
    messages:
        - MISSING_REQUIRED_FIELD
    """

    class DataRequired(Model):
        a = StringType(required=True)

    class DataNotRequired(Model):
        a = StringType(required=False)

    _test_data(
        model=DataRequired,
        data={},
        expected=(False, {"a": [messages.MISSING_REQUIRED_FIELD]}),
    )
    _test_data(model=DataNotRequired, data={}, expected=(True, {})) 
開發者ID:scrapinghub,項目名稱:spidermon,代碼行數:20,代碼來源:test_validators_schematics.py

示例2: test_choices

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_choices():
    """
    messages:
        - VALUE_NOT_IN_CHOICES
    """

    class Data(Model):
        a = StringType(choices=["a", "b"])
        b = IntType(choices=[1, 2, 3])

    _test_data(model=Data, data={}, expected=(True, {}))
    _test_data(model=Data, data={"a": "b", "b": 3}, expected=(True, {}))
    _test_data(
        model=Data,
        data={"a": "c", "b": 4},
        expected=(
            False,
            {
                "a": [messages.VALUE_NOT_IN_CHOICES],
                "b": [messages.VALUE_NOT_IN_CHOICES],
            },
        ),
    ) 
開發者ID:scrapinghub,項目名稱:spidermon,代碼行數:25,代碼來源:test_validators_schematics.py

示例3: test_string_regex

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_string_regex():
    """
    messages:
        - REGEX_NOT_MATCHED
    """

    class Data(Model):
        a = StringType(regex=".*def.*")

    _test_data(
        model=Data,
        data={"a": "abc"},
        expected=(False, {"a": [messages.REGEX_NOT_MATCHED]}),
    )
    _test_data(model=Data, data={"a": "abcdefghi"}, expected=(True, {}))
    _test_data(model=Data, data={"a": "def"}, expected=(True, {})) 
開發者ID:scrapinghub,項目名稱:spidermon,代碼行數:18,代碼來源:test_validators_schematics.py

示例4: test_boolean

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_boolean():
    """
    messages:
        - INVALID_BOOLEAN
        - NUMBER_TOO_LOW
        - NUMBER_TOO_HIGH
    """

    class Data(Model):
        a = BooleanType()

    INVALID = ["", "a", "2" "TRUE", "FALSE", "TruE", "FalsE"]
    VALID = [0, 1, "0", "1", "True", "False", "true", "false", True, False]
    _test_valid_invalid(
        model=Data,
        valid=VALID,
        invalid=INVALID,
        expected_error=messages.INVALID_BOOLEAN,
    ) 
開發者ID:scrapinghub,項目名稱:spidermon,代碼行數:21,代碼來源:test_validators_schematics.py

示例5: test_multiple_errors_per_field

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_multiple_errors_per_field():
    """
    messages:
        - FIELD_TOO_SHORT
        - REGEX_NOT_MATCHED
    """

    class Data(Model):
        a = StringType(min_length=3, regex=r"foo")

    data = {"a": "z"}
    v = SchematicsValidator(Data)
    result = v.validate(data, strict=True)
    assert result[0] is False
    error_messages = result[1]
    assert "a" in error_messages
    expected = [messages.FIELD_TOO_SHORT, messages.REGEX_NOT_MATCHED]
    assert sorted(error_messages["a"]) == expected 
開發者ID:scrapinghub,項目名稱:spidermon,代碼行數:20,代碼來源:test_validators_schematics.py

示例6: get_pv_model_info

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def get_pv_model_info(model: Union[peewee.Model, Type[peewee.Model]]):
    new_model_cls: Type[Model] = type(model.__class__.__name__ + 'Validator', (Model,), {})
    foreign_keys = {}
    peewee_fields = {}

    ret = {
        'table_name': get_pv_table_name(model),
        'primary_key': get_pv_pk_name(model),
        'foreign_keys': foreign_keys,
        'data_model': new_model_cls,
        '_peewee_fields': peewee_fields
    }

    for name, field in model._meta.fields.items():
        if isinstance(field, peewee.ForeignKeyField):
            rm = field.rel_model
            name = '%s_id' % name
            # TODO: 這裏可能會出問題
            foreign_keys[name] = [SQLForeignKey(get_pv_table_name(rm), get_pv_pk_name(rm))]

        peewee_fields[name] = field
        new_model_cls._append_field(name, field_class_to_schematics_field(field))

    return ret 
開發者ID:fy0,項目名稱:slim,代碼行數:26,代碼來源:validate.py

示例7: validate_references

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def validate_references(model: models.Model) -> None:
    """Validates that all `optplan.ReferenceType` are valid.

    This function recursively checks to see if every `ReferenceType` field
    is actually holding a reference to the appropriate type.

    Args:
        model: The model to check.

    Raises:
        ValueError: If a bad type is encountered.
    """

    def process_field(parent: models.Model,
                      child: Union[str, optplan.ProblemGraphNode],
                      field_type: optplan.ReferenceType) -> None:
        if not child:
            return

        if not isinstance(child, (str, field_type.reference_type)):
            raise ValueError("Expected type {} for node {}, got {}".format(
                field_type.reference_type, child, type(child)))

    _iter_optplan_fields(model, set(), process_field, pass_field_info=True) 
開發者ID:stanfordnqp,項目名稱:spins-b,代碼行數:26,代碼來源:io.py

示例8: _replace_ref_nodes_with_names

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def _replace_ref_nodes_with_names(
        model: models.Model,
        model_list: List[optplan.ProblemGraphNode]) -> None:
    """Replaces `optplan.ProblemGraphNode` references with names.

    This is used by `dumps` to replace all `optplan.ProblemGraphNode` instances
    with their names for serialization.

    Args:
        model: Model to recurse on.
        model_list: List of `optplan.ProblemGraphNode` models.
    """

    # Replace model reference with a name.
    def process_field(model: models.Model, child_model: models.Model) -> str:
        if isinstance(child_model, str):
            return child_model

        ind = model_list.index(child_model)
        return model_list[ind].name

    _iter_optplan_fields(model, set(), process_field) 
開發者ID:stanfordnqp,項目名稱:spins-b,代碼行數:24,代碼來源:io.py

示例9: get_node_model

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def get_node_model(self, node_meta_type: str,
                       node_type: str) -> Optional[models.Model]:
        """Retrieves the schematics model corresponding to a given type.

        Args:
            node_meta_type: Node metatype.
            node_type: Node type.

        Returns:
            Model corresponding to node metatype and type. Returns `None`
            if no such model can be found.
        """
        if node_meta_type not in self._optplan_node_map:
            return None

        if node_type not in self._optplan_node_map[node_meta_type]:
            return None
        return self._optplan_node_map[node_meta_type][node_type][0] 
開發者ID:stanfordnqp,項目名稱:spins-b,代碼行數:20,代碼來源:context.py

示例10: get_node_model_dict

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def get_node_model_dict(self,
                            node_meta_type: str) -> Dict[str, models.Model]:
        """Returns a mapping from node type to model.

        Args:
            node_meta_type: Node metatype to use.

        Returns:
            A dictionary for the given node metatype that maps node types
            to models. If the node metatype is not used in this context, an
            empty dictionary is returned.
        """
        if node_meta_type not in self._optplan_node_map:
            return {}

        return {
            node_type: vals[0] for node_type, vals in self._optplan_node_map[
                node_meta_type].items()
        } 
開發者ID:stanfordnqp,項目名稱:spins-b,代碼行數:21,代碼來源:context.py

示例11: register_node_type

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def register_node_type(self, node_meta_type: str, node_type: str,
                           model: models.Model, fun: CreatorFunction) -> None:
        """Registers a optplan node.

        Args:
            node_meta_type: Metatype of the node.
            node_type: Node type.
            model: Schematics model used to (de)serialize the node.
            fun: Callable used to instantiate the node from the model.

        Raises:
            ValueError: If a model with the same node metatype and node type
                was already registered for this context.
        """
        node_map = self._optplan_node_map.get(node_meta_type, {})
        if node_type in node_map:
            raise ValueError(
                "Node type '{}' with metatype '{}' was registered twice.".
                format(node_type, node_meta_type))
        node_map[node_type] = (model, fun)
        self._optplan_node_map[node_meta_type] = node_map 
開發者ID:stanfordnqp,項目名稱:spins-b,代碼行數:23,代碼來源:context.py

示例12: test_complex_type

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_complex_type():

    class Model(models.Model):
        x = schema_types.ComplexNumberType()

    model = Model({"x": 1 + 2j})
    model.validate()
    assert model.to_primitive() == {"x": [1, 2]}
    assert model.to_native() == {"x": 1 + 2j}

    model = Model({"x": [1, 2]})
    model.validate()
    assert model.to_primitive() == {"x": [1, 2]}
    assert model.to_native() == {"x": 1 + 2j}

    model = Model({"x": 1})
    model.validate()
    assert model.to_primitive() == {"x": [1, 0]}
    assert model.to_native() == {"x": 1 + 0j}

    with pytest.raises(ValueError, match="not convert to complex"):
        model = Model({"x": "hi"}) 
開發者ID:stanfordnqp,項目名稱:spins-b,代碼行數:24,代碼來源:test_schema_types.py

示例13: test_schematics_uses_cached_entries

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_schematics_uses_cached_entries():
    """
    Regression test. Validating that SchematicsSerializer uses the
    same json schema it used previously, as before erroneous
    use of the instantiated model as a key was causing memory leaks.
    """
    serializer = SchematicsSerializer()
    # A nested schema type is required as primitives have
    # hard-coded dictionaries representing the json.
    class SchematicsBody(Model):
        name = StringType(max_length=5)

    # ensure that instances have the same key as well.
    instance = ModelType(SchematicsBody)
    original_payload = serializer.to_json_schema(instance)
    second_payload = serializer.to_json_schema(instance)
    assert original_payload is second_payload

    # classes are also valid output to recieve that the json schema
    original_payload = serializer.to_json_schema(SchematicsBody)
    second_payload = serializer.to_json_schema(SchematicsBody)
    assert original_payload is second_payload 
開發者ID:toumorokoshi,項目名稱:transmute-core,代碼行數:24,代碼來源:test_schematics.py

示例14: _load_schematics_validator

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def _load_schematics_validator(cls, model_path):
        model_class = load_object(model_path)
        if not issubclass(model_class, Model):
            raise NotConfigured(
                "Invalid model, models must subclass schematics.models.Model"
            )
        return SchematicsValidator(model_class) 
開發者ID:scrapinghub,項目名稱:spidermon,代碼行數:9,代碼來源:pipelines.py

示例15: test_rogue_fields

# 需要導入模塊: from schematics import models [as 別名]
# 或者: from schematics.models import Model [as 別名]
def test_rogue_fields():
    """
    messages:
        - UNEXPECTED_FIELD
    """
    _test_data(
        model=Model, data={"a": 1}, expected=(False, {"a": [messages.UNEXPECTED_FIELD]})
    )
    _test_data(model=Model, data={"a": 1}, expected=(True, {}), strict=False) 
開發者ID:scrapinghub,項目名稱:spidermon,代碼行數:11,代碼來源:test_validators_schematics.py


注:本文中的schematics.models.Model方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。