Skip to content

Instantly share code, notes, and snippets.

@paoyung
Last active June 11, 2022 16:46
MicroPython 用於儲存小型資料的 KeyValue 模組
# name: KeyValue.py, version: 0.1.2, author: paoyung.chang@gmail.com
# Copyright (c) 2022 Paoyung Chang. See the file LICENSE for copying permission.
# License link: https://gist.github.com/paoyung/7e465ad984a6cf24024508831ec54516
import os, json
LIST = None
DEBUG = True
# 此模組會產生一個名為 _kv_ 的目錄,並將資料檔放於其中。
kvDir = "_kv_"
if kvDir not in os.listdir("/"):
os.mkdir(kvDir)
LIST = os.listdir(kvDir)
# 顯示訊息,預設為開啟
def enableMsg(en=True):
global DEBUG
if en:
DEBUG = True
else:
DEBUG = False
print("debug mode:", DEBUG)
return DEBUG
def debugMsg(arg1="", *arg2, end="\n"):
global DEBUG
if DEBUG:
print(arg1, end=" ")
#
for arg in arg2:
print(arg, end=" ")
print(end=end)
def updateList():
global LIST
LIST = os.listdir(kvDir)
return True
# 列出已儲存的清單
def list():
global LIST
return LIST
def fn(key):
return "/{}/{}".format(kvDir, key)
# 清除所有資料
def renew(really=False):
global LIST
if really:
for each in list():
os.remove(fn(each))
LIST = []
return True
return False
def loadRaw(key):
v = None
if key in list():
with open(fn(key)) as f:
v = f.read()
return v
# 讀取
def load(key):
v = None
try:
v = json.loads(loadRaw(key))
except:
pass
return v
# 讀取,若無值使用給定的值並儲存
def get(key, value):
v = load(key)
if v is None:
save(key, value)
return value
else:
return v
# 儲存
def save(key, value):
if not type(key) == type('str'):
debugMsg("key must be string type.")
return False
v = json.dumps(value)
debugMsg("new:", v)
ov = loadRaw(key)
debugMsg("old:", ov)
msg = 'key: {}, v: {}'.format(key, v)
if not v == ov:
with open(fn(key), 'w') as f:
f.write(v)
updateList()
debugMsg(msg, "(update)")
return True
else:
debugMsg(msg, "(keep)")
return False
# 重新命名
def rename(key1, key2):
if key1 in list():
os.rename(fn(key1), fn(key2))
updateList()
return True
else:
debugMsg('key "{}" is not found.'.format(key1))
return False
# 刪除
def rm(key):
if key in list():
os.remove(fn(key))
updateList()
return True
else:
debugMsg('key "{}" is not found.'.format(key))
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment