storj.io/minio@v0.0.0-20230509071714-0cbc90f649b1/docs/sts/client_grants/sts_element.py (about) 1 # -*- coding: utf-8 -*- 2 # Licensed under the Apache License, Version 2.0 (the "License"); 3 # you may not use this file except in compliance with the License. 4 # You may obtain a copy of the License at 5 # 6 # http://www.apache.org/licenses/LICENSE-2.0 7 # 8 # Unless required by applicable law or agreed to in writing, software 9 # distributed under the License is distributed on an "AS IS" BASIS, 10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 # See the License for the specific language governing permissions and 12 # limitations under the License. 13 14 from xml.etree import cElementTree 15 from xml.etree.cElementTree import ParseError 16 17 if hasattr(cElementTree, 'ParseError'): 18 _ETREE_EXCEPTIONS = (ParseError, AttributeError, ValueError, TypeError) 19 else: 20 _ETREE_EXCEPTIONS = (SyntaxError, AttributeError, ValueError, TypeError) 21 22 _STS_NS = {'sts': 'https://sts.amazonaws.com/doc/2011-06-15/'} 23 24 25 class STSElement(object): 26 """STS aware XML parsing class. Wraps a root element name and 27 cElementTree.Element instance. Provides STS namespace aware parsing 28 functions. 29 30 """ 31 32 def __init__(self, root_name, element): 33 self.root_name = root_name 34 self.element = element 35 36 @classmethod 37 def fromstring(cls, root_name, data): 38 """Initialize STSElement from name and XML string data. 39 40 :param name: Name for XML data. Used in XML errors. 41 :param data: string data to be parsed. 42 :return: Returns an STSElement. 43 """ 44 try: 45 return cls(root_name, cElementTree.fromstring(data)) 46 except _ETREE_EXCEPTIONS as error: 47 raise InvalidXMLError( 48 '"{}" XML is not parsable. Message: {}'.format( 49 root_name, error.message 50 ) 51 ) 52 53 def findall(self, name): 54 """Similar to ElementTree.Element.findall() 55 56 """ 57 return [ 58 STSElement(self.root_name, elem) 59 for elem in self.element.findall('sts:{}'.format(name), _STS_NS) 60 ] 61 62 def find(self, name): 63 """Similar to ElementTree.Element.find() 64 65 """ 66 elt = self.element.find('sts:{}'.format(name), _STS_NS) 67 return STSElement(self.root_name, elt) if elt is not None else None 68 69 def get_child_text(self, name, strict=True): 70 """Extract text of a child element. If strict, and child element is 71 not present, raises InvalidXMLError and otherwise returns 72 None. 73 74 """ 75 if strict: 76 try: 77 return self.element.find('sts:{}'.format(name), _STS_NS).text 78 except _ETREE_EXCEPTIONS as error: 79 raise InvalidXMLError( 80 ('Invalid XML provided for "{}" - erroring tag <{}>. ' 81 'Message: {}').format(self.root_name, name, error.message) 82 ) 83 else: 84 return self.element.findtext('sts:{}'.format(name), None, _STS_NS) 85 86 def text(self): 87 """Fetch the current node's text 88 89 """ 90 return self.element.text