Package pyxb
[hide private]
[frames] | no frames]

Source Code for Package pyxb

  1  """PyXB stands for Python U{W3C XML 
  2  Schema<http://www.w3.org/XML/Schema>} Bindings, and is pronounced 
  3  "pixbee".  It enables translation between XML instance documents and 
  4  Python objects following rules specified by an XML Schema document. 
  5   
  6  This is the top-level entrypoint to the PyXB system.  Importing this 
  7  gets you all the L{exceptions<pyxb.exceptions_.PyXBException>}, and 
  8  L{pyxb.namespace}.  For more functionality, delve into these 
  9  submodules: 
 10   
 11   - L{pyxb.xmlschema} Module holding the 
 12     L{structures<pyxb.xmlschema.structures>} that convert XMLSchema 
 13     from a DOM model to a Python class model based on the XMLSchema 
 14     components.  Use this when you need to operate on the component 
 15     model. 
 16   
 17   - L{pyxb.binding} Module used to generate the bindings and at runtime 
 18     to support the generated bindings.  Use this if you need to use the 
 19     binding model or content model. 
 20   
 21   - L{pyxb.utils} Common utilities used in parsing, generating, and 
 22     executing.  The submodules must be imported separately. 
 23   
 24  """ 
 25   
26 -class cscRoot (object):
27 """This little bundle of joy exists because in Python 2.6 it 28 became an error to invoke C{object.__init__} with parameters (unless 29 you also override C{__new__}, in which case it's only a warning. 30 Whatever.). Since I'm bloody not going to check in every class 31 whether C{super(Myclass,self)} refers to C{object} (even if I could 32 figure out how to do that, 'cuz the obvious solutions don't work), 33 we'll just make this thing the root of all U{cooperative super 34 calling<http://www.geocities.com/foetsch/python/new_style_classes.htm#super>} 35 hierarchies. The standard syntax in PyXB for this pattern is:: 36 37 def method_csc (self, *args, **kw): 38 super_fn = getattr(super(ThisClass, self), 'method_csc', lambda *a,**kw: self) 39 return super_fn(*args, **kw) 40 41 """ 42
43 - def __init__ (self, *args, **kw):
44 # Oh gross. If this class descends from list (and probably dict), we 45 # get here when object is *not* our direct superclass. In that case, 46 # we have to pass the arguments on up, or the strings don't get 47 # created right. Below is the only way I've figured out to detect the 48 # situation. 49 # 50 # Note that we might also get here if you mix-in a class that used 51 # object as a parent instead of cscRoot. Don't do that. Printing the 52 # mro() is a decent way of identifying the problem. 53 if issubclass(self.__class__.mro()[-2], ( list, dict )): 54 super(cscRoot, self).__init__(*args)
55 56 __version__ = '1.1.4' 57 """The version of PyXB""" 58 59 __url__ = 'http://pyxb.sourceforge.net' 60 """The URL for PyXB's homepage""" 61 62 __license__ = 'Apache License 2.0' 63 64 # Bring in the exception hierarchy 65 from exceptions_ import * 66 67 # Bring in namespace stuff 68 import namespace 69
70 -class BIND (object):
71 """Bundle data for automated binding generation. 72 73 Instances of this class capture positional and keyword arguments that are 74 used to create binding instances based on context. For example, if C{w} 75 is an instance of a complex type whose C{option} element is declared to be 76 an anonymous class with simple content of type integer and an attribute of 77 C{units}, a correct assignment to that element could be achieved with:: 78 79 w.option = BIND(54, units="m") 80 81 """ 82 __args = None 83 __kw = None 84
85 - def __init__ (self, *args, **kw):
86 """Cache parameters for subsequent binding creation. 87 Invoke just as you would the factory for a binding class.""" 88 self.__args = args 89 self.__kw = kw
90
91 - def createInstance (self, factory, **kw):
92 """Invoke the given factory method. 93 94 Position arguments to the factory are those cached in this instance. 95 Keyword arguments are the ones on the command line, updated from the 96 ones in this instance.""" 97 kw.update(self.__kw) 98 return factory(*self.__args, **kw)
99 100 101 XMLStyle_minidom = 0 102 """Use xml.dom.minidom for XML processing. This is the fastest, but does not 103 provide location information. It produces DOM instances.""" 104 105 XMLStyle_saxdom = 1 106 """Use pyxb.utils.saxdom for XML processing. This is the slowest, but both 107 provides location information and generates a DOM instance.""" 108 109 XMLStyle_saxer = 2 110 """Use pyxb.binding.saxer when converting documents to binding instances. 111 This style supports location information in the bindings. It produces binding 112 instances directly, without going through a DOM stage, so is faster than 113 XMLStyle_saxdom. However, since the pyxb.xmlschema.structures classes require 114 a DOM model, XMLStyle_saxdom will be used for pyxb.utils.domutils.StringToDOM 115 if this style is selected.""" 116 117 _XMLStyle = XMLStyle_saxer 118 """The current XML processing style.""" 119 120 _XMLStyleMap = { 'minidom' : XMLStyle_minidom, 121 'saxdom' : XMLStyle_saxdom, 122 'saxer' : XMLStyle_saxer } 123 _XMLStyleMapReverse = dict([ (_v, _k) for (_k, _v) in _XMLStyleMap.items() ]) 124 125 _XMLStyle_envvar = 'PYXB_XML_STYLE' 126
127 -def _SetXMLStyle (style=None):
128 """Set the interface used to parse XML content. 129 130 This can be invoked within code. The system default of L{XMLStyle_saxer} 131 can also be overridden at runtime by setting the environment variable 132 C{PYXB_XML_STYLE} to one of C{minidom}, C{saxdom}, or C{saxer}. 133 134 @param style: One of L{XMLStyle_minidom}, L{XMLStyle_saxdom}, 135 L{XMLStyle_saxer}. If not provided, the system default is used. 136 """ 137 global _XMLStyle 138 if style is None: 139 import os 140 style_name = os.environ.get(_XMLStyle_envvar) 141 if style_name is None: 142 style_name = 'saxer' 143 style = _XMLStyleMap.get(style_name) 144 if style is None: 145 raise PyXBException('Bad value "%s" for %s' % (style_name, _XMLStyle_envvar)) 146 if _XMLStyleMapReverse.get(style) is None: 147 raise PyXBException('Bad value %s for _SetXMLStyle' % (style,)) 148 _XMLStyle = style
149 #print "XML style %s" % (_XMLStyleMapReverse.get(_XMLStyle),) 150 151 _SetXMLStyle() 152 153 # Global flag that we can use to determine whether optimization is active in 154 # this session. There may be cases where we can bypass methods that just 155 # check for things we don't care about in an optimized context 156 _OptimizationActive = False 157 try: 158 assert False 159 _OptimizationActive = True 160 except: 161 pass 162 163 _CorruptionDetectionEnabled = not _OptimizationActive 164 """If C{True}, blocks attempts to assign to attributes that are reserved for 165 PyXB methods. 166 167 Applies only at compilation time; dynamic changes are ignored. 168 """ 169 170 _GenerationRequiresValid = True
171 -def RequireValidWhenGenerating (value=None):
172 """Query or set a flag that controls validation checking in XML generation. 173 174 Normally any attempts to convert a binding instance to a DOM or XML 175 representation requires that the binding validate against the content 176 model, since only in this way can the content be generated in the correct 177 order. In some cases it may be necessary or useful to generate a document 178 from a binding that is incomplete. If validation is not required, the 179 generated documents may not validate even if the content validates, 180 because ordering constraints will be ignored. 181 182 @keyword value: If absent or C{None}, no change is made; otherwise, this 183 enables (C{True}) or disables (C{False}) the requirement that instances 184 validate before being converted to XML. 185 @type value: C{bool} 186 187 @return: C{True} iff attempts to generate XML for a binding that does not 188 validate should raise an exception. """ 189 global _GenerationRequiresValid 190 if value is None: 191 return _GenerationRequiresValid 192 if not isinstance(value, bool): 193 raise TypeError(value) 194 _GenerationRequiresValid = value 195 return _GenerationRequiresValid
196 197 _ParsingRequiresValid = True
198 -def RequireValidWhenParsing (value=None):
199 """Query or set a flag that controls validation checking in XML parsing. 200 201 Normally any attempts to convert XML to a binding instance to a binding 202 instance requires that the document validate against the content model. 203 In some cases it may be necessary or useful to process a document that is 204 incomplete. If validation is not required, the generated documents may 205 not validate even if the content validates, because ordering constraints 206 will be ignored. 207 208 @keyword value: If absent or C{None}, no change is made; otherwise, this 209 enables (C{True}) or disables (C{False}) the requirement that documents 210 validate when being converted to bindings. 211 @type value: C{bool} 212 213 @return: C{True} iff attempts to generate bindings for a document that 214 does not validate should raise an exception.""" 215 global _ParsingRequiresValid 216 if value is None: 217 return _ParsingRequiresValid 218 if not isinstance(value, bool): 219 raise TypeError(value) 220 _ParsingRequiresValid = value 221 return _ParsingRequiresValid
222 223 _PreserveInputTimeZone = False
224 -def PreserveInputTimeZone (value=None):
225 """Control whether time values are converted to UTC during input. 226 227 The U{specification <http://www.w3.org/TR/xmlschema-2/#dateTime>} makes 228 clear that timezoned times are in UTC and that times in other timezones 229 are to be translated to UTC when converted from literal to value form. 230 Provide an option to bypass this step, so the input timezone is preserved. 231 232 @note: Naive processing of unnormalized times--i.e., ignoring the 233 C{tzinfo} field--may result in errors.""" 234 global _PreserveInputTimeZone 235 if value is None: 236 return _PreserveInputTimeZone 237 if not isinstance(value, bool): 238 raise TypeError(value) 239 _PreserveInputTimeZone = value 240 return _PreserveInputTimeZone
241 242 _OutputEncoding = 'utf-8' 243 """Default unicode encoding to use when creating output. 244 245 Material being written to an XML parser is not output.""" 246 247 _InputEncoding = 'utf-8' 248 """Default unicode encoding to assume when decoding input. 249 250 Material being written to an XML parser is treated as input.""" 251 252 ## Local Variables: 253 ## fill-column:78 254 ## End: 255