【问题标题】:how to redirect to particular url on 404如何重定向到 404 上的特定 url
【发布时间】:2011-06-21 15:53:00
【问题描述】:
@error(404)
def error404(error):
    return 'Nothing here, sorry'

这是在bottle framework 中响应 404 的方式。但是在 404 上,我想重定向到特定的 url,比如 http://abc.com/。有可能吗?

【问题讨论】:

    标签: python bottle


    【解决方案1】:
    @error(404)
    def error404(error):
        from bottle import redirect
        # maybe test the error to see where you want to go next?
        redirect(new_url, 303) # HTTP 303 should be used in this case
    

    编辑我不能 100% 确定这可以做到,我现在不能测试它,但我会稍后测试它并更新答案,除非你打败我.

    【讨论】:

    • 你用的是什么版本的瓶子?我在瓶中处理错误时遇到了麻烦-我认为是因为文档不是最新的代码。我使用瓶子 0.9.dev 尝试了上面的重定向代码并得到了 500 响应代码并显示“严重错误”错误:HTTPResponse('HTTP Response 303',)
    • 抱歉耽搁了,暂时关闭 StackOverflow。该示例引用了 Git 的 HEAD 版本。它可能同时发生了变化,但我对此表示怀疑。您是否检查过您的应用程序中发生的确切错误? 500 通常表明您的代码中有错误。
    【解决方案2】:
        @app.error(404)
        def error(err):
            bottle.response.status = 303 
            bottle.response.header['Location'] = '/' 
    

    【讨论】:

    • 你能解释一下为什么它会起作用,而不仅仅是给出答案吗?
    【解决方案3】:
    import urllib
    url = urllib.urlopen('www.google.com/testing') #a 404 address
    if url.code == 404:
        url = urllib.urlopen('www.google.com')
    

    创建 urlobject 时,.code 实例返回页面的代码,

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多