Django模版系统中方法调用的注意事项

Method Call Behavior

Method calls are slightly more complex than the other lookup types. Here are some things to keep in mind:

  • If, during the method lookup, a method raises an exception, the exception will be propagated, unless the exception has an attribute silent_variable_failure whose value is True. If the exception does have asilent_variable_failure attribute, the variable will render as an empty string, for example:

    >>> t = Template("My name is {{ person.first_name }}.")
    >>> class PersonClass3:
    ...     def first_name(self):
    ...         raise AssertionError, "foo"
    >>> p = PersonClass3()
    >>> t.render(Context({"person": p}))
    Traceback (most recent call last):
    ...
    AssertionError: foo
    
    >>> class SilentAssertionError(AssertionError):
    ...     silent_variable_failure = True
    >>> class PersonClass4:
    ...     def first_name(self):
    ...         raise SilentAssertionError
    >>> p = PersonClass4()
    >>> t.render(Context({"person": p}))
    u'My name is .'
    
  • A method call will only work if the method has no required arguments. Otherwise, the system will move to the next lookup type (list-index lookup).

  • Obviously, some methods have side effects, and it would be foolish at best, and possibly even a security hole, to allow the template system to access them.

    Say, for instance, you have a BankAccount object that has a delete() method. If a template includes something like {{ account.delete }}, where account is a BankAccount object, the object would be deleted when the template is rendered!

    To prevent this, set the function attribute alters_data on the method:

    def delete(self):
        # Delete the account
    delete.alters_data = True

    The template system won’t execute any method marked in this way. Continuing the above example, if a template includes {{ account.delete }} and the delete() method has the alters_data=True, then thedelete() method will not be executed when the template is rendered. Instead, it will fail silently.




    上面是Django文档关于模版系统中方法调用的一部分内容。意思就是说,

    在方法调用期间,如果被调用的方法发

    起一个异常,如果此时这个异常

    silent_variable_failure这个属性,并且值为true,那么此时这个发生的异常不会传播,

    并且在字符串中会被空字符串代替。如果属性值没有,那么就会

    传播这个异常。在模板系统 中调用方法,这个方法必须是不接受任何参数的,否则这个方法不会被调用,

    会按照点号引用的查找规则

    进行下一项的查找。


    另外,加入你现在有一个BlankAccount的类,这个类有一个account的对象,有一个delete的方法。

    加入你在模板系统的变量里面

    有{{account.delete}}这样的点号调用的话,会造成一些意想不到的问题。

    模板中的account.delete和account对象调用delete不是一个意思,

    这样的话就会出现了代码重复的情况。

    所以Django会删除account这个对象,这样就造成 了不必要的麻烦。

    给方法设置alters_data这个属性,在发生这种情况的时候,

    程序不会调用任何方法,只是默默的退出。

    要知道在Django模板系统中很多时候,

    如果你用点号引用了一下不存在的变量或者方法,让系统深度查找不到的话,

    那么他就会在那里用空字符串代替,虽然没有引发明显的异常,但是

    这就已经代表 有错误了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值