While learning how to build a web application using Flask and React, I've run into the ever delightful recursion error because I forgot to use an extremely helpful extension. The 'flask-restful' extension has a tool called 'SerializerMixin' which allows you to control how the objects are serialized.
What is Serialization?
It's a process to convert complex data structures (like Python objects) into a format that is easily transmitted/stored (like JSON).
How would SerializerMixin help to avoid recursion?
Let's say that in the application that is being built, there is a many to many relationship between authors and books. An author can write many books and a book can have multiple authors. When you try to fetch an author's information and you want to include a list of books that they've written, you might end up in an infinite loop when you serialize the author object with their books.
To prevent this, you would use 'serialize_rules' in the author class to control the depth of recursion, which would look something like- serialize_rules = ('-what_you_want_to_remove',)
. Just remember that when you use 'serialize_rules it has to equal a tuple.
Top comments (0)