Python 使用 Swagger 制作的 Flask 应用程序意外崩溃
Python Flask app made with Swagger crashes unexpectedly
我有一个在 docker 容器中运行的烧瓶 python 服务器。我发现一旦执行到某个点,容器就会崩溃,并且不会抛出任何异常或消息,即使您将代码放在任何 try-except 块中也是如此。
当代码试图访问某个变量时,问题似乎出现了。在我的例子中,它在访问 bar 变量时崩溃:
try:
logger.trace(foo)
logger.trace(bar)
except Exception as e:
logger.error(e)
我的代码就是这么简单。读取 foo 并记录其值按预期工作,但从未记录 bar 变量并且容器崩溃。控制台仅在记录 foo:
后显示此消息
Disconnected from container.
每当我从 Postman 发出请求并到达代码的这一部分时,就会发生这种情况。
变量 bar 应该是使用 Swagger 建模的 class 的一个实例。
当读取一个不会显示或抛出任何异常的变量时,什么会导致 Python 崩溃?
经过一些研究,我发现当存在无限递归问题时可能会发生这种情况。
在我的例子中,在代码中的某个时刻,对象实例被分配给了错误的 属性 导致了这个无限递归问题:
from swagger_server.model import ObjectModel
def do_something(bar: ObjectModel) -> ObjectModel:
<some code that modifies bar>
return bar
bar = ObjectModel(
id = 'obj1'
)
bar.id = do_something(bar)
# Here is the problem. The ID now points to the sub_object creating
# infinite recursion but it does not throw an error here
# bar = do_something(bar) # This is the correct way to use the do_something() function
# do_something(bar) # As they're objects we could use this too and will modify the original object
<some more code>
logger.trace(bar) # Accessing the data triggers the crash
我也找到了一种查找此类错误的方法。 Swagger 自动为控制器创建一个测试文件。如果使用测试文件针对该特定情况测试了端点,则错误将以这种方式显示:
maximum recursion depth exceeded while calling a Python object
当我用 Postman 测试这个案例时,没有抛出错误,它只是崩溃了。
我有一个在 docker 容器中运行的烧瓶 python 服务器。我发现一旦执行到某个点,容器就会崩溃,并且不会抛出任何异常或消息,即使您将代码放在任何 try-except 块中也是如此。
当代码试图访问某个变量时,问题似乎出现了。在我的例子中,它在访问 bar 变量时崩溃:
try:
logger.trace(foo)
logger.trace(bar)
except Exception as e:
logger.error(e)
我的代码就是这么简单。读取 foo 并记录其值按预期工作,但从未记录 bar 变量并且容器崩溃。控制台仅在记录 foo:
后显示此消息Disconnected from container.
每当我从 Postman 发出请求并到达代码的这一部分时,就会发生这种情况。
变量 bar 应该是使用 Swagger 建模的 class 的一个实例。
当读取一个不会显示或抛出任何异常的变量时,什么会导致 Python 崩溃?
经过一些研究,我发现当存在无限递归问题时可能会发生这种情况。
在我的例子中,在代码中的某个时刻,对象实例被分配给了错误的 属性 导致了这个无限递归问题:
from swagger_server.model import ObjectModel
def do_something(bar: ObjectModel) -> ObjectModel:
<some code that modifies bar>
return bar
bar = ObjectModel(
id = 'obj1'
)
bar.id = do_something(bar)
# Here is the problem. The ID now points to the sub_object creating
# infinite recursion but it does not throw an error here
# bar = do_something(bar) # This is the correct way to use the do_something() function
# do_something(bar) # As they're objects we could use this too and will modify the original object
<some more code>
logger.trace(bar) # Accessing the data triggers the crash
我也找到了一种查找此类错误的方法。 Swagger 自动为控制器创建一个测试文件。如果使用测试文件针对该特定情况测试了端点,则错误将以这种方式显示:
maximum recursion depth exceeded while calling a Python object
当我用 Postman 测试这个案例时,没有抛出错误,它只是崩溃了。