An example of using MongoDB in the Python Web framework Pylons

  • 2020-04-02 13:14:56
  • OfStack

Pylons came out with version 1.0 after a long development process. The 1.0 release made a lot of sense for formal product development, suggesting that Pylons' API was finally stabilizing.

Pylons is a Rails clone, but as a pure Python Web framework, it has one distinct feature: it is highly customizable. Rather than reinventing the wheel at each level of the framework, it tries to integrate existing Python libraries. In the Model layer of MVC, Pylons supports SQLAlchemy by default. Now NoSQL is hot and MongoDB is hot. It's also easy to apply MongoDB in Pylons. Here is a simple example.

Define the MongoDB initialization function and mapping object in PROJECT/model/ arbitration. Py:


from ming import Session
from ming import schema
from ming.orm import MappedClass
from ming.orm import FieldProperty, ForeignIdProperty, RelationProperty
from ming.orm import ThreadLocalORMSession
session = None
def init_single_model(model_class):
    model_class.__mongometa__.session = session
class Page(MappedClass):
    class __mongometa__:
        session = session
        name = 'pages'
    _id = FieldProperty(schema.ObjectId)
    title = FieldProperty(str)
    content = FieldProperty(str)
def init_model(engine):
    global session
    session = ThreadLocalORMSession(doc_session=Session(engine))
    init_single_model(Page)
    MappedClass.compile_all()

In the PROJECT/config/environment. The initialized in the py:


from ..model import init_model
from ming.datastore import DataStore
def load_environment(global_conf, app_conf):
    ...
    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', default_filters=['escape'],
        imports=['from webhelpers.html import escape'])
    # Setup the mongodb database engine
    init_model(DataStore(config['database.uri']))
    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)
    return config

Finally, add the MongoDB configuration item in development.ini:


[app:main]
database.uri = mongodb://localhost:27017/test

If you need to initialize some data at program installation time, you can add it in PROJECT/websetup.py


"""Setup the wukong application"""
import logging
import pylons.test
from .config.environment import load_environment
from . import model
log = logging.getLogger(__name__)
def setup_app(command, conf, vars):
    """Place any commands to setup wukong here"""
    # Don't reload the app if it was loaded under the testing environment
    if not pylons.test.pylonsapp:
        load_environment(conf.global_conf, conf.local_conf)
        log.info("Adding demo data.")
        page = model.Page(title='demo', content='This is for demo.')
        model.session.flush()
        log.info("Successfully set up.")

The Ming library is used to connect to MongoDB and to do simple ORM. The Ming library is an ORM wrapper library for PyMongo. It is a byproduct of SourceForge's efforts to refactor the web site with TurboGears and MongoDB. It is a bit like SQLAlchemy ORM in use. In the example above, you can also replace Ming with MongoKit or another MongoDB ORM library, or even directly with PyMongo.
There's a feeling that MongoDB will be hot.


Related articles: