<s> from django . db . models import get_model <EOL> from django . utils . translation import ugettext <EOL> def encode_object ( obj , name = None ) : <EOL> encoded = "<STR_LIT>" % ( obj . _meta . app_label , obj . _meta . object_name , obj . pk ) <EOL> if name : <EOL> encoded = "<STR_LIT>" % ( encoded , name ) <EOL> return "<STR_LIT>" % encoded <EOL> def encode_message ( message_template , objects ) : <EOL> if objects is None : <EOL> return message_template <EOL> if isinstance ( objects , list ) or isinstance ( objects , tuple ) : <EOL> return message_template % tuple ( encode_object ( obj ) for obj in objects ) <EOL> if type ( objects ) is dict : <EOL> return message_template % dict ( ( name , encode_object ( obj , name ) ) for name , obj in objects . iteritems ( ) ) <EOL> return "<STR_LIT>" <EOL> def decode_object ( ref ) : <EOL> decoded = ref . split ( "<STR_LIT:.>" ) <EOL> if len ( decoded ) == <NUM_LIT:4> : <EOL> app , name , pk , msgid = decoded <EOL> return get_model ( app , name ) . objects . get ( pk = pk ) , msgid <EOL> app , name , pk = decoded <EOL> return get_model ( app , name ) . objects . get ( pk = pk ) , None <EOL> class FormatException ( Exception ) : <EOL> pass <EOL> def decode_message ( message , decoder ) : <EOL> out = [ ] <EOL> objects = [ ] <EOL> mapping = { } <EOL> in_field = False <EOL> prev = <NUM_LIT:0> <EOL> for index , ch in enumerate ( message ) : <EOL> if not in_field : <EOL> if ch == "<STR_LIT:{>" : <EOL> in_field = True <EOL> if prev != index : <EOL> out . append ( message [ prev : index ] ) <EOL> prev = index <EOL> elif ch == "<STR_LIT:}>" : <EOL> raise FormatException ( "<STR_LIT>" ) <EOL> elif in_field : <EOL> if ch == "<STR_LIT:{>" : <EOL> raise FormatException ( "<STR_LIT>" ) <EOL> elif ch == "<STR_LIT:}>" : <EOL> in_field = False <EOL> obj , msgid = decoder ( message [ prev + <NUM_LIT:1> : index ] ) <EOL> if msgid is None : <EOL> objects . append ( obj ) <EOL> out . append ( "<STR_LIT:%s>" ) <EOL> else : <EOL> mapping [ msgid ] = obj <EOL> out . append ( "<STR_LIT>" + msgid + "<STR_LIT>" ) <EOL> prev = index + <NUM_LIT:1> <EOL> if in_field : <EOL> raise FormatException ( "<STR_LIT>" ) <EOL> if prev <= index : <EOL> out . append ( message [ prev : index + <NUM_LIT:1> ] ) <EOL> result = "<STR_LIT>" . join ( out ) <EOL> if mapping : <EOL> args = mapping <EOL> else : <EOL> args = tuple ( objects ) <EOL> return ugettext ( result ) % args <EOL> def message_to_text ( message ) : <EOL> def decoder ( ref ) : <EOL> obj , msgid = decode_object ( ref ) <EOL> return unicode ( obj ) , msgid <EOL> return decode_message ( message , decoder ) <EOL> def message_to_html ( message ) : <EOL> def decoder ( ref ) : <EOL> obj , msgid = decode_object ( ref ) <EOL> if hasattr ( obj , "<STR_LIT>" ) : <EOL> return u"""<STR_LIT>""" % ( obj . get_absolute_url ( ) , unicode ( obj ) ) , msgid <EOL> else : <EOL> return unicode ( obj ) , msgid <EOL> return decode_message ( message , decoder ) </s>
