Python Web架構Pylons中使用MongoDB的例子

來源:互聯網
上載者:User
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 會火。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.