diff --git a/source/serialization.txt b/source/serialization.txt index 723e7d5e..f0b439ec 100644 --- a/source/serialization.txt +++ b/source/serialization.txt @@ -56,19 +56,40 @@ Serializing Custom Classes To serialize a custom class, you must convert the class to a dictionary. The following example serializes a custom class by using the ``vars()`` method, and then inserts the -serialized object into a collection: +serialized object into a collection. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: -.. code-block:: python +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. code-block:: python + + class Restaurant: + def __init__(self, name, cuisine): + self.name = name + self.cuisine = cuisine + + restaurant = Restaurant("Example Cafe", "Coffee") + restaurant_dict = vars(restaurant) + + collection.insert_one(restaurant_dict) + + .. tab:: Asynchronous + :tabid: async - class Restaurant: - def __init__(self, name, cuisine): - self.name = name - self.cuisine = cuisine + .. code-block:: python - restaurant = Restaurant("Example Cafe", "Coffee") - restaurant_dict = vars(restaurant) + class Restaurant: + def __init__(self, name, cuisine): + self.name = name + self.cuisine = cuisine + + restaurant = Restaurant("Example Cafe", "Coffee") + restaurant_dict = vars(restaurant) - collection.insert_one(restaurant_dict) + await collection.insert_one(restaurant_dict) The preceding example serializes the ``Restaurant`` object into the following dictionary: @@ -84,15 +105,32 @@ Deserializing Custom Classes To deserialize a custom class, you must convert the dictionary back into an instance of the class. The following example retrieves a document from a collection, and then converts -it back into a ``Restaurant`` object from the preceding example: +it back into a ``Restaurant`` object from the preceding example. Select the +:guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. code-block:: python + + def deserialize_restaurant(doc): + return Restaurant(name=doc["name"], cuisine=doc["cuisine"]) + + restaurant_doc = collection.find_one({"name": "Example Cafe"}) + restaurant = deserialize_restaurant(restaurant_doc) + + .. tab:: Asynchronous + :tabid: async -.. code-block:: python + .. code-block:: python - def deserialize_restaurant(doc): - return Restaurant(name=doc["name"], cuisine=doc["cuisine"]) + def deserialize_restaurant(doc): + return Restaurant(name=doc["name"], cuisine=doc["cuisine"]) - restaurant_doc = collection.find_one({"name": "Example Cafe"}) - restaurant = deserialize_restaurant(restaurant_doc) + restaurant_doc = await collection.find_one({"name": "Example Cafe"}) + restaurant = deserialize_restaurant(restaurant_doc) To learn more about retrieving documents from a collection, see the :ref:`pymongo-retrieve` guide.