Skip to content

Commit 1010e04

Browse files
committed
Add yaml serializer
1 parent 2cd73f1 commit 1010e04

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

aiocache/serializers/serializers.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import pickle # noqa: S403
3+
import yaml
34
from abc import ABC, abstractmethod
45
from typing import Any, Optional
56

@@ -197,3 +198,38 @@ def loads(self, value):
197198
if value is None:
198199
return None
199200
return msgpack.loads(value, raw=raw, use_list=self.use_list)
201+
202+
203+
class YamlSerializer(BaseSerializer):
204+
"""
205+
Transform data to YAML string with ``yaml.dump`` and ``yaml.load`` to retrieve it back.
206+
"""
207+
208+
def __init__(self, *args, loader=yaml.SafeLoader, **kwargs):
209+
"""
210+
Initialize the YamlSerializer with the specified loader.
211+
212+
:param loader: The YAML loader to use for deserialization. Default is yaml.SafeLoader.
213+
"""
214+
super().__init__(*args, **kwargs)
215+
self.loader = loader
216+
217+
def dumps(self, value):
218+
"""
219+
Serialize the received value using ``yaml.dump``.
220+
221+
:param value: obj
222+
:returns: str
223+
"""
224+
return yaml.dump(value)
225+
226+
def loads(self, value):
227+
"""
228+
Deserialize value using ``yaml.load``.
229+
230+
:param value: str
231+
:returns: obj
232+
"""
233+
if value is None:
234+
return None
235+
return yaml.load(value, Loader=self.loader)

0 commit comments

Comments
 (0)