Package pyxb :: Package namespace :: Module builtin
[hide private]
[frames] | no frames]

Source Code for Module pyxb.namespace.builtin

  1  # Copyright 2009, Peter A. Bigot 
  2  # 
  3  # Licensed under the Apache License, Version 2.0 (the "License"); you may 
  4  # not use this file except in compliance with the License. You may obtain a 
  5  # copy of the License at: 
  6  # 
  7  #            http://www.apache.org/licenses/LICENSE-2.0 
  8  # 
  9  # Unless required by applicable law or agreed to in writing, software 
 10  # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 11  # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 12  # License for the specific language governing permissions and limitations 
 13  # under the License. 
 14   
 15  """Classes and global objects related to built-in U{XML Namespaces<http://www.w3.org/TR/2006/REC-xml-names-20060816/index.html>}.""" 
 16   
 17  import pyxb 
 18   
 19  # A unique identifier for components that are built-in to the PyXB system 
 20  BuiltInObjectUID = pyxb.utils.utility.UniqueIdentifier('PyXB-' + pyxb.__version__ + '-Builtin') 
 21   
 22  from pyxb.namespace import Namespace 
 23   
24 -class _XMLSchema_instance (Namespace):
25 """Extension of L{Namespace} that pre-defines components available in the 26 XMLSchema Instance namespace.""" 27 28 PT_strict = 'strict' 29 """xsi:type is validated and supersedes the declared type. If no xsi:type is 30 present, the declared element type will be used. If xsi:type is 31 present, it must resolve to valid type. The resolved type must be 32 a subclass of the declared type (if available), and will be used 33 for the binding.""" 34 35 PT_lax = 'lax' 36 """xsi:type supersedes the declared type without validation. If 37 no xsi:type is present, or it is present and fails to resolve to a 38 type, the declared element type will be used. If xsi:type is 39 present and resolves to valid type, that type will be used for the 40 binding, even if it is not a subclass of the declared type.""" 41 42 PT_skip = 'skip' 43 """xsi:type attributes are ignored. The declared element type 44 will be used.""" 45 46 __processType = PT_strict 47 48 type = None 49 """An expanded name for {http://www.w3.org/2001/XMLSchema-instance}type.""" 50 51 nil = None 52 """An expanded name for {http://www.w3.org/2001/XMLSchema-instance}nil.""" 53
54 - def __init__ (self, *args, **kw):
55 super(_XMLSchema_instance, self).__init__(*args, **kw) 56 self.type = self.createExpandedName('type') 57 self.nil = self.createExpandedName('nil')
58 59 # NB: Because Namespace instances are singletons, I've made this 60 # is an instance method even though it looks and behaves like a 61 # class method.
62 - def ProcessTypeAttribute (self, value=None):
63 """Specify how PyXB should interpret xsi:type attributes when 64 converting a document to a binding instance. 65 66 The default value is L{PT_strict}. 67 68 xsi:type should only be provided when using an abstract class, 69 or a concrete class that happens to be the same as the 70 xsi:type value, or when accepting a wildcard that has an 71 unrecognized element name. In practice, web services tend to 72 set it on nodes just to inform their lax-processing clients 73 how to interpret the value. 74 75 @param value: One of L{PT_strict}, L{PT_lax}, L{PT_skip}, or C{None} (no change) 76 @return: The current configuration for processing xsi:type attributes 77 """ 78 79 if value in (self.PT_strict, self.PT_lax, self.PT_skip): 80 self.__processType = value 81 elif value is not None: 82 raise pyxb.ValueError(value) 83 return self.__processType
84
85 - def _InterpretTypeAttribute (self, type_name, ns_ctx, fallback_namespace, type_class):
86 """Interpret the value of an xsi:type attribute as configured. 87 88 @param type_name: The QName value from the attribute 89 @param ns_ctx: The NamespaceContext within which the type_name should be resolved 90 @param fallback_namespace: The namespace that should be used if the type name has no prefix 91 @param type_class: The value to return if the type name is missing or acceptably invalid 92 @raises L{pyxb.BadDocumentError}: if the processing type 93 configuration is L{PT_strict} and the type name fails to 94 resolve to a type definition that is consistent with any 95 provided type_class. 96 """ 97 did_replace = False 98 if type_name is None: 99 return (did_replace, type_class) 100 pt = self.__processType 101 if self.PT_skip == pt: 102 return (did_replace, type_class) 103 type_en = ns_ctx.interpretQName(type_name, namespace=fallback_namespace) 104 try: 105 alternative_type_class = type_en.typeBinding() 106 except KeyError, e: 107 alternative_type_class = None 108 if self.PT_strict == pt: 109 if alternative_type_class is None: 110 raise pyxb.BadDocumentError('No type binding for %s' % (type_name,)) 111 if (type_class is not None) and (not (type_class._IsUrType() or issubclass(alternative_type_class, type_class))): 112 raise pyxb.BadDocumentError('%s value %s is not subclass of element type %s' % (type_name, type_en, type_class._ExpandedName)) 113 if (self.PT_strict == pt) or ((self.PT_lax == pt) and (alternative_type_class is not None)): 114 type_class = alternative_type_class 115 did_replace = True 116 return (did_replace, type_class)
117
118 - def _defineBuiltins_ox (self, structures_module):
119 """Ensure this namespace is ready for use. 120 121 Overrides base class implementation, since there is no schema 122 for this namespace. """ 123 124 assert structures_module is not None 125 schema = structures_module.Schema(namespace_context=self.initialNamespaceContext(), schema_location="URN:noLocation:PyXB:xsi", generation_uid=BuiltInObjectUID, _bypass_preload=True) 126 type = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('type', schema)) 127 nil = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('nil', schema)) 128 schema_location = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('schemaLocation', schema)) 129 no_namespace_schema_location = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('noNamespaceSchemaLocation', schema)) 130 return self
131
132 -class _XML (Namespace):
133 """Extension of L{Namespace} that pre-defines components available in the 134 XML (xml) namespace. Specifically those are the attribute declarations: 135 136 - C{xml:space} 137 - C{xml:lang} 138 - C{xml:base} 139 - C{xml:id} 140 141 the encompassing attribute group declaration: 142 143 - C{xml:specialAttrs} 144 145 and the anonymous types that support these.""" 146
147 - def _defineBuiltins_ox (self, structures_module):
148 """Ensure this namespace is ready for use. 149 150 Overrides base class implementation, since there is no schema 151 for this namespace. """ 152 153 assert structures_module is not None 154 import pyxb.binding.datatypes as xsd 155 import pyxb.binding.facets as xsdf 156 import archive 157 158 self.configureCategories([archive.NamespaceArchive._AnonymousCategory()]) 159 160 schema = structures_module.Schema(namespace_context=self.initialNamespaceContext(), schema_location="URN:noLocation:PyXB:XML", generation_uid=BuiltInObjectUID, _bypass_preload=True) 161 162 std_space = structures_module.SimpleTypeDefinition._CreateXMLInstance('space', schema) 163 std_space._setAnonymousName(self, anon_name='STD_ANON_space') 164 std_space._setBindingNamespace(self) 165 std_lang = structures_module.SimpleTypeDefinition._CreateXMLInstance('lang', schema) 166 std_lang._setAnonymousName(self, anon_name='STD_ANON_lang') 167 std_lang._setBindingNamespace(self) 168 169 base = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('base', schema, std=xsd.anyURI.SimpleTypeDefinition())) 170 id = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('id', schema, std=xsd.ID.SimpleTypeDefinition())) 171 space = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('space', schema, std=std_space)) 172 lang = schema._addNamedComponent(structures_module.AttributeDeclaration.CreateBaseInstance('lang', schema, std=std_lang)) 173 174 specialAttrs = schema._addNamedComponent(structures_module.AttributeGroupDefinition.CreateBaseInstance('specialAttrs', schema, [ 175 structures_module.AttributeUse.CreateBaseInstance(schema, space), 176 structures_module.AttributeUse.CreateBaseInstance(schema, base), 177 structures_module.AttributeUse.CreateBaseInstance(schema, lang), 178 structures_module.AttributeUse.CreateBaseInstance(schema, id), 179 ])) 180 181 return self
182
183 -class _XMLSchema (Namespace):
184 """Extension of L{Namespace} that pre-defines components available in the 185 XMLSchema namespace. 186 187 The types are defined when L{pyxb.xmlschema.structures} is imported. 188 """ 189
190 - def _defineBuiltins_ox (self, structures_module):
191 """Register the built-in types into the XMLSchema namespace.""" 192 193 # Defer the definitions to the structures module 194 assert structures_module is not None 195 structures_module._AddSimpleTypes(self) 196 197 # A little validation here 198 assert structures_module.ComplexTypeDefinition.UrTypeDefinition() == self.typeDefinitions()['anyType'] 199 assert structures_module.SimpleTypeDefinition.SimpleUrTypeDefinition() == self.typeDefinitions()['anySimpleType'] 200 201 # Provide access to the binding classes 202 self.configureCategories(['typeBinding', 'elementBinding']) 203 for ( en, td ) in self.typeDefinitions().items(): 204 if td.pythonSupport() is not None: 205 self.addCategoryObject('typeBinding', en, td.pythonSupport())
206 207 XMLSchema_instance = _XMLSchema_instance('http://www.w3.org/2001/XMLSchema-instance', 208 description='XML Schema Instance', 209 builtin_namespace='XMLSchema_instance') 210 """Namespace and URI for the XMLSchema Instance namespace. This is always 211 built-in, and does not (cannot) have an associated schema.""" 212 213 XMLNamespaces = Namespace('http://www.w3.org/2000/xmlns/', 214 description='Namespaces in XML', 215 builtin_namespace='XMLNamespaces', 216 bound_prefix='xmlns') 217 """Namespaces in XML. Not really a namespace, but is always available as C{xmlns}.""" 218 219 # http://www.w3.org/2001/XMLSchema.xsd 220 XMLSchema = _XMLSchema('http://www.w3.org/2001/XMLSchema', 221 description='XML Schema', 222 builtin_namespace='XMLSchema', 223 builtin_module_path='pyxb.binding.datatypes', 224 in_scope_namespaces = { 'xs' : None }) 225 """Namespace and URI for the XMLSchema namespace (often C{xs}, or C{xsd})""" 226 227 # http://www.w3.org/1999/xhtml.xsd 228 XHTML = Namespace('http://www.w3.org/1999/xhtml', 229 description='Family of document types that extend HTML', 230 builtin_namespace='XHTML', 231 default_namespace=XMLSchema) 232 """There really isn't a schema for this, but it's used as the default 233 namespace in the XML schema, so define it.""" 234 235 # http://www.w3.org/2001/xml.xsd 236 XML = _XML('http://www.w3.org/XML/1998/namespace', 237 description='XML namespace', 238 builtin_namespace='XML', 239 builtin_module_path='pyxb.binding.xml_', 240 is_undeclared_namespace=True, 241 bound_prefix='xml', 242 default_namespace=XHTML, 243 in_scope_namespaces = { 'xs' : XMLSchema }) 244 """Namespace and URI for XML itself (always available as C{xml})""" 245 246 # http://www.w3.org/2001/XMLSchema-hasFacetAndProperty 247 XMLSchema_hfp = Namespace('http://www.w3.org/2001/XMLSchema-hasFacetAndProperty', 248 description='Facets appearing in appinfo section', 249 builtin_namespace='XMLSchema_hfp', 250 default_namespace=XMLSchema, 251 in_scope_namespaces = { 'hfp' : None 252 , 'xhtml' : XHTML }) 253 """Elements appearing in appinfo elements to support data types.""" 254 255 # List of built-in namespaces. 256 BuiltInNamespaces = [ 257 XMLSchema_instance, 258 XMLSchema_hfp, 259 XMLSchema, 260 XMLNamespaces, 261 XML, 262 XHTML 263 ] 264 265 __InitializedBuiltinNamespaces = False 266
267 -def _InitializeBuiltinNamespaces (structures_module):
268 """Invoked at the end of the L{pyxb.xmlschema.structures} module to 269 initialize the component models of the built-in namespaces. 270 271 @param structures_module: The L{pyxb.xmlschema.structures} module may not 272 be importable by that name at the time this is invoked (because it is 273 still being processed), so it gets passed in as a parameter.""" 274 global __InitializedBuiltinNamespaces 275 if not __InitializedBuiltinNamespaces: 276 __InitializedBuiltinNamespaces = True 277 [ _ns._defineBuiltins(structures_module) for _ns in BuiltInNamespaces ]
278 279 # Set up the prefixes for xml, xmlns, etc. 280 _UndeclaredNamespaceMap = { } 281 [ _UndeclaredNamespaceMap.setdefault(_ns.boundPrefix(), _ns) for _ns in BuiltInNamespaces if _ns.isUndeclaredNamespace() ] 282