NimarkoGram Docs
RU
Docs/Files and cache

Files and cache

Cache a result locally and recover when the cached file disappears.

On this pagePick a storage locationWrite and read a resultDistinguish an empty file from a cache miss

Pick a storage location

A document opened by the user, a preference and a generated preview have different lifetimes. Use self.set_setting for a selected option. For text you can regenerate, create a directory inside file_utils.get_cache_dir(). The cache root is shared by the client. Name the directory after the plugin's stable ID.

Write and read a result

Run this example in a plugin background job. It creates a directory, writes a UTF-8 string and reads it back. The write uses Path.write_text so the caller receives an OSError if storage is full or inaccessible. The SDK helper file_utils.write_file logs write errors and returns no success flag.

Python
from pathlib import Path
from file_utils import get_cache_dir, read_file

def save_preview(plugin_id, text):
    directory = Path(get_cache_dir()) / plugin_id
    directory.mkdir(parents=True, exist_ok=True)
    file = directory / "preview.txt"
    file.write_text(text, encoding="utf-8")
    return read_file(str(file))

Choose the filename in your plugin. When previews belong to different accounts, include the signed-in user ID in the path. This short example expects one writer at a time. Schedule competing writes on the same queue.

Distinguish an empty file from a cache miss

For an empty UTF-8 file, read_file returns "". An open or decoding error returns None. Test value is None before asking the user to regenerate data. For binary files, use read_file_bytes.

Try three cases: save “Hello”, save an empty string, then remove only preview.txt and read it again. The third case should lead back to preview generation. Leave other cached client files in place during this test.