Example of using MongoDB in Python Web framework Pylons

Source: Internet
Author: User

Example of using MongoDB in Python Web framework Pylons

This article describes how to use MongoDB in Python Web framework Pylons.

Python 1.0 was released after a long development. For formal product development, version 1.0 is of great significance, which indicates that the Pylons API has finally stabilized.

 

Although Pylons was born from Rails, as a pure Python Web framework, Pylons has a distinctive feature: Strong customization. Every layer of the Framework does not reinvent the wheel, but tries to integrate the existing Python library as much as possible. In the Model layer of MVC, Pylons supports SQLAlchemy by default. At present, NoSQL is very popular with MongoDB. It is also easy to apply MongoDB in Pylons. The following is a simple example.

 

Define the MongoDB initialization function and ing object in PROJECT/model/_ init _. py:

 

The Code is 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. _ metadata meta _. session = session

 

Class Page (MappedClass ):

Class _ metadata meta __:

Session = session

Name = 'page'

 

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

 

 

 

Initialize in PROJECT/config/environment. py:

 

The Code is 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. url'])

 

# Configuration options here (note: all config options will override

# Any Pylons config options)

 

Return config

 

 

 

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

 

The Code is as follows:

[App: main]

Database. uri = mongodb: // localhost: 27017/test

 

 

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

 

 

The Code is 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 ):

"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 implement a simple ORM. The Ming library is an ORM packaging library for PyMongo. It is a by-product of website reconstruction by SourceForge using TurboGears and MongoDB. It is a bit like SQLAlchemy ORM. In the above example, you can also replace Ming with MongoKit or other MongoDB ORM libraries, and even directly use PyMongo.

There is a feeling that MongoDB will get angry.

 

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.