PyMODM ODM

Similar to Ruby's Mongoid, PyMODM is an ODM for Python that follows closely on Django's built-in ORM. Installing pymodm can be done via pip, as shown in the following code:

pip install pymodm

Then we need to edit settings.py and replace the database ENGINE with a dummy database, as shown in the following code:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy'
}
}

Then we add our connection string anywhere in settings.py, as shown in the following code:

from pymodm import connect
connect("mongodb://localhost:27017/myDatabase", alias="MyApplication")

Here, we have to use a connection string that has the following structure:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

Options have to be pairs of name=value with an & between each pair. Some interesting pairs are shown in the following table:

Name

Description

minPoolSize/maxPoolSize

Minimum and maximum pool size for connections.

w

Write concern option.

wtimeoutMS

Timeout for write concern operations.

Journal

Journal options.

readPreference

Read preference to be used for replica sets. Available options are: primary, primaryPreferred, secondary, secondaryPreferred, nearest.

maxStalenessSeconds

Specifies, in seconds, how stale (data lagging behind master) a secondary can be before the client stops using it for read operations.

SSL

Using SSL to connect to the database.

authSource

Used in conjunction with username, this specifies the database associated with the user's credentials. When we use external authentication mechanisms, this should be $external for LDAP or Kerberos.

authMechanism

Authentication mechanism can be used for connections. Available options for MongoDB are: SCRAM-SHA-1, MONGODB-CRMONGODB-X.509.

MongoDB enterprise (paid version) offers two more options: GSSAPI (Kerberos), PLAIN (LDAP SASL)

 

Model classes need to inherit from MongoModel. The following code shows what a sample class will look like:

from pymodm import MongoModel, fields
class User(MongoModel):
email = fields.EmailField(primary_key=True)
first_name = fields.CharField()
last_name = fields.CharField()

This has a User class with first_name, last_name, and email fields, where email is the primary field.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset