def encryptMessage(self, env, use_encrypted_header=False, second_pass=False): encrypted_parts = second_pass and self.second_pass_encrypted_parts or self.encrypted_parts elements_to_encrypt = [] encrypted_headers = [] for elements_to_encrypt_func in encrypted_parts: addl_elements = elements_to_encrypt_func(env) if addl_elements[0] is None: continue if not isinstance(addl_elements[0], list): addl_elements = ([addl_elements[0]], addl_elements[1]) for element in addl_elements[0]: if element not in elements_to_encrypt: if element[0].parent.match("Header") and use_encrypted_header: enc_hdr = Element("EncryptedHeader", ns=wsse11ns) element[0].parent.replaceChild(element[0], enc_hdr) enc_hdr.append(element[0]) elements_to_encrypt.append((enc_hdr, "Content")) encrypted_headers.append(enc_hdr) else: elements_to_encrypt.append((element, addl_elements[1])) ref_list = xmlsec.encryptMessage( self.cert, self.symmetricKey, elements_to_encrypt, "#" + self.keyId, self.keyReference, self.keyTransport ) for enc_hdr in encrypted_headers: enc_hdr.set("wsu:Id", enc_hdr[0].get("Id")) enc_hdr[0].unset("Id") if self.includeRefList: self.encryptedKey.append(ref_list) return self.encryptedKey else: return (self.encryptedKey, ref_list)
def marshalled(self, context): userid = self.userid timestamp = rfc3339(datetime.datetime.now()) secret = self.secret signature = sign(secret, timestamp+userid) auth = self.authfragment % locals() envelope = context.envelope #Set the right ns prefixes envelope.nsprefixes[ 'ns1' ] = envelope.nsprefixes[ 'ns0' ] envelope.clearPrefix( 'ns0' ) #Add our auth to the header element header = envelope.getChild('Header') authns = Element( 'ns1:AuthenticationHeader' ) authns.append( Element( 'mktowsUserId' ).setText(self.userid) ) authns.append( Element( 'requestSignature' ).setText(signature) ) authns.append( Element( 'requestTimestamp' ).setText(timestamp) ) header.append( authns ) #Set the proper body prefixes body = envelope.getChild( 'Body' ) body.prefix = 'SOAP-ENV' body.children[0].prefix = 'ns1' if self.debug: with open("/tmp/envelope.txt","w") as f: f.write(envelope.str())
def init_client(faults=True): ENTREPRISE_WSDL = getattr(settings, 'SALESFORCE_ENTERPRISE_WSDL') DJANGO_WSDL = getattr(settings, 'SALESFORCE_DJANGO_WSDL') SALESFORCE_ENDPOINT = getattr(settings, 'SALESFORCE_ENDPOINT') SALESFORCE_USER = getattr(settings, 'SALESFORCE_USER') SALESFORCE_PASS = getattr(settings, 'SALESFORCE_PASS') SALESFORCE_TOKEN = getattr(settings, 'SALESFORCE_TOKEN') # Use the entreprise login to get a session id entreprise_client = Client(ENTREPRISE_WSDL) #entreprise_client.wsdl.url = SALESFORCE_ENDPOINT login_result = entreprise_client.service.login(SALESFORCE_USER, SALESFORCE_PASS+SALESFORCE_TOKEN) # our client specific methods are in this specific # NOTE we have to create the endpoint url using values from the serverUrl in the loginResponse plus # the djangoAdapter schema options = urlparse(login_result.serverUrl) #DJANGO_SF_ENDPOINT = '%s://%s/services/Soap/class/dJangoAdapter' % (options.scheme, options.netloc) django_client = Client(DJANGO_WSDL, location = SALESFORCE_ENDPOINT, faults=faults) session_name_space = ('djan', 'http://soap.sforce.com/schemas/class/dJangoAdapter') session = Element('sessionId').setText(login_result.sessionId) wrapper = Element('SessionHeader') wrapper.append(session) django_client.set_options(soapheaders=wrapper) return django_client
def main(self): items = self.adsm_lists.service.GetListItems(self.args.list, self.args.view).listitems.data.row method_idx = 1 batch = Element('Batch')\ .append(Attribute('OnError', 'Continue'))\ .append(Attribute('ListVersion', 1)) def update(b): if not self.args.d: updates = Element('ns1:updates').append(b) print self.adsm_lists.service.UpdateListItems(listName=self.args.list, updates=updates) for item in items: method = Element('Method')\ .append(Attribute('ID', method_idx))\ .append(Attribute('Cmd', 'Delete'))\ .append(Element('Field')\ .append(Attribute('Name', 'ID'))\ .setText(item['_ows_ID'])) batch.append(method) print method method_idx += 1 if len(batch) > 20: update(batch) batch.detachChildren() if len(batch) > 0: update(batch)
def _ensure_service(self): """Trying to add service if no one definied explicitly. EWS workaround.""" if (self.services or not self.bindings or len(self.bindings) > 1 or not self.bindings.keys()[0][0].startswith('Exchange')): return service = Element('service') service.set('name', 'ExchangeServices') port = Element('port', service) port.set('name', 'ExchangeServicePort') port.set('binding', self.bindings.keys()[0][0]) address = Element('address', port) address.set('location', urljoin(self.url, 'exchange.asmx')) port.append(address) service.append(port) service = Factory.create(service, self) service.resolve(self) self.children.append(service) self.services.append(service) log.debug('Auto created service: %s', service)
def xml(self): root = Element("Timestamp", ns=wsuns) created = Element('Created', ns=wsuns) created.setText(str(DateTime(self.created))) expires = Element('Expires', ns=wsuns) expires.setText(str(DateTime(self.expires))) root.append(created) root.append(expires) return root
def xml(self): root = Element("Timestamp", ns=wsuns) # xsd:datetime format does not have fractional seconds created = Element("Created", ns=wsuns) created.setText(str(UTC(self.created - timedelta(microseconds=self.created.microsecond)))) expires = Element("Expires", ns=wsuns) expires.setText(str(UTC(self.expires - timedelta(microseconds=self.expires.microsecond)))) root.append(created) root.append(expires) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Security', ns=wssens) root.set('mustUnderstand', str(self.mustUnderstand).lower()) for t in self.tokens: root.append(t.xml()) return root
def header(self, content): """ Build the B{<Body/>} for an soap outbound message. @param content: The header content. @type content: L{Element} @return: the soap body fragment. @rtype: L{Element} """ header = Element('Header', ns=envns) header.append(content) return header
def body(self, content): """ Build the B{<Body/>} for an soap outbound message. @param content: The body content. @type content: L{Element} @return: the soap body fragment. @rtype: L{Element} """ body = Element('Body', ns=envns) body.append(content) return body
def _fault(code, msg): '''Generate fault XML''' faultcode = Element('faultcode').setText(code) faultstring = Element('faultstring').setText(msg) fault = Element('Fault').append([faultcode, faultstring]) body = Element('Body').append(fault) envelope = Element('Envelope', ns=soap_envns) envelope.append(body) envelope.refitPrefixes() return envelope.str()
def xml(self): self.created = datetime.utcnow() root = Element("Timestamp", ns=WSUNS) created = Element('Created', ns=WSUNS) created.setText(iso_utc(self.created)) root.append(created) if self.validity is not None: self.expires = self.created + timedelta(seconds=self.validity) expires = Element('Expires', ns=WSUNS) expires.setText(iso_utc(self.expires)) root.append(expires) return root
def startElement(self, name, attrs): top = self.top() node = Element(unicode(name), parent=top) for a in attrs.getNames(): n = unicode(a) v = unicode(attrs.getValue(a)) attribute = Attribute(n, v) if self.mapPrefix(node, attribute): continue node.append(attribute) top.append(node) self.push(node)
def startElement(self, name, attrs): top = self.top() node = Element(unicode(name), parent=top) for a in attrs.getNames(): n = unicode(a) v = unicode(attrs.getValue(a)) attribute = Attribute(n,v) if self.mapPrefix(node, attribute): continue node.append(attribute) top.append(node) self.push(node)
def xml(self): self.created = Token.utc() root = Element("Timestamp", ns=WSUNS) created = Element('Created', ns=WSUNS) created.setText(self._trim_to_ms(str(UTC(self.created)))) root.append(created) if self.validity is not None: self.expires = self.created + timedelta(seconds=self.validity) expires = Element('Expires', ns=WSUNS) expires.setText(self._trim_to_ms(str(UTC(self.expires)))) root.append(expires) return root
def set_session(self, session_id): """ Record the session info. """ self.session = session_id self.session_expiration = datetime.now() + timedelta( seconds=self.session_duration) session_namespace = ('ns1', 'http://api.zuora.com/') session = Element('session', ns=session_namespace).setText(session_id) header = Element('SessionHeader', ns=session_namespace) header.append(session) self.client.set_options(soapheaders=[header])
def startElement(self, name, attrs): top = self.top() node = Element(str(name)) for a in attrs.getNames(): n = str(a) v = str(attrs.getValue(a)) attribute = Attribute(n, v) if self.mapPrefix(node, attribute): continue node.append(attribute) node.charbuffer = [] top.append(node) self.push(node)
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Security', ns=wssens) root.set('mustUnderstand', 1 if self.mustUnderstand else 0) if self.timestamp: root.append(Timestamp().xml()) for t in self.tokens: root.append(t.xml()) return root
class AuthInfo: def __init__(self, client, username, password): tns = ('tns', 'http://services.tripolis.com/') self.__auth_info = Element('authInfo', ns=tns) client = Element('client').setText(client) username = Element('username').setText(username) password = Element('password').setText(password) self.__auth_info.append(client) self.__auth_info.append(username) self.__auth_info.append(password) def get(self): return self.__auth_info
def body(self, content): """ Build the B{<Body/>} for a SOAP outbound message. @param content: The body content. @type content: L{Element} @return: The SOAP body fragment. @rtype: L{Element} """ body = Element("Body", ns=envns) body.append(content) return body
def startElement(self, name, attrs): top = self.top() node = Element(str(name)) for a in attrs.getNames(): n = str(a) v = str(attrs.getValue(a)) attribute = Attribute(n,v) if self.mapPrefix(node, attribute): continue node.append(attribute) node.charbuffer = [] top.append(node) self.push(node)
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Security', ns=WSSE_NS) for p, u in self.nsprefixes.items(): root.addPrefix(p, u) root.set('SOAP-ENV:mustUnderstand', self.mustUnderstand) for t in self.tokens: root.append(t.xml()) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) root.set('wsu:Id', 'UsernameToken-%i' % hash(self)) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) # The Type attribute defaults to PasswordText, but some endpoints # seem to want it specified anyway. p.set('Type', PASSWORD_TYPES['plain']) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(self.created.isoformat()) root.append(n) return root
def xml(self): if self.digest and self.password is None: raise RuntimeError("Cannot generate password digest without the password.") if self.autosetnonce: self.setnonce() if self.autosetcreated: self.setcreated() root = Element('UsernameToken', ns=WSSENS) u = Element('Username', ns=WSSENS) u.setText(self.username) root.append(u) if self.password is not None: password = self.password if self.digest: password = self.get_digest() p = Element('Password', ns=WSSENS) p.setText(password) p.set('Type', DIGEST_TYPE if self.digest else TEXT_TYPE) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=WSSENS) n.setText(base64.encodestring(self.nonce)[:-1]) n.set('EncodingType', BASE64_ENC_TYPE) root.append(n) if self.created: c = Element('Created', ns=WSUNS) c.setText(str(UTC(self.created))) root.append(c) return root
def xml(self): usernametoken = Element("UsernameToken", ns=wssens) username = Element("Username", ns=wssens) username.setText(self.username) usernametoken.append(username) password = Element("Password", ns=wssens) s = hashlib.sha1() s.update(self.nonce) s.update(self._print_datetime(self.created).encode("utf-8")) s.update(self.password.encode("utf-8")) password.setText(b64encode(s.digest()).decode("utf-8")) password.set( "Type", "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-username-token-profile-1.0" "#PasswordDigest", ) usernametoken.append(password) nonce = Element("Nonce", ns=wssens) nonce.setText(b64encode(self.nonce).decode("utf-8")) nonce.set( "EncodingType", "http://docs.oasis-open.org/wss/2004" "/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary", ) usernametoken.append(nonce) created = Element("Created", ns=wsuns) created.setText(self._print_datetime(self.created)) usernametoken.append(created) return usernametoken
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) if self.password_digest: p.set("Type", wsdigest) p.setText(self.password_digest) else: p.set("Type", wstext) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) if self.nonce_has_encoding: n.set("EncodingType", nonce_encoding_type) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(DateTime(self.created))) root.append(n) return root
def xml(self): usernametoken = Element('UsernameToken', ns=wssens) username = Element('Username', ns=wssens) username.setText(self.username) usernametoken.append(username) password = Element('Password', ns=wssens) s = hashlib.sha1() s.update(self.nonce) s.update(self._print_datetime(self.created).encode('utf-8')) s.update(self.password.encode('utf-8')) password.setText(b64encode(s.digest()).decode('utf-8')) password.set( 'Type', 'http://docs.oasis-open.org/wss/2004/01/' 'oasis-200401-wss-username-token-profile-1.0' '#PasswordDigest') usernametoken.append(password) nonce = Element('Nonce', ns=wssens) nonce.setText(b64encode(self.nonce).decode('utf-8')) nonce.set( 'EncodingType', 'http://docs.oasis-open.org/wss/2004' '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary') usernametoken.append(nonce) created = Element('Created', ns=wsuns) created.setText(self._print_datetime(self.created)) usernametoken.append(created) return usernametoken
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText( str( UTC(self.created - timedelta(microseconds=self.created.microsecond)))) root.append(n) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(self.created) #txt=str(DateTime(self.created)) #txt=txt.replace('Z', '') #n.setText(txt) root.append(n) return root
def xml(self): usernametoken = Element('UsernameToken', ns=wssens) username = Element('Username', ns=wssens) username.setText(self.username) usernametoken.append(username) password = Element('Password', ns=wssens) s = hashlib.sha1() s.update(self.nonce) s.update(self._print_datetime(self.created).encode('utf-8')) s.update(self.password.encode('utf-8')) password.setText(b64encode(s.digest()).decode('utf-8')) password.set('Type', 'http://docs.oasis-open.org/wss/2004/01/' 'oasis-200401-wss-username-token-profile-1.0' '#PasswordDigest') usernametoken.append(password) nonce = Element('Nonce', ns=wssens) nonce.setText(b64encode(self.nonce).decode('utf-8')) nonce.set( 'EncodingType', 'http://docs.oasis-open.org/wss/2004' '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary' ) usernametoken.append(nonce) created = Element('Created', ns=wsuns) created.setText(self._print_datetime(self.created)) usernametoken.append(created) return usernametoken
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) p.set( 'Type', 'http://docs.oasis-open.org/wss/2004/01/' 'oasis-200401-wss-username-token-profile-1.0#' + ('PasswordDigest' if self.digest else 'PasswordText')) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) if self.digest: n.set( 'EncodingType', 'http://docs.oasis-open.org/wss/2004' '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary' ) n.setText(b64encode(self.nonce)) else: n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(UTC(self.created))) root.append(n) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.generate_digest()) p.set(wspassd[0], wspassd[1]) root.append(p) n = Element('Nonce', ns=wssens) nonce_bytes = self.nonce if not isinstance(self.nonce, bytes): nonce_bytes = self.nonce.encode('utf-8') n.setText(base64.encodebytes(nonce_bytes)[:-1]) n.set(wsenctype[0], wsenctype[1]) root.append(n) n = Element('Created', ns=wsuns) n.setText(self.created) root.append(n) self.reset() return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) if self.password_digest: p.set('Type', wsdigest) p.setText(self.password_digest) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) if self.nonce_has_encoding: n.set('EncodingType', nonce_encoding_type) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(DateTime(self.created))) root.append(n) return root
def xml(self): if self.digest and self.password is None: raise RuntimeError("Cannot generate password digest without the password.") if self.autosetnonce: self.setnonce() if self.autosetcreated: self.setcreated() root = Element('UsernameToken', ns=WSSENS) u = Element('Username', ns=WSSENS) u.setText(self.username) root.append(u) if self.password is not None: password = self.password if self.digest: password = self.get_digest() p = Element('Password', ns=WSSENS) p.setText(password) p.set('Type', DIGEST_TYPE if self.digest else TEXT_TYPE) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=WSSENS) n.setText(base64.encodestring(self.nonce)[:-1]) n.set('EncodingType', BASE64_ENC_TYPE) root.append(n) if self.created: c = Element('Created', ns=WSUNS) c.setText(iso_utc(self.created)) root.append(c) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.generate_digest()) p.set(wspassd[0], wspassd[1]) root.append(p) n = Element('Nonce', ns=wssens) n.setText(base64.encodestring(self.nonce)[:-1]) n.set(wsenctype[0], wsenctype[1]) root.append(n) n = Element('Created', ns=wsuns) n.setText(self.created) root.append(n) self.reset() return root
def payuMeaGetTransactionApiCall(self, args): #urlToQuery = 'https://secure.payu.co.za/service/PayUAPI?wsdl' if (args['store']['environment'] == 'staging'): urlToQuery = 'https://staging.payu.co.za/service/PayUAPI?wsdl' else: urlToQuery = 'https://secure.payu.co.za/service/PayUAPI?wsdl' plugin = MyPlugin() client = Client(urlToQuery, plugins=[plugin]) #client = Client(urlToQuery, faults=False) #------------------------------------- CREATING CUSTOM HEADER-------------------------------------- wsse = ( 'wsse', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' ) mustAttributeSecurity = Attribute('SOAP-ENV:mustUnderstand', '1') addressAttributeSecurity = Attribute( 'xmlns:wsse', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' ) AttributeUsernameToken1 = Attribute('wsu:Id', 'UsernameToken-9') addressAttributeUsernameToken = Attribute( 'xmlns:wsu', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' ) addressAttributePassword = Attribute( 'Type', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText' ) msgUsername = Element('Username', ns=wsse).setText(args['store']['soapUsername']) msgPassword = Element('Password', ns=wsse).setText( args['store']['soapPassword']).append(addressAttributePassword) msgUsernameToken = Element('UsernameToken', ns=wsse) msgUsernameToken.append(AttributeUsernameToken1) msgUsernameToken.append(addressAttributeUsernameToken) msgUsernameToken.insert(msgPassword).insert(msgUsername) msgSecurity = Element('Security', ns=wsse).addPrefix( p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding') msgSecurity.append(mustAttributeSecurity) msgSecurity.append(addressAttributeSecurity) msgSecurity.insert(msgUsernameToken) client.set_options(soapheaders=[msgSecurity]) #------------------------------------- CREATING SOAP CALL DETAILS HERE-------------------------------------- transaction = {} transaction['Api'] = 'ONE_ZERO' transaction['Safekey'] = args['store']['safekey'] transaction['AdditionalInformation'] = args['additionalInformation'] #------------------------------------- DOING SOAP CALL HERE-------------------------------------- try: setTransaction = client.service.getTransaction(**transaction) except Exception, e: print_exc()
def envelope(self, header, body): """ Build the B{<Envelope/>} for a SOAP outbound message. @param header: The SOAP message B{header}. @type header: L{Element} @param body: The SOAP message B{body}. @type body: L{Element} @return: The SOAP envelope containing the body and header. @rtype: L{Element} """ env = Element('Envelope', ns=envns) env.addPrefix(Namespace.xsins[0], Namespace.xsins[1]) env.append(header) env.append(body) return env
def envelope(self, header, body): """ Build the B{<Envelope/>} for an soap outbound message. @param header: The soap message B{header}. @type header: L{Element} @param body: The soap message B{body}. @type body: L{Element} @return: The soap envelope containing the body and header. @rtype: L{Element} """ env = Element('Envelope', ns=envns) env.addPrefix(Namespace.xsins[0], Namespace.xsins[1]) env.append(header) env.append(body) return env
def xml(self): root = Element("Timestamp", ns=wsuns) # xsd:datetime format does not have fractional seconds created = Element('Created', ns=wsuns) created.setText( str( UTC(self.created - timedelta(microseconds=self.created.microsecond)))) expires = Element('Expires', ns=wsuns) expires.setText( str( UTC(self.expires - timedelta(microseconds=self.expires.microsecond)))) root.append(created) root.append(expires) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Timestamp', ns=wsuns) root.set('wsu:Id', 'Timestamp-%i' % hash(self)) c = Element('Created', ns=wsuns) c.setText(self.created.isoformat()) root.append(c) if self.expires: e = Element('Expires', ns=wsuns) e.setText(self.expires.isoformat()) root.append(e) return root
def deleteItems(self, *item_ids): """ Remove list items given by value of their primary key """ batch = Element('Batch') batch.append(Attribute('OnError', 'Return')).append(Attribute('ListVersion', '1')) for i, item_id in enumerate(item_ids): method = Element('Method') method.append(Attribute('ID', str(i + 1))).append( Attribute('Cmd', 'Delete')) method.append( Element('Field').append(Attribute( 'Name', self.primary_key)).setText(item_id)) batch.append(method) updates = Element('ns0:updates') updates.append(batch) result = self.service.UpdateListItems(self.list_id, updates) return ParsedSoapResult(result)
def add_extern_service(self, name, portname, binding, location): """Add a service that was not defined in the wsdl. This is used after the Definitions object has been created. @param name: The name of the new service. @type url: str @param portname: The name of the port of the new service. @type portname: str @param binding: The name of the wsdl binding to use for the new service. The binding must be defined in the wsdl. @type binding: str @param location: The location of the new service. @type location: str """ if binding not in [bind[0] for bind in self.bindings.keys()]: log.debug('Binding "%s" not defined in %s' % (binding, self.url)) raise Exception('Binding "%s" not defined in %s' % (binding, self.url)) service = Element('service') service.set('name', name) port = Element('port', service) port.set('name', portname) port.set('binding', binding) address = Element('address', port) address.set('location', location) port.append(address) service.append(port) service = Factory.create(service, self) service.resolve(self) self.children.append(service) self.services.append(service) self.add_methods(service) log.debug('Created service: %s', service) return service
def get_suds_element(suds_obj, element_name): "Build a suds Element based on a suds-encoded response variable" el = Element(element_name) for node in suds_obj: left = node[0] right = node[1] # Attributes start with _ if left[:1] == '_': el.set(left[1:], str(right)) # Otherwise it's a subelement else: if type(right) is list: for item in right: sub = get_suds_element(item, str(left)) el.append(sub) else: sub = get_suds_element(right, str(left)) el.append(sub) return el
def build_soap_client(self): if self.endpoint is None: self.endpoint = self.determineStack() self.authObj = {'oAuth' : {'oAuthToken' : self.internalAuthToken}} self.authObj['attributes'] = { 'oAuth' : { 'xmlns' : 'http://exacttarget.com' }} self.soap_client = suds.client.Client(self.wsdl_file_url, faults=False, cachingpolicy=1) self.soap_client.set_options(location=self.endpoint) element_oAuth = Element('oAuth', ns=('etns', 'http://exacttarget.com')) element_oAuthToken = Element('oAuthToken').setText(self.internalAuthToken) element_oAuth.append(element_oAuthToken) self.soap_client.set_options(soapheaders=(element_oAuth)) security = suds.wsse.Security() token = suds.wsse.UsernameToken('*', '*') security.tokens.append(token) self.soap_client.set_options(wsse=security)
def create_version(): el = Element('Version') el.setPrefix('ns0') major_release = Element('majorRelease') major_release.setPrefix('ns0') major_release.setText('1') el.append(major_release) minor_release = Element('minorRelease') minor_release.setPrefix('ns0') minor_release.setText('18') el.append(minor_release) return { 'majorRelease': '1', 'minorRelease': '0', } return el
def build_soap_client(self): if self.soap_endpoint is None or not self.soap_endpoint: self.soap_endpoint = self.get_soap_endpoint() self.soap_client = suds.client.Client(self.wsdl_file_url, faults=False, cachingpolicy=1) self.soap_client.set_options(location=self.soap_endpoint) self.soap_client.set_options(headers={'user-agent' : 'FuelSDK-Python-v1.1.1'}) security = suds.wsse.Security() if self.is_endpoints_tenant: element_oAuthToken = Element('fueloauth', ns=('etns', 'http://exacttarget.com')).setText(self.internalAuthToken) self.soap_client.set_options(soapheaders=element_oAuthToken) else : element_oAuth = Element('oAuth', ns=('etns', 'http://exacttarget.com')) element_oAuthToken = Element('oAuthToken').setText(self.internalAuthToken) element_oAuth.append(element_oAuthToken) self.soap_client.set_options(soapheaders=element_oAuth) token = suds.wsse.UsernameToken('*', '*') security.tokens.append(token) self.soap_client.set_options(wsse=security)
def addItems(self, *addable_items): """ Add a sequence of items to the list. All items must be passed as dict. The list of assigned primary key values should from the 'row' values of the result object. """ batch = Element('Batch') batch.append(Attribute('OnError', 'Return')).append(Attribute('ListVersion', '1')) for i, d in enumerate(addable_items): self._preflight(d, primary_key_check=False) method = Element('Method') method.append(Attribute('ID', str(i + 1))).append( Attribute('Cmd', 'New')) for k, v in d.items(): method.append( Element('Field').append(Attribute('Name', k)).setText(v)) batch.append(method) updates = Element('ns0:updates') updates.append(batch) result = self.service.UpdateListItems(self.list_id, updates) return ParsedSoapResult(result)
def updateItems(self, *update_items): """ Update list items as given through a list of update_item dicts holding the data to be updated. The list items are identified through the value of the primary key inside the update dict. """ batch = Element('Batch') batch.append(Attribute('OnError', 'Return')).append(Attribute('ListVersion', '1')) for i, d in enumerate(update_items): self._preflight(d) method = Element('Method') method.append(Attribute('ID', str(i + 1))).append( Attribute('Cmd', 'Update')) for k, v in d.items(): method.append( Element('Field').append(Attribute('Name', k)).setText(v)) batch.append(method) updates = Element('ns0:updates') updates.append(batch) result = self.service.UpdateListItems(self.list_id, updates) return ParsedSoapResult(result)
def __init__(self, wsdl=None, api_key=None, timeout=5): """ Constructor Keyword arguments: wsdl -- the URL of the Darwin LDB WSDL document. Will fall back to using the DARWIN_WEBSERVICE_WSDL environment variable if not supplied api_key -- a valid API key for the Darwin LDB webservice. Will fall back to the DARWIN_WEBSERVICE_API_KEY if not supplied timeout -- a timeout in seconds for calls to the LDB Webservice (default 5) """ if not wsdl: wsdl = os.environ['DARWIN_WEBSERVICE_WSDL'] if not api_key: api_key = os.environ['DARWIN_WEBSERVICE_API_KEY'] self._soap_client = Client(wsdl) self._soap_client.set_options(timeout=timeout) #build soap headers token3 = Element('AccessToken', ns=DARWIN_WEBSERVICE_NAMESPACE) token_value = Element('TokenValue', ns=DARWIN_WEBSERVICE_NAMESPACE) token_value.setText(api_key) token3.append(token_value) self._soap_client.set_options(soapheaders=(token3))