File: mapping-with-slug-keys.md

package info (click to toggle)
python-strictyaml 1.7.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,708 kB
  • sloc: python: 12,836; sh: 48; makefile: 3
file content (71 lines) | stat: -rw-r--r-- 1,394 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
---
title: Mapping with defined keys and a custom key validator (Map)
---

!!! warning "Experimental"

    This feature is in alpha. The API may change on a minor version increment.


A typical mapping except that the key values are determined
by the value provided by the validator.


Example yaml_snippet:

```yaml
Name: United Kingdom
country-code: GB
DIAL CODE: +44
official languages:
- English
- Welsh

```


```python
from collections import OrderedDict
from strictyaml import Map, Optional, Str, Seq, load, ScalarValidator
from ensure import Ensure

# This example uses slugify from the "python-slugify" package
from slugify import slugify

class Slug(ScalarValidator):
    def validate_scalar(self, chunk):
        return slugify(unicode(chunk.contents))

schema = Map({
    "name": Str(),
    Optional("country-code"): Str(),
    "dial-code": Str(),
    "official-languages": Seq(Str())
}, key_validator=Slug())

```



```python
Ensure(load(yaml_snippet, schema).data).equals(
    {
        "name": "United Kingdom",
        "country-code": "GB",
        "dial-code": "+44",
        "official-languages": ["English", "Welsh"],
    }
)

```






!!! note "Executable specification"

    Documentation automatically generated from 
    <a href="https://github.com/crdoconnor/strictyaml/blob/master/hitch/story/map-with-key-validator.story">map-with-key-validator.story
    storytests.