mercredi 29 avril 2015

How to handle python objects built from a web API that have references to each other?

I'm building a client library for a web API that exposes some objects like this:

# objs/foo/obj_id_1
{id: "foo_id_1"
 name: "your momma"
 bar: "bar_id_2"}

# objs/bar/obj_id_1
{id: "bar_id_2"
 name: "puh-lease"
 foo: "foo_id_1"}

So, objects of type foo have a reference to objects of type bar and vice versa.

In my python client library, I build python objects out of this API data. A Foo instance will have a bar attribute containing a Bar instance instead of just the id of the bar and a Bar instance has a reference to a Foo instance in the foo attribute.

My python classes have save and refresh methods that POST or GET from the web API, and they do this for sub-objects. For example, if I call a_foo.refresh(), this will also automatically call a_foo.bar.refresh().

The above is a very simplified example, and there might be many different classes all referring to the same instance of bar or foo or any of the many other types of objects we get.

I think my question is actually two questions:

  1. What is a good design or strategy to ensure that when I build an object from api data that all of its references to other objects point to the same object if I've already built that object from previous api requests?
  2. When I call save or refresh what's a good design or strategy to prevent an infinite loop when two or more objects refer to each other?

Aucun commentaire:

Enregistrer un commentaire