Skip to main content
 首页 » 编程设计

python之Pyramid 中的条件重定向

2025年05月04日20me-sa

我正在寻找一种将用户重定向到与使用 @view_config 兼容的不同路由/模板的方法。

我有一个读取上传文件并尝试根据文件内容创建新模型的函数。我想知道是否有一种干净的方法可以根据新模型的创建是成功还是有错误将用户重定向到两个 url 之一。

如果模型创建成功,我想将用户重定向到模型页面。如果出现错误,我想将用户重定向到错误页面。但是,在呈现错误页面时,我无法分解原始函数 (load_model) 的 view_config。

@view_config(renderer="error.mak") 
@view_config(renderer="model.mak", 
        route_name='load_model_route') 
def load_model(self): 
   ... 
   model = Model.find_model(model_name) 
   if model: 
      #redirect to model_route 
   else: 
      #redirect to model_error_route 

每个路由都有一个将它绑定(bind)到一个函数的@view_config。

请您参考如下方法:

您要问的不是“如何重定向”,而是“如何在 View 函数中更改渲染器”。为了快速回答,我认为你可以使用:

request.override_renderer = 'other-renderer.mak' 

但我认为这不是一个好主意。下面是大多数时候用于处理表单提交的常用模式:

from pyramid.httpexceptions import HTTPFound, HTTPNotFound 
from pyramid.url import route_url 
from your_app import Model, some_stuff, save_to_db 
 
@view_config(route_name='new_model', 
        renderer='model/new.mak', request_method='GET') 
def new(request): 
    """Shows the empty form.""" 
    return {'model': Model(), 'errors': {}} 
 
@view_config(route_name='create_model', 
        renderer='model/new.mak', request_method='POST') 
def create(request): 
    """Receives submitted form.""" 
    model = some_stuff() 
    if len(model.errors) = 0: # is valid 
        # do your stuff, then redirect 
        save_to_db(model) 
        return HTTPFound(route_url('show_model', request, model_id=model.id)) 
    # is invalid 
    return {'model': model, 'errors': model.errors} 
 
@view_config(route_name='show_model', 
    renderer='model/show.mak', request_method='GET') 
def show(request): 
    """Shows details of one model.""" 
    model = Model.find(request.matchdict['model_id']) 
    if model is None: 
        return HTTPNotFound() 
    return {'model': model} 

简而言之:

  • 当您在新模型的路线上有一个 GET 时,您会显示一个空表单。
  • 您在不同的 View 函数中处理表单提交(POST)
    • 如果数据有效,你就做你的事情,然后用 HTTPFound 重定向
    • 如果数据无效,你返回一个字典来再次显示表单,这次有错误
  • 您在 GET 和 POST 中使用相同的渲染器,但在 POST 中的渲染器仅在出现无效数据时使用(否则,你重定向)。
  • 您有另一个 View 函数来显示创建的模型。