Package suds :: Package sax :: Module enc
[hide private]
[frames] | no frames]

Source Code for Module suds.sax.enc

 1  # This program is free software; you can redistribute it and/or modify 
 2  # it under the terms of the (LGPL) GNU Lesser General Public License as 
 3  # published by the Free Software Foundation; either version 3 of the  
 4  # License, or (at your option) any later version. 
 5  # 
 6  # This program is distributed in the hope that it will be useful, 
 7  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 8  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 9  # GNU Library Lesser General Public License for more details at 
10  # ( http://www.gnu.org/licenses/lgpl.html ). 
11  # 
12  # You should have received a copy of the GNU Lesser General Public License 
13  # along with this program; if not, write to the Free Software 
14  # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
15  # written by: Jeff Ortel ( jortel@redhat.com ) 
16   
17  """ 
18  Provides XML I{special character} encoder classes. 
19  """ 
20   
21  import re 
22   
23 -class Encoder:
24 """ 25 An XML special character encoder/decoder. 26 @cvar encodings: A mapping of special characters encoding. 27 @type encodings: [(str,str)] 28 @cvar decodings: A mapping of special characters decoding. 29 @type decodings: [(str,str)] 30 @cvar special: A list of special characters 31 @type special: [char] 32 """ 33 34 encodings = \ 35 (( '&(?!(amp|lt|gt|quot|apos);)', '&amp;' ),( '<', '&lt;' ),( '>', '&gt;' ),( '"', '&quot;' ),("'", '&apos;' )) 36 decodings = \ 37 (( '&lt;', '<' ),( '&gt;', '>' ),( '&quot;', '"' ),( '&apos;', "'" ),( '&amp;', '&' )) 38 special = \ 39 ('&', '<', '>', '"', "'") 40
41 - def needsEncoding(self, s):
42 """ 43 Get whether string I{s} contains special characters. 44 @param s: A string to check. 45 @type s: str 46 @return: True if needs encoding. 47 @rtype: boolean 48 """ 49 if isinstance(s, basestring): 50 for c in self.special: 51 if c in s: 52 return True 53 return False
54
55 - def encode(self, s):
56 """ 57 Encode special characters found in string I{s}. 58 @param s: A string to encode. 59 @type s: str 60 @return: The encoded string. 61 @rtype: str 62 """ 63 if isinstance(s, basestring) and self.needsEncoding(s): 64 for x in self.encodings: 65 s = re.sub(x[0], x[1], s) 66 return s
67
68 - def decode(self, s):
69 """ 70 Decode special characters encodings found in string I{s}. 71 @param s: A string to decode. 72 @type s: str 73 @return: The decoded string. 74 @rtype: str 75 """ 76 if isinstance(s, basestring) and '&' in s: 77 for x in self.decodings: 78 s = s.replace(x[0], x[1]) 79 return s
80