问题
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