国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

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

2020-02-23 04:59:52
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Pylons 經(jīng)過(guò)漫長(zhǎng)的開發(fā),終于放出了 1.0 版本。對(duì)于正規(guī)的產(chǎn)品開發(fā)來(lái)說(shuō),1.0 版本的意義很大,這表明 Pylons 的 API 終于穩(wěn)定下來(lái)了。

Pylons 雖是山寨 Rails 而生,但作為一個(gè)純 Python 的 Web 框架,它有一個(gè)鮮明的特點(diǎn):可定制性強(qiáng)。框架每一層都沒(méi)重新發(fā)明輪子,而是盡量整合現(xiàn)有的 Python 庫(kù)。在 MVC 的 Model 層,Pylons 默認(rèn)支持 SQLAlchemy。現(xiàn)在 NoSQL 很火 MongoDB 很熱。在 Pylons 中應(yīng)用 MongoDB 也很簡(jiǎn)單。下面是一個(gè)簡(jiǎn)單的示例。

在 PROJECT/model/__init__.py 中定義 MongoDB 初始化函數(shù)和映射對(duì)象:

代碼如下:
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 中進(jìn)行初始化:

代碼如下:
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 的配置項(xiàng):

代碼如下:
[app:main]
database.uri = mongodb://localhost:27017/test

如果需要在程序安裝時(shí)初始化一些數(shù)據(jù), 可以在 PROJECT/websetup.py 中加入

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 扶沟县| 巴彦淖尔市| 瑞安市| 额济纳旗| 武胜县| 房山区| 湖南省| 吴桥县| 辽宁省| 江北区| 镇远县| 保德县| 南宁市| 凤庆县| 桃园县| 北安市| 双城市| 六安市| 德江县| 遂溪县| 囊谦县| 富顺县| 岳西县| 福海县| 舟曲县| 泰顺县| 驻马店市| 枝江市| 江安县| 洛浦县| 蕉岭县| 元阳县| 湖南省| 临夏县| 德江县| 克东县| 多伦县| 耿马| 永川市| 天津市| 曲水县|