5

我试图通过这个非常简单的示例来了解金字塔遍历。我还没有完全掌握的是Article从数据库中“注入”一个对象的位置。

照原样,/Article正确地找到并渲染了,article_view但那是相当没用的。如何/何时/在哪里使用 URL 的下一部分从数据库中查询特定文章?例如。/Article/5048230b2485d614ecec341d.

任何线索都会很棒!

初始化.py

from pyramid.config import Configurator
from pyramid.events import subscriber
from pyramid.events import NewRequest
import pymongo

from otk.resources import Root

def main(global_config, **settings):
    """ This function returns a WSGI application.
    """
    config = Configurator(settings=settings, root_factory=Root)
    config.add_static_view('static', 'otk:static')
    # MongoDB
    def add_mongo_db(event):
        settings = event.request.registry.settings
        url = settings['mongodb.url']
        db_name = settings['mongodb.db_name']
        db = settings['mongodb_conn'][db_name]
        event.request.db = db
    db_uri = settings['mongodb.url']
    MongoDB = pymongo.Connection
    if 'pyramid_debugtoolbar' in set(settings.values()):
        class MongoDB(pymongo.Connection):
            def __html__(self):
                return 'MongoDB: <b>{}></b>'.format(self)
    conn = MongoDB(db_uri)
    config.registry.settings['mongodb_conn'] = conn
    config.add_subscriber(add_mongo_db, NewRequest)
    config.include('pyramid_jinja2')
    config.include('pyramid_debugtoolbar')
    config.scan('otk')
    return config.make_wsgi_app()

资源.py

class Root(object):
    __name__ = None
    __parent__ = None

    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        if key == 'Article':
            return Article(self.request)
        else:
            raise KeyError

class Article:
    __name__ = ''
    __parent__ = Root

    def __init__(self, request):
        self.reqeust = request

    # so I guess in here I need to update the Article with
    # with the document I get from the db.  How?

    def __getitem__(self, key):
        raise KeyError

视图.py

from pyramid.view import view_config
from otk.resources import *
from pyramid.response import Response

@view_config(context=Root, renderer='templates/index.jinja2')
def index(request):
    return {'project':'OTK'}

@view_config(context=Article, renderer='templates/view/article.jinja2')
def article_view(context, request):
    # I end up with an instance of Article here as the context.. but 
    # at the moment, the Article is empty
    return {}
4

1 回答 1

8

您通常会从 URL 遍历的id部分返回一个Article对象。

遍历发生的情况是,对于 URL 路径中的每个元素,都会查找一个对象并将新的当前对象作为下一个路径元素查找的对象。

因此,对于Article,根对象被要求提供与该名称匹配的内容,并且该查找的结果成为新的“当前”对象,5048230b2485d614ecec341d然后在该新对象上进行查找。

因此,您正在寻找的是一个调度程序对象,它根据您传递的较长 id 查找文章,并返回您的Article实例:

class Root(object):
    __name__ = None
    __parent__ = None

    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        if key == 'articles':
            dispatch =  ArticleDispatcher(self.request)
            dispatch.__name__ = key
            dispatch.__parent__ = self
            return dispatch
        raise KeyError(key)

class ArticleDispatcher(object):
    __name__ = None
    __parent__ = None

    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        # Get a hold of the database here:
        db = findDatabase(self.request)
        if db.exists(key):          
            data = db.load(key)
            art = Article(data)
            art.__name__ = key
            art.__parent__ = self
            return art
        raise KeyError(key)

class Article:
    __name__ = None
    __parent__ = None

    def __init__(self, data):
        self.data = data

ArticleDispatcher注意当你使用URL 路径时我​​是如何返回的/articles,以及我是如何设置__name____parent__变量的;您需要那些能够为这些实例生成 URL。

现在返回的Article对象包含实际的文章数据,并且视图可以在渲染时访问该信息。

你真的很想去学习Pyramid Traversal 教程,它更详细地解释了这一切。

于 2012-09-06T08:40:44.300 回答