我想用這個非常簡單的例子讓我的頭繞着金字塔遍歷。我還沒有完全掌握的是從數據庫中「注入」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()
resources.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
views.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 {}
謝謝。你的例子並不完美,因爲你沒有將足夠的參數傳遞給調度器的'init',但是你給了我一個良好的開端。我一直在閱讀金字塔遍歷教程幾個小時,但它太複雜和充滿了可能不需要在那裏純粹演示遍歷的東西。所以我非常感謝你的回覆! – MFB
@MFB:對不起,編輯以前版本的錯誤。 :-)更正了'__init__'簽名。 –
非常好,謝謝你的伴侶 – MFB