anystore.serialize
Usually, these functions are not called directly by a program but by the higher
level Store.get
or Store.put
methods.
The store backends assume bytes
to be written to and read from. The two main
functions, to_store
and from_store
(de)serialize given values based on
configuration. See higher level anystore.store.BaseStore
for how to use
these serialization options in the stores get
, put
and stream
methods.
Serialization options:
serialization_mode:
- "raw": Return value as is, assuming bytes
- "json": Use
orjson
to (de)serialize - "pickle": Use
cloudpickle
to (de)serialize - "auto": Try different serialization methods, see below
serialization_func:
A callable that serializes the input to bytes
deserialization_func:
A callable that deserializes the bytes input to any data
model
A pydantic model class used for (de)serialization
from_store(value, serialization_mode='auto', deserialization_func=None, model=None)
Deserialize the bytes value retrieved from a store backend to any data.
In "auto" mode, this tries to deserialize value
in the following ways:
- Try to load a data object via
orjson
from the input - Try to deserialize via
cloudpickle
- Try to decode the value to
str
(use mode="raw" to make sure to getbytes
values) - Return the unserialized bytes value
Parameters:
Name | Type | Description | Default |
---|---|---|---|
serialization_mode
|
Mode | None
|
"auto", "pickle", "json", "raw" |
'auto'
|
deserialization_func
|
Callable | None
|
Function to use to deserialize, takes bytes as input |
None
|
model
|
Model | None
|
Pydantic model to use for serialization from a json bytes string |
None
|
Returns:
Type | Description |
---|---|
Any
|
The deserialized object |
Source code in anystore/serialize.py
to_store(value, serialization_mode='auto', serialization_func=None, model=None)
Serialize the given value to bytes.
In "auto" mode, this tries to serialize value
in the following ways:
- If
value
isbytes
, just store it - If
value
isstr
, encode tobytes
- If
value
is an instance of a pydanticBaseModel
, it is dumped to it's json byte string - If it is possible to serialize
value
to json, it is stored as that byte string - Try to cloudpickle or raise an error
Parameters:
Name | Type | Description | Default |
---|---|---|---|
serialization_mode
|
Mode | None
|
"auto", "pickle", "json", "raw" |
'auto'
|
serialization_func
|
Callable | None
|
Function to use to serialize |
None
|
model
|
Model | None
|
Pydantic model to use for serialization |
None
|