From 3877126d03ffef12a4c2780d4f930e1db8045a71 Mon Sep 17 00:00:00 2001 From: yumoqing Date: Fri, 19 Jul 2024 15:44:19 +0800 Subject: [PATCH] bugfix --- appPublic/registerfunction.py | 69 +++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 15 deletions(-) diff --git a/appPublic/registerfunction.py b/appPublic/registerfunction.py index 98db70c..5cd71f2 100755 --- a/appPublic/registerfunction.py +++ b/appPublic/registerfunction.py @@ -1,5 +1,7 @@ -from inspect import isfunction, isroutinefunction +import asyncio +from inspect import isfunction, iscoroutinefunction from functools import partial +from appPublic.dictObject import DictObject from appPublic.Singleton import SingletonDecorator @SingletonDecorator @@ -8,14 +10,45 @@ class RegisterFunction: self.registKW = {} def register(self,name,func): - if not isfunction(func) and not isroutinefunction(func): + if not isfunction(func) and not iscoroutinefunction(func): error(f'RegisterFunction.register({name}, {func}): func is not a function or routine') return self.registKW[name] = func def get(self,name): return self.registKW.get(name,None) + + async def exe(name, *args, **kw): + f = self.get(name) + if f is None: + return None + if iscoroutinefunction(f): + return await f(*args, **kw) + return f(*args, **kw) +@SingletonDecorator +class RegisterCoroutine: + def __init__(self): + self.kw = DictObject() + + def register(self, name, func): + if not isfunction(func) and not iscoroutinefunction(func): + error(f'RegisterFunction.register({name}, {func}): func is not a function or routine') + return + if not self.kw.get(name): + self.kw[name] = [func] + else: + self.kw[name].append(func) + async def exe(self, name, *args, **kw): + fs = self.kw.get(name).copy() + fs.reverse() + if fs: + for f in fs: + if iscoroutinefunction(f): + await f(*args, **kw) + else: + f(*args, **kw) + return None def getRegisterFunctionByName(name): rf = RegisterFunction() @@ -25,20 +58,26 @@ def registerFunction(name, func): rf = RegisterFunction() rf.register(name, func) +async def main(): + d = {} + rf = RegisterCoroutine() + rf.register('test', z) + rf.register('test', y) + rf.register('test', x) + nd = await rf.exe('test', d) + print(nd) + if __name__ == '__main__': - def x(a): - print('x():a=',a) + def x(dic): + dic['a'] = 'a' + return dic - def y(a): - print('y():a=',a) + async def y(dic): + dic['b'] = 'b' + return dic - def z(): - rf = RegisterFunction() - for name in ['func1', 'func2' ]: - f = rf.get(name) - print(name,f('hahah')) + def z(dic): + dic['c'] = 1 + return dic - rf = RegisterFunction() - rf.register('func1',x) - rf.register('func2',y) - z() + asyncio.get_event_loop().run_until_complete(main())