简体   繁体   English

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

[英]How to log redirects in Pyramid?

I'm trying to set it up so that my Pyramid app logs a message whenever it does a redirect - eg When one of my views raises HTTPFound . 我正在尝试对其进行设置,以使我的Pyramid应用程序HTTPFound重定向时(例如,当我的某个视图引发HTTPFound时)记录一条消息。

Creating a custom subclass of HTTPFound worked but it sucks to have to make sure that class is used everywhere in the app. 创建HTTPFound的自定义子类是HTTPFound但是必须确保该类在应用程序中的任何地方都使用很HTTPFound

I then had the idea of creating a custom exception view with context=HTTPFound but that view doesn't seem to get called. 然后,我想到了使用context=HTTPFound创建自定义异常视图的想法,但是该视图似乎没有被调用。

Is there a standard way to set up special handling for a redirect that is global to the app? 是否有一种标准方法可以为应用程序全局重定向设置特殊处理?

To log out redirects you would just have a tween that checks the return status, something like: 要注销重定向,您将只有一个补间可以检查返回状态,例如:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM