瀏覽代碼

use aiofiles again

Falko Schindler 2 年之前
父節點
當前提交
96ae60787a
共有 3 個文件被更改,包括 26 次插入2 次删除
  1. 13 2
      nicegui/storage.py
  2. 12 0
      poetry.lock
  3. 1 0
      pyproject.toml

+ 13 - 2
nicegui/storage.py

@@ -5,11 +5,12 @@ from collections.abc import MutableMapping
 from pathlib import Path
 from typing import Any, Dict, Iterator, Optional, Union
 
+import aiofiles
 from fastapi import Request
 from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
 from starlette.responses import Response
 
-from . import globals, observables
+from . import background_tasks, globals, observables
 
 request_contextvar: contextvars.ContextVar[Optional[Request]] = contextvars.ContextVar('request_var', default=None)
 
@@ -39,8 +40,18 @@ class ReadOnlyDict(MutableMapping):
 class PersistentDict(observables.ObservableDict):
 
     def __init__(self, filepath: Path) -> None:
+        self.filepath = filepath
         data = json.loads(filepath.read_text()) if filepath.exists() else {}
-        super().__init__(data, lambda: filepath.write_text(json.dumps(self)))
+        super().__init__(data, self.backup)
+
+    def backup(self) -> None:
+        async def backup() -> None:
+            async with aiofiles.open(self.filepath, 'w') as f:
+                await f.write(json.dumps(self))
+        if globals.loop:
+            background_tasks.create_lazy(backup(), name=self.filepath.stem)
+        else:
+            globals.app.on_startup(backup())
 
 
 class RequestTrackingMiddleware(BaseHTTPMiddleware):

+ 12 - 0
poetry.lock

@@ -1,5 +1,17 @@
 # This file is automatically @generated by Poetry and should not be changed by hand.
 
+[[package]]
+name = "aiofiles"
+version = "23.1.0"
+description = "File support for asyncio."
+category = "main"
+optional = false
+python-versions = ">=3.7,<4.0"
+files = [
+    {file = "aiofiles-23.1.0-py3-none-any.whl", hash = "sha256:9312414ae06472eb6f1d163f555e466a23aed1c8f60c30cccf7121dba2e53eb2"},
+    {file = "aiofiles-23.1.0.tar.gz", hash = "sha256:edd247df9a19e0db16534d4baaf536d6609a43e1de5401d7a4c1c148753a1635"},
+]
+
 [[package]]
 name = "anyio"
 version = "3.6.2"

+ 1 - 0
pyproject.toml

@@ -29,6 +29,7 @@ orjson = {version = "^3.8.6", markers = "platform_machine != 'i386' and platform
 pywebview = "^4.0.2"
 importlib_metadata = { version = "^6.0.0", markers = "python_version ~= '3.7'" } # Python 3.7 has no importlib.metadata
 itsdangerous = "^2.1.2"
+aiofiles = "^23.1.0"
 
 [tool.poetry.group.dev.dependencies]
 icecream = "^2.1.0"