Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Mongoengine to_python() is not working as expected

70 views
Skip to first unread message

Vishnu Jayan

unread,
Feb 1, 2024, 4:12:25 AM2/1/24
to MongoEngine Users
I am new to MongoDb and Python. I would like to work Field level Encryption. In order to understand the best practices, I have tried with simple to_mongo() and to_python() functions of Field class.
My code is as follows.

from mongoengine import Document, StringField
from faker import Faker
from mongoengine import connect

class TestMixin:
    pass

class TestField(StringField):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def to_mongo(self, value):
        print(f"Calling to_mongo with {value}")
        print("---------------------------")
        if value is not None:
            return f"to_mongo: {value}"

    def to_python(self, value):
        print(f"Calling to_python with {value}")
        print("---------------------------")
        # Modify the data when converting from MongoDB to Python
        if value is not None:
            modified_value = f"to_python: {value}"
            return modified_value
        return value

class MyDocument(Document):
    ssn = TestField(required=True)
    name = StringField(required=True)
    key = StringField()

if __name__ == '__main__':
    faker = Faker()
    connection = connect(host="mongodb://localhost:27017/test-db")
    my_doc = MyDocument(ssn=faker.ssn(), name=faker.name())
    try:
        print("On Saving/n-----------------")
        my_doc.save()
        print("Object saved")
    except Exception as e:
        print(str(e))

    data = MyDocument.objects
    print("ON retrieval\n-------------------")
    for item in data:
        print(f"id: {item.id}\n")
        print(f"ssn: {item.ssn}\n")
        print(f"name: {item.name}\n")
        print(f"key: {item.key}\n")
        print("-------------------")

My output is

Calling to_python with 375-07-7733
---------------------------
On Saving/n-----------------
Calling to_mongo with to_python: 375-07-7733
---------------------------
Object saved
ON retrieval
-------------------
Calling to_python with to_mongo: to_python: 066-30-4869
---------------------------
Calling to_python with to_mongo: to_python: 291-98-9774
---------------------------
Calling to_python with to_mongo: to_python: 815-65-3945

Kindly explain how this is happening and how to resolve it?
Reply all
Reply to author
Forward
0 new messages