我怎样才能在金字塔中建立一条路线

时间:2017-01-28 13:05:47

标签: python pyramid

我正在使用pyramid_handlers进行路由,controller.py

import pyramid_handlers
from blue_yellow_app.controllers.base_controller import BaseController
from blue_yellow_app.services.albums_service import AlbumsService


class AlbumsController(BaseController):
    @pyramid_handlers.action(renderer='templates/albums/index.pt')
    def index(self):
        # data / service access
        all_albums = AlbumsService.get_albums()

        # return the model
        return {'albums': all_albums}

我已在__init__.py注册了这样的内容:

from pyramid.config import Configurator
import blue_yellow_app.controllers.controller as albums


def main(_, **settings):
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.include('pyramid_handlers')

    config.add_handler(
        'albums' + 'ctrl_index', '/' + 'albums',
        handler=albums.AlbumsController, action='index')
    config.add_handler(
        'albums' + 'ctrl_index/', '/' + 'albums' + '/',
        handler=albums.AlbumsController, action='index')
    config.add_handler(
        'albums' + 'ctrl', '/' + 'albums' + '/{id}',
        handler=albums.AlbumsController)

现在如何为某个专辑添加新的控制器视图?我试过了 添加这样的新视图:

import pyramid_handlers
from blue_yellow_app.controllers.base_controller import BaseController
from blue_yellow_app.services.albums_service import AlbumsService


class AlbumsController(BaseController):
    @pyramid_handlers.action(renderer='templates/albums/index.pt')
    def index(self):
        # data / service access
        all_albums = AlbumsService.get_albums()

        # return the model
        return {'albums': all_albums}

    @pyramid_handlers.action(
        name='albums/{id}',
        renderer='templates/albums/item.pt')
    def album(self):
        print ('test')
        return {}

但它不起作用。如何为溃败albums/{id}添加视图?

1 个答案:

答案 0 :(得分:1)

看起来这段代码来自我的Python for Entrepreneurs course。让我们关注add_handler部分。该函数的通用形式是:

 config.add_handler(NAME, URL, handler=HANDLER, action=OPTIONAL_ACTION_METHOD)

您希望将网址/albums/rock-classics映射到操作方法def album(self)。在add_handler调用中,您有:

config.add_handler(
    'albumsctrl', '/' + 'albums' + '/{id}',
    handler=albums.AlbumsController)

问题是双重的:

您不在路由值或函数调用中指定操作。你应该:

# via add_handler, url: /albums/rock-classics
config.add_handler(
     'albumsctrl', '/albums/{id}',
     handler=albums.AlbumsController, action=album)

# via route, url: /albums/album/rock-classics
config.add_handler(
     'albumsctrl', '/albums/{action}/{id}',
     handler=albums.AlbumsController)

第二个问题是你在行动方法本身中的名字

 @pyramid_handlers.action(
     name='albums/{id}', <----- PROBLEM: this is not a valid action name
     renderer='templates/albums/item.pt')
 def album(self):
     print ('test')
     return {}

它应该重复名称=&#39;专辑&#39;或者只是方法的名称:

 @pyramid_handlers.action(renderer='templates/albums/item.pt')
 def album(self):
     print ('test')
     return {}