Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use is_safe?

Tags:

python

django

I'm reading Django documentation on custom filter.

and.. I don't see the reason of the existence of is_safe. https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping

when I coded some examples and then tried them, the result were always same whether is_safe is True or False.

Why do you use is_safe?

Here is my code

extra_tags.py

from django.template.defaultfilters import stringfilter
from django import template
import datetime
register = template.Library()

@register.filter(name='custom_lower')        
@stringfilter
def lower(value):
    is_safe = True
    return '%sxx'%value
lower.is_safe = True;

from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe

@register.filter(name='custom_lf')
def initial_letter_filter(text, autoescape=None):
    first, other = text[0], text[1:]
    if autoescape:
        esc = conditional_escape
    else:
        esc = lambda x: x
    result = '<strong>%s</strong>%s' % (esc(first), esc(other))
    return mark_safe(result)
initial_letter_filter.is_safe = False
initial_letter_filter.needs_autoescape = True

my point is that whether I code is_safe=True or is_safe=False, the result will be auto-escaped characters.. and I don't see why we use is_safe.

like image 973
Anderson Avatar asked Dec 22 '22 08:12

Anderson


1 Answers

Using is_safe together with mark_safe() is redundant, which is probably why you don't see any differences.

As noted in the section you linked to, down where it talks about mark_safe():

There's no need to worry about the is_safe attribute in this case (although including it wouldn't hurt anything). Whenever you manually handle the auto-escaping issues and return a safe string, the is_safe attribute won't change anything either way.

is_safe is simply a way to automatically mark the return value of a function as safe, given that all of the external inputs were already safe. Django will still autoescape anything that was an input, but it won't try to escape the other parts which were added afterwards by your function.

mark_safe(), on the other hand, certifies that the output is safe regardless of whether the inputs were safe - it's a much stronger requirement that you have to fulfill if you're going to use it.

like image 144
Amber Avatar answered Dec 31 '22 21:12

Amber