4. 验证

映射文件库的一个关键部分是验证mapfiles—检查各种关键字的选项是否有效。为了实现这一点,已经在JSON文件中对mapfile语言的完整定义进行了编码-请参见 Mapfile 架构 .

jsonschema 用于通过将转换后的字典转换为JSON来验证映射文件。有关创建JSON模式的详细信息,请参阅优秀的文档 here .

4.1. 什么是已验证?

每个mapfile关键字都有一组有限的允许值。例如 LAYER``的`UNIT 必须是下面列表中的字符串之一:

{
"units": {
    "enum": [
        "dd",
        "feet",
        "inches",
        "kilometers",
        "meters",
        "miles",
        "nauticalmiles",
        "percentages",
        "pixels"
    ]
}
}

如果映射文件包含不在此列表中的值,则将引发错误。

对于 COLOR 等设置,允许使用RGB值或十六进制代码。在架构中使用 oneOf 属性进行说明:

{
"color": {
    "oneOf": [
        {
            "minItems": 3,
            "items": {
                "minimum": -1,
                "type": "number",
                "maximum": 255
            },
            "type": "array",
            "maxItems": 3
        },
        {
            "pattern": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$",
            "type": "string",
            "example": "#aa33cc"
        }
    ]
}
}

4.2. 如何验证

映射文件验证可以使用 命令行界面 运行,或者直接在python代码中运行:

s = """MAP
    NAME "sample"
    LAYER
        NAME "test"
        STATUS DEFAULT
        DATA "SELECT GEOM
        FROM
        TABLE"
        TYPE LINEX
    END
END"""

d = mappyfile.loads(s, include_position=True)
v = Validator()
errors = v.validate(d, add_comments=True, version=7.6)
for e in errors:
    print(e)

输出以下内容:

{'column': 9, 'message': 'ERROR: Invalid value in TYPE', 'line': 9, 'error': "u'linex' is not one of [u'chart', u'circle', u'line', u'point', u'polygon', u'raster', u'query', u'annotation']"}

在加载映射文件(或映射文件片段)时, include_position 参数可以设置为 True 这样任何验证错误都包括行位置。

可选的 version 参数可用于根据特定版本的MapServer验证映射文件。