在 Pylons 中使用 MongoDB 的例子

jopen 8年前發布 | 8K 次閱讀 Python開發

Pylons 經過漫長的開發,終于放出了 1.0 版本。對于正規的產品開發來說,1.0 版本的意義很大,這表明 Pylons 的 API 終于穩定下來了。

Pylons 雖是山寨 Rails 而生,但作為一個純 Python 的 Web 框架,它有一個鮮明的特點:可定制性強。框架每一層都沒重新發明輪子,而是盡量整合現有的 Python 庫。在 MVC 的 Model 層,Pylons 默認支持 SQLAlchemy。現在 NoSQL 很火 MongoDB 很熱。在 Pylons 中應用 MongoDB 也很簡單。下面是一個簡單的示例。

PROJECT/model/__init__.py 中定義 MongoDB 初始化函數和映射對象:

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

PROJECT/config/environment.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

最后在 development.ini 中加入 MongoDB 的配置項:

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

如果需要在程序安裝時初始化一些數據, 可以在 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.")

這里使用了 Ming 庫來連接 MongoDB 并做簡單的 ORM。Ming 庫是對 PyMongo 的 ORM 包裝庫。它是 SourceForge 用 TurboGears 和 MongoDB 對網站進行重構的副產物。使用起來有點象 SQLAlchemy ORM 。在上面的示例中,也可以把 Ming 替換成 MongoKit 或其它 MongoDB 的 ORM 庫,甚至直接用 PyMongo 也無不可。

有種感覺,MongoDB 會火。

Pylons 經過漫長的開發,終于放出了 1.0 版本。對于正規的產品開發來說,1.0 版本的意義很大,這表明 Pylons 的 API 終于穩定下來了。

Pylons 雖是山寨 Rails 而生,但作為一個純 Python 的 Web 框架,它有一個鮮明的特點:可定制性強。框架每一層都沒重新發明輪子,而是盡量整合現有的 Python 庫。在 MVC 的 Model 層,Pylons 默認支持 SQLAlchemy。現在 NoSQL 很火 MongoDB 很熱。在 Pylons 中應用 MongoDB 也很簡單。下面是一個簡單的示例。

PROJECT/model/__init__.py 中定義 MongoDB 初始化函數和映射對象:

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

PROJECT/config/environment.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

最后在 development.ini 中加入 MongoDB 的配置項:

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

如果需要在程序安裝時初始化一些數據, 可以在 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.")

這里使用了 Ming 庫來連接 MongoDB 并做簡單的 ORM。Ming 庫是對 PyMongo 的 ORM 包裝庫。它是 SourceForge 用 TurboGears 和 MongoDB 對網站進行重構的副產物。使用起來有點象 SQLAlchemy ORM 。在上面的示例中,也可以把 Ming 替換成 MongoKit 或其它 MongoDB 的 ORM 庫,甚至直接用 PyMongo 也無不可。

有種感覺,MongoDB 會火。

來自: http://zhuoqiang.me/use-mongodb-in-pylons.html

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!