如何在金字塔中记录重定向?

2024-05-19 23:26:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试设置它,以便我的金字塔应用程序在执行重定向时记录消息—例如,当我的一个视图引发HTTPFound。你知道吗

创建一个HTTPFound的自定义子类是可行的,但是必须确保该类在应用程序中的任何地方都被使用,这很糟糕。你知道吗

然后我想到用context=HTTPFound创建一个定制的异常视图,但是这个视图似乎没有被调用。你知道吗

有没有一种标准的方法来为应用程序的全局重定向设置特殊处理?你知道吗


Tags: 方法视图应用程序消息标准地方记录context
1条回答
网友
1楼 · 发布于 2024-05-19 23:26:30

要注销重定向,您只需要一个tween来检查返回状态,例如:

from wsgiref.simple_server import make_server

from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPFound


def hello1(request):
    raise HTTPFound(request.route_url('hello2'))


def hello2(request):
    return {'boom': 'shaka'}


def redirect_logger(handler, registry):
    def redirect_handler(request):
        response = handler(request)
        if response.status_int == 302:
            print("OMGZ ITS NOT GOING WHERE YOU THINK")

        return response
    return redirect_handler


def main():
    config = Configurator()

    config.add_route('hello1', '/', view=hello1)
    config.add_route('hello2', '/hi', view=hello2, renderer='json')
    config.add_tween('__main__.redirect_logger')

    app = config.make_wsgi_app()
    return app

if __name__ == '__main__':
    app = main()
    server = make_server('0.0.0.0', 8080, app)
    print("http://0.0.0.0:8080")
    server.serve_forever()

相关问题 更多 >