File tree 2 files changed +10
-3
lines changed
2 files changed +10
-3
lines changed Original file line number Diff line number Diff line change 5
5
import asyncio
6
6
import logging
7
7
from pathlib import Path
8
+ import shutil
8
9
from typing import TYPE_CHECKING , Any , cast
9
10
11
+ from atomicwrites import atomic_write
12
+
10
13
from ..common .helpers .json import JSON_DECODE_EXCEPTIONS , json_dumps , json_loads
11
14
12
15
if TYPE_CHECKING :
@@ -152,11 +155,14 @@ async def async_save(self) -> None:
152
155
153
156
def do_save () -> None :
154
157
# make backup before we write a new file
155
- if self .filename . is_file ():
156
- self .filename . replace ( self .filename_backup )
158
+ self .filename_backup . unlink ( True )
159
+ shutil . copy ( self .filename , self .filename_backup )
157
160
158
- with open (self .filename , "w" , encoding = "utf-8" ) as _file :
161
+ # use atomomic write to avoid corrupting the file
162
+ # if power is cut during write, we don't write a corrupted file
163
+ with atomic_write (self .filename , encoding = "utf-8" , overwrite = True ) as _file :
159
164
_file .write (json_dumps (self ._data ))
165
+
160
166
LOGGER .debug ("Saved data to persistent storage" )
161
167
162
168
async with self ._save_lock :
Original file line number Diff line number Diff line change @@ -35,6 +35,7 @@ server = [
35
35
" aiohttp==3.11.11" ,
36
36
" aiorun==2024.8.1" ,
37
37
" async-timeout==5.0.1" ,
38
+ " atomicwrites==1.4.1" ,
38
39
" coloredlogs==15.0.1" ,
39
40
" cryptography==44.0.0" ,
40
41
" orjson==3.10.12" ,
You can’t perform that action at this time.
0 commit comments