Example of using MongoDB in Python web framework pylons

Source: Internet
Author: User
Tags ming
Pylons after a long period of development, finally released the 1.0 version. For formal product development, the 1.0 version is of great significance, which indicates that the pylons API has finally stabilized.

Pylons is a cottage Rails, but as a pure Python WEB framework, it has a distinct feature: strong customization. Each layer of the framework did not reinvent the wheel, but instead tried to integrate the existing Python library. In the MVC Model layer, pylons supports SQLAlchemy by default. Now NoSQL is very hot in MongoDB. It is also easy to apply MongoDB in pylons. The following is a simple example.

To define the MongoDB initialization function and the mapping object in project/model/__init__.py:

Copy the Code code as follows:


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 ()

To initialize in project/config/environment.py:

Copy the Code code as follows:


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 would override
# any pylons config options)

return config

Finally, add MongoDB configuration items to the Development.ini:

Copy the Code code as follows:


[App:main]
Database.uri = Mongodb://localhost:27017/test

If you need to initialize some data when the program is installed, you can add a project/websetup.py

Copy the Code code as follows:


"" "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):
"Commands to setup Wukong" "
# 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 was for demo. ')
Model.session.flush ()
Log.info ("Successfully set up.")

The Ming library is used here to connect MongoDB and make a simple ORM. The Ming library is the ORM wrapper library for Pymongo. It is a by-product of SourceForge's website reconfiguration with TurboGears and MongoDB. It's a bit like SQLAlchemy ORM. In the example above, it is also possible to replace the Ming with Mongokit or other MongoDB ORM libraries, even with Pymongo directly.
There is a feeling that MongoDB will fire.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.