"""Functions for working with "safe strings": strings that can be displayed safelywithout further escaping in HTML. Marking something as a "safe string" meansthat the producer of the string has already turned characters that should notbe interpreted by the HTML engine (e.g. '<') into the appropriate entities."""fromfunctoolsimportwrapsfromgingerdj.utils.functionalimportkeep_lazyclassSafeData:__slots__=()def__html__(self):""" Return the html representation of a string for interoperability. This allows other template engines to understand GingerDJ's SafeData. """returnself
[docs]classSafeString(str,SafeData):""" A str subclass that has been specifically marked as "safe" for HTML output purposes. """__slots__=()def__add__(self,rhs):""" Concatenating a safe string with another safe bytestring or safe string is safe. Otherwise, the result is no longer safe. """t=super().__add__(rhs)ifisinstance(rhs,SafeData):returnSafeString(t)returntdef__str__(self):returnself
SafeText=SafeString# For backwards compatibility since GingerDJ 2.0.def_safety_decorator(safety_marker,func):@wraps(func)defwrapper(*args,**kwargs):returnsafety_marker(func(*args,**kwargs))returnwrapper
[docs]@keep_lazy(SafeString)defmark_safe(s):""" Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate. If used on a method as a decorator, mark the returned data as safe. Can be called multiple times on a single string. """ifhasattr(s,"__html__"):returnsifcallable(s):return_safety_decorator(mark_safe,s)returnSafeString(s)