我有以下代码:
run_in_background (
update_contacts(data={'email': email,'access_token': g.tokens['access_token']})
)
我创建了这个函数来在后台处理被调用的函数:
def run_in_background(function):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_in_executor(None, **function**, **data**)
我将如何检索函数和传递给它的数据?
答案 0 :(得分:1)
使用装饰器!
装饰器是一个包装器,它接受一个函数作为参数:
def decorate(func):
def wrapper(*args, **kwargs):
# *args and **kwargs are input vars passed to func() on its call
return f(*args, **kwargs)
return wrapper
@decorate
def func(arg1, arg2, **kwargs):
#do_things
在您的情况下,这看起来像:
def run_in_background(func):
def wrapper(*args, **kwargs):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# remember, data is in *args (or **kwargs if it's a keyword arg)
loop.run_in_executor(None, func, data)
return None
return wrapper
@run_in_background
# data is an arg or positional arg here, but could easily be data=data
def update_contents(data):
# function logic
您可以将装饰器更改为在背景与非背景之间切换:
def run_in_background(func):
def wrapper(*args, **kwargs):
if background:
# run in background
else:
func(data)
return None
return wrapper
@run_in_background
def update_contact(data, background=False):
#contact func logic
这将允许您保留装饰器并减少代码重复,同时使您可以灵活地指定是否需要后台进程