This article describes how to use MongoDB in the PythonWeb framework Pylons. For more information, see Pylons. after a long development, version 1.0 is released. 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.