gpt4 book ai didi

python - 我如何在 Pyramid 中建立一条路线

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:12 26 4
gpt4 key购买 nike

我使用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)

现在如何为某个专辑添加新的 Controller View ?我试过了添加新 View ,如下所示:

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}的 View ?

最佳答案

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

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

您想要将 URL /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 {}

它应该是重复的 name='album' 或只是方法的名称:

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

关于python - 我如何在 Pyramid 中建立一条路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41910115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com