Django里面的RequestContext

原文链接: http://www.cnblogs.com/james1207/p/3320127.html
    c = RequestContext(request, {
    'foo': 'bar',
    })

    get_template('about.html').render(c)

当我们定义一个RequestContext对象的时候,它的构造函数 __init__

会调用 get_standard_processors(), 返回一个collect

        collect.extend(_builtin_context_processors)
        collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS)


这个就和TEMPLATE_CONTEXT_PROCESSORS 联系在一起, 得到settings里面的设置.

这个过程只执行一次,当下次再执行的时候,由于

global _standard_context_processors 变量非none.



另外观察RequestContext的__init__

    def __init__(self, request, dict_=None, processors=None, current_app=None,
            use_l10n=None, use_tz=None):

有一个processors参数,我们可以在构造对象的时候,给它n个临时的processor


=================Example================================

Info.xml

<!DOCTYPE html>
<html>
<head>
	About firstDJ
</head>

<body>
	Thanks for watching me, my address is <b>{{myaddress}}</b>, my request is <b>{{myrequest}}</b>...
</body>
</html>


py

def custome_proc(request):
    return {'myaddress': request.META['REMOTE_ADDR']}

def hello(request, *args, **kwargs):
    
    c = RequestContext(request, {
    'myrequest': 'milk',
    },
    processors = [custome_proc])

    t = get_template('info.html')
    return HttpResponse(t.render(c))


结果




转载于:https://www.cnblogs.com/james1207/p/3320127.html

猜你喜欢

转载自blog.csdn.net/weixin_30487701/article/details/94985707