Skip to content

Commit da17412

Browse files
committed
add async save/read
1 parent 2c146eb commit da17412

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

app/io.py

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,56 @@
11
"""app.io.py"""
22
import json
33
import pathlib
4-
from typing import Dict, Union
4+
from typing import Dict, List, Union
5+
6+
import aiofiles
57

68
HERE = pathlib.Path(__file__)
79
DATA = HERE.joinpath("..", "data").resolve()
810

911

1012
def save(
11-
name: str, content: Union[str, Dict], write_mode: str = "w", indent: int = 2, **json_dumps_kwargs
13+
name: str, content: Union[str, Dict, List], write_mode: str = "w", indent: int = 2, **json_dumps_kwargs
1214
) -> pathlib.Path:
1315
"""Save content to a file. If content is a dictionary, use json.dumps()."""
1416
path = DATA / name
15-
if isinstance(content, dict):
17+
if isinstance(content, (dict, list)):
1618
content = json.dumps(content, indent=indent, **json_dumps_kwargs)
1719
with open(DATA / name, mode=write_mode) as f_out:
1820
f_out.write(content)
1921
return path
2022

2123

22-
def load(name: str, **json_kwargs) -> Union[str, Dict]:
24+
def load(name: str, **json_kwargs) -> Union[str, Dict, List]:
2325
"""Loads content from a file. If file ends with '.json', call json.load() and return a Dictionary."""
2426
path = DATA / name
2527
with open(path) as f_in:
2628
if path.suffix == ".json":
2729
return json.load(f_in, **json_kwargs)
2830
return f_in.read()
31+
32+
33+
class AIO:
34+
"""Asynsc compatible file io operations."""
35+
36+
@classmethod
37+
async def save(
38+
cls, name: str, content: Union[str, Dict, List], write_mode: str = "w", indent: int = 2, **json_dumps_kwargs
39+
):
40+
"""Save content to a file. If content is a dictionary, use json.dumps()."""
41+
path = DATA / name
42+
if isinstance(content, (dict, list)):
43+
content = json.dumps(content, indent=indent, **json_dumps_kwargs)
44+
async with aiofiles.open(DATA / name, mode=write_mode) as f_out:
45+
await f_out.write(content)
46+
return path
47+
48+
@classmethod
49+
async def load(cls, name: str, **json_kwargs) -> Union[str, Dict, List]:
50+
"""Loads content from a file. If file ends with '.json', call json.load() and return a Dictionary."""
51+
path = DATA / name
52+
async with aiofiles.open(path) as f_in:
53+
content = await f_in.read()
54+
if path.suffix == ".json":
55+
content = json.loads(content, **json_kwargs)
56+
return content

0 commit comments

Comments
 (0)