In Django, how do I write a this for every function?

亡梦爱人 提交于 2020-01-07 09:03:13

问题


Whenever someone loads a page, I want to print "Hello" in console.

I don't want to add a decorator to all my 100 views. That's silly. I sort of want this decorator to automatically be added to my views. Hmm...


回答1:


Middleware: http://docs.djangoproject.com/en/dev/topics/http/middleware/#writing-your-own-middleware

Define a middleware class, override one of the functions defined above, print "Hello", return the appropriate object (according to docs), and add the middleware class to your settings.py

class PrintHelloMiddleware(object):
    def process_response(self, request, response):
        print "Hello"
        return None

# settings.py
MIDDLEWARE_CLASSES = ( # ... usual middleware
                       'path.to.my.middleware.PrintHelloMiddleware',
                      )


来源:https://stackoverflow.com/questions/4808664/in-django-how-do-i-write-a-this-for-every-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!