Samuel O.D.
Samuel O.D.

Reputation: 392

Python Flask app made with Swagger crashes unexpectedly

I have a flask python server that runs in a docker container. I have found that once the execution reaches a certain point, the container just crashes, and no exceptions or messages are thrown even if you surround your code in any try-except block.

The problem seems to arise when the code tries to access a certain variable. In my case it crashes when accessing the bar variable:

try:
    logger.trace(foo)
    logger.trace(bar)
except Exception as e:
    logger.error(e)

My code is this simple. Reading foo and logging its value works as expected but the bar variable is never logged and the container crashes. The console only shows this message after logging foo:

Disconnected from container.

This happens whenever I make a request from Postman and reach this part of the code.

The variable bar is supposed to be an instance of a class modeled with Swagger.

What could make Python crash when a variable is read that would not show or throw any exception?

Upvotes: 0

Views: 246

Answers (1)

Samuel O.D.
Samuel O.D.

Reputation: 392

After some research I found out that this can happen when there is an infinite recursion problem.

In my case, at some point in the code the object instance gets assigned to the wrong property resulting in this infinite recursion problem:


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

I also found a way to find this kinds of errors. Swagger creates automatically a test file for the controller. If the endpoint is tested for that specific case with the test file the error is shown this way:

maximum recursion depth exceeded while calling a Python object

When I tested this case with Postman the error is not thrown, it just crashes.

Upvotes: 1

Related Questions