This commit is contained in:
yumoqing 2024-07-19 15:44:19 +08:00
parent 54393c736e
commit 3877126d03

View File

@ -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,7 +10,7 @@ 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
@ -16,6 +18,37 @@ class RegisterFunction:
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())