在Django中,如何为每个函数写一个? [英] In Django, how do I write a this for every function?
本文介绍了在Django中,如何为每个函数写一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当有人加载页面时,我想在控制台中打印Hello。
Whenever someone loads a page, I want to print "Hello" in console.
我不想为我所有的100个视图添加装饰器。太傻了
我想要这个装饰器自动添加到我的视图。
Hmm ...
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...
推荐答案
中间件: http://docs.djangoproject.com/en/dev/topics/http/middleware/#writing-your-自己的中间件
定义一个中间件类,覆盖上面定义的一个函数,打印Hello,返回适当的对象(根据文档)并将中间件类添加到您的settings.py
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',
)
这篇关于在Django中,如何为每个函数写一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文