home-assistant core 源码粗读--如何管理多用户-用户存储(二)

程序中搜索User,  很容易命中homeassistant/auth/models.py

程序中大量使用了attr.s 进行模型的声明。上篇说过dataclass,以及BaseModel , 区别见: https://www.modb.pro/db/412679

文件中定义了5个模型,这里只需要猜测他们的意思即可,这里重点分析User。

程序中搜索User, 很容易命中homeassistant/auth/auth_store.py  # 进行User相关的存取相关。

需要细看的是AuthStore.__init__,AuthStore.async_get_users,AuthStore.async_create_user,

def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the auth store."""
self.hass = hass
self._loaded = False
self._users: dict[str, models.User] = None # 从AuthStore.async_get_user可知,_users的结构是:{user_id:user}
self._groups: dict[str, models.Group] = None # type: ignore[assignment] # 同理直接猜测 _groups的结构是 {group_id:group}
self._perm_lookup: PermissionLookup = None # type: ignore[assignment]
self._store = Store[dict[str, list[dict[str, Any]]]](
hass, STORAGE_VERSION, STORAGE_KEY, private=True, atomic_writes=True
) # 自行百度python 的泛型:做类型提示和编辑器类型校验用的。 Store 内部的结构可以从Store.async_save 中看到就是一个需要存储的结构。
在官网搜索storage:

 跳转到 https://www.home-assistant.io/integrations/analytics/   可以看到

Your data is securely stored in Cloudflare’s Key-Value store. It will be stored for a maximum of 60 days since the last update. Only aggregated data is made publicly available.

This is an example of how the information is stored:

uuid:12a3456bc78d90123ef4567g789012h3

{‘version’: ‘2024.2.2’, ‘installation_type’: ‘Home Assistant OS’, ‘country’: ‘NO’}

 

在阅读AuthStore.async_create_user 过程中可以发现调用了self._async_schedule_save() , self._store.async_delay_save()、self._data_to_save()

return {
"users": users,
"groups": groups,
"credentials": credentials,
"refresh_tokens": refresh_tokens,
}

我们再 看看self._store.async_delay_save()。函数收到的是一个Callable 

homeassistant/helpers/storage.py L179
self._data = {
"version": self.version,
"minor_version": self.minor_version,
"key": self.key,
"data_func": data_func,
}

可以看到data_func 也只是一个callable 。

接着看主逻辑: self._async_callback_delayed_write、self._async_handle_write_data() , 可以看到_async_handle_write_data 内部对data_func进行执行,并创建成data字段。

接下来就是对self._data 进行保存L352: self._async_write_data(self.path, data) 、self._write_data 至此用户数据保存完成。至于里面的path参数就是保存到了某个文件中(可以看看此文件的开头:STORAGE_DIR)。

回过头来看上面的return 部分,可以看到一个保存流程,把用户,用户组,用户身份,相关的用户token都进行了一次保存,而且是以json 的形式保持到了文件中,没有接入数据库!!

 

所以homeassistant 目前只适合家庭级的用户使用。期待官方后续上线用户组,把用户等保存到数据库中。

 

posted @ 2024-02-21 16:28  xunhanliu  阅读(41)  评论(0编辑  收藏  举报