From 2e9f1c12f7ef2ea7a3bb8daaa9e26ef147d2d428 Mon Sep 17 00:00:00 2001 From: CNWei Date: Mon, 7 Apr 2025 16:35:14 +0800 Subject: [PATCH] =?UTF-8?q?feat,fix():=20=E4=BC=98=E5=8C=96funcs=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 优化 register 方法 --- commons/funcs.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/commons/funcs.py b/commons/funcs.py index 9a98b55..b6913e2 100644 --- a/commons/funcs.py +++ b/commons/funcs.py @@ -22,23 +22,25 @@ from commons import settings logger = logging.getLogger(__name__) -class Funcs: +class Funcs: FUNC_MAPPING = { "int": int, "float": float, "bool": bool } # 内置函数有的,直接放入mapping;内置函数没有的,在funcs中定义,自动放入mapping - @classmethod - def register(cls, name: str): + def register(cls, name: str | None = None): def decorator(func): + if name is None: + cls.FUNC_MAPPING[func.__name__] = func cls.FUNC_MAPPING[name] = func return func return decorator + @Funcs.register("url_unquote") def url_unquote(s: str) -> str: return urllib.parse.unquote(s) @@ -49,20 +51,24 @@ def to_string(s) -> str: # 将数据转换为str类型。 return f"'{s}'" + @Funcs.register("time_str") def time_str() -> str: return str(time.time()) + @Funcs.register("add") def add(a, b): return str(int(a) + int(b)) + @Funcs.register("sql") def sql(s: str) -> str: res = db.execute_sql(s) return res[0][0] + @Funcs.register("new_id") def new_id(): # 自增,永不重复 @@ -72,6 +78,7 @@ def new_id(): return id_file["id"] + @Funcs.register("last_id") def last_id() -> str: # 不自增,只返回结果 @@ -79,6 +86,7 @@ def last_id() -> str: id_file = FileHandle(settings.id_path) return id_file["id"] + @Funcs.register("md5") def md5(content: str) -> str: # 1,原文转为字节 @@ -86,6 +94,7 @@ def md5(content: str) -> str: result = hashlib.md5(content).hexdigest() return result + @Funcs.register("base64_encode") def base64_encode(content: str) -> str: # 1,原文转二进制 @@ -97,6 +106,7 @@ def base64_encode(content: str) -> str: return encode_str + @Funcs.register("base64_decode") def base64_decode(content: str) -> str: # 1,原文转二进制 @@ -108,18 +118,22 @@ def base64_decode(content: str) -> str: return decode_str + @Funcs.register("rsa_encode") def rsa_encode(content: str) -> str: ... + @Funcs.register("rsa_decode") def rsa_decode(content: str) -> str: ... - +@Funcs.register() +def func_name_test(): + ... if __name__ == '__main__': # res = url_unquote("%E6%88%90%E5%8A%9F%E3%80%82") # print(res) # print(f"计数器:{new_id()}") # print(f"当前数值:{last_id()}") - print(Funcs().FUNC_MAPPING) \ No newline at end of file + print(Funcs().FUNC_MAPPING)