简体   繁体   English

在 FastAPI 服务器中 x 秒后停止 function

[英]Stop a function after x seconds in a FastAPI server

I have a class A with a function foo() that logs information for an infinite time.我有一个 class A 和一个 function foo() 无限时间记录信息。 I would like to execute this function for 30 sec, retrieving these logs.我想执行此 function 30 秒,以检索这些日志。 For the recovery of the logs, I base myself on this article , the logs being realized at the C level.日志的恢复,我是根据这篇文章,实现C级别的日志。

So I realized, in addition to the code of the previous article, this portion of code, allowing to stop the execution of the function after 30 seconds.所以我意识到,除了上一篇文章的代码之外,这部分代码允许在 30 秒后停止执行 function。

if __name__ == '__main__':
    f = io.BytesIO()
    with stdout_redirector(f):
        p = multiprocessing.Process(target=A.foo, name="myfunc")
        p.start()
        # Cleanup
        p.join(30)
        if p.is_alive():
            # Terminate foo
            p.terminate()
            p.join()
data = f.getvalue().decode('utf-8')

This works fine as is.这可以正常工作。 However, I can't get this portion of the code into a fastAPI endpoint.但是,我无法将这部分代码放入 fastAPI 端点。 Indeed, no matter what I try, errors around the multiprocessing appear.事实上,无论我尝试什么,多处理都会出现错误。 Either the endpoint returns nothing, or a Pickle error appears... I don't know what to do!要么端点什么都不返回,要么出现 Pickle 错误……我不知道该怎么办!

Here I use multiprocessing only to stop foo() after a while;在这里,我使用 multiprocessing 只是为了在一段时间后停止 foo(); maybe there is another way to avoid problems with fastAPI.也许还有另一种方法可以避免 fastAPI 出现问题。 Does anyone have a way to fix my problem?有没有人有办法解决我的问题?

EDIT #1编辑#1

Based on Brandt's suggestion, the following function was done (Using windows, I can't use signals.):根据 Brandt 的建议,完成了以下 function(使用 windows,我无法使用信号。):

@timeout_decorator.timeout(30, use_signals=False)
def run_func(func):
    f = io.BytesIO()
    with stdout_redirector(f):
       func()   
    return f.getvalue().decode('utf-8')

And the following endpoint:以及以下端点:

@app.get('/foo')
def get_foo():
   data = run_func(A.foo)
   return {'data' : data}

but the EOFError: Ran out of input is triggered by thetimeout_decorator module.但是EOFError: Ran out of input是由 timeout_decorator 模块触发的。

You can use the ' timeout_decorator ' package:您可以使用 ' timeout_decorator ' package:

Back in the days, it provided me the solution for a similar issue;过去,它为我提供了类似问题的解决方案; I was/am not using FastAPI, but pretty much the same thing(AFAIU).我以前/现在不使用 FastAPI,但几乎是一样的东西(AFAIU)。

Basically, you just decorate the function you want to stop in case it surpasses some "T-seconds" timeout.基本上,您只需装饰要停止的 function,以防它超过某个“T 秒”超时。 Here is the code I used it:这是我使用它的代码:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM