Source code for chaise.attrs

 1"""
 2Integration for attrs/cattrs
 3"""
 4
 5from typing import AbstractSet
 6
 7import attrs
 8from cattrs.converters import Converter
 9
10try:
11    # ujson is preferred, since muffin&c can also use it
12    from cattrs.preconf.ujson import configure_converter
13except ImportError:
14    from cattrs.preconf.json import configure_converter
15# Omitting orjson, even though it's a preconf, because I'm not confident it's a
16# drop-in equivalent to (u)json
17
18from . import DocumentRegistry
19
20
21# All implementations exhibit the conversions:
22# * bytes are wrapped in base85
23# * dates & datetimes are ISO 8601
24#: The converter used when talking to CouchDB.
25converter = Converter(
26    unstruct_collection_overrides={
27        AbstractSet: list,
28    }
29)
30configure_converter(converter)
31
32
[docs] 33class AttrsRegistry(DocumentRegistry):
[docs] 34 @classmethod 35 def document(cls, name: str, /, **flags): 36 """ 37 Registers a class as a document of the given type. 38 39 Passes it through :func:`attrs.define` 40 """ 41 func = super().document(name) 42 43 def _(klass: type): 44 # Disable slots so chaise can attach extra data 45 klass = attrs.mutable(klass, slots=False, **flags) 46 return func(klass) 47 48 return _
49
[docs] 50 def load_doc(self, cls: type, blob: dict): 51 return converter.structure(blob, cls)
52
[docs] 53 def dump_doc(self, doc) -> dict: 54 return converter.unstructure(doc)