def to_dict(sudsobject): # Convert a WSDL Type instance into a dictionary if sudsobject is None: return {} elif isinstance(sudsobject, list): ret = [] for item in sudsobject: ret.append(Client.dict(item)) return ret return Client.dict(sudsobject)
def to_dict(sudsobject): # Convert a WSDL Type instance into a dictionary if sudsobject is None: return { } elif isinstance(sudsobject, list): ret = [ ] for item in sudsobject: ret.append(Client.dict(item)) return ret return Client.dict(sudsobject)
def run(self, inData): dictConfig = UtilsConfig.getTaskConfig('ISPyB') username = dictConfig['username'] password = dictConfig['password'] httpAuthenticated = HttpAuthenticated(username=username, password=password) wdsl = dictConfig['ispyb_ws_url'] + '/ispybWS/ToolsForCollectionWebService?wsdl' client = Client(wdsl, transport=httpAuthenticated, cache=None) if 'image' in inData: path = pathlib.Path(inData['image']) indir = path.parent.as_posix() infilename = path.name dataCollection = client.service.findDataCollectionFromFileLocationAndFileName( indir, infilename ) elif 'dataCollectionId' in inData: dataCollectionId = inData['dataCollectionId'] dataCollection = client.service.findDataCollection(dataCollectionId) else: errorMessage = 'Neither image nor data collection id given as input!' logger.error(errorMessage) raise BaseException(errorMessage) if dataCollection is not None: outData = Client.dict(dataCollection) else: outData = {} return outData
def update_or_create_instance(self, record): """Creates and returns an instance if it does not already exist.""" created = False api_instance = Client.dict(record) try: instance_pk = api_instance[self.lookup_key] instance = self.model_class.objects.get(pk=instance_pk) except self.model_class.DoesNotExist: instance = self.model_class() created = True try: self._assign_field_data(instance, api_instance) instance.save() except IntegrityError as e: msg = "IntegrityError while attempting to create {}." \ " Error: {}".format(self.model_class, e) logger.error(msg) raise InvalidObjectException(msg) logger.info('{}: {} {}'.format('Created' if created else 'Updated', self.model_class.__name__, instance)) return instance, created
def form(): name = request.args['userInput'] times = request.args['times'] hello_client = Client('http://localhost:7789/?wsdl') hello = hello_client.service.say_hello(name, times) data = Client.dict(hello) return render_template('result_soap.html', data=data, xml=hello_client.__str__())
class WebService(object): def __init__(self, url, username=None, password=None, proxy_netloc=None): # faults=True raise faults raised by server, else return tuple from service method invocation as (httpcode, object). # timeout=180 default suds transport timeout is 90 seconds # use logging plugin collect last sent/received self.logging_plugin = LoggingWebServicePlugin() options = DictObject(timeout=180, faults=True, plugins=[self.logging_plugin]) if not VEIL_ENV.is_prod: options.cache = None if username: options.username = username options.password = password self.suds_client = Client(url, **options) self.proxy_netloc = str(proxy_netloc) if proxy_netloc else None def new_object_of_type(self, wsdl_type, returns_dict_object=False): suds_object = self.suds_client.factory.create(wsdl_type) if returns_dict_object: return DictObject(self.suds_client.dict(suds_object)) return suds_object def last_sent(self): return self.logging_plugin.last_sent() def last_received(self): return self.logging_plugin.last_received() def __getattr__(self, item): service = getattr(self.suds_client.service, item) if self.proxy_netloc: service.method.location = RE_NETLOC.sub(self.proxy_netloc, service.method.location, count=1) return service
def checkOpenid(openid): client = Client('http://172.16.10.107/uapws/service/nc.ws.intf.IPsnService?wsdl') result = client.service.checkOpenId(openid) print client # result = simplejson.loads(result) result = Client.dict(result) return result
def checkOpenid(openid): client = Client( 'http://172.16.10.107/uapws/service/nc.ws.intf.IPsnService?wsdl') result = client.service.checkOpenId(openid) print client # result = simplejson.loads(result) result = Client.dict(result) return result
def conver_to_dict(cls, suds_object): """ Convert a sudsobject into a dictionary. :param suds_object - A suds object :return: dict - A python dictionary containing the items contained in sobject. """ required_dict = Client.dict(suds_object) return required_dict
def checkForOutput(input): dictionary = Client.dict(input) for item in dictionary: if (item == "Message"): return "Message" elif (item == "Proof"): return "Proof" elif (item == "WhyNot"): return "WhyNot" return "Error"
def get_project_info_from_soap(self): soap_config = self.app.config['soap'] client = Client(soap_config['url']) info = client.service.mc_projects_get_user_accessible(soap_config['username'], soap_config['password']) array = [] project_list = [] for item in info: array.append(client.dict(item)) for item in array: project_list.append(str(item['name'])) return project_list
def getaltname(row): erg = [] try: print('setzt Abfrage ab für:', row[1]) result = client.service.getObject(row[1]) print('Ergebnis empfangen') if 'name' in Client.dict(result): for eintrag in Client.dict(result)['name']: if Client.dict(eintrag)['_value'] != gov.loc[ row[0], 'aktueller Name']: print( Client.dict(eintrag)['_value'], ' != ', gov.loc[row[0], 'aktueller Name']) erg.append([row[0], Client.dict(eintrag)['_value']]) print(erg) print('---------------------------bearbeitet:', row[0], 'von:', y) except Exception as e: print('hier eine Fehlermeldung', e, row) return erg
def getcoords(row): erg = [] print('setzt Abfrage ab für:', row[1]) result = client.service.getObject(row[1]) print('Ergebnis empfangen') longitude = 0.1 latitude = 0.1 #print(result) if 'position' in Client.dict(result): for eintrag in Client.dict(result)['position']: print(eintrag) if (eintrag[0] == '_lon') and (longitude == 0.1): longitude = eintrag[1] if (eintrag[0] == '_lat') and (latitude == 0.1): latitude = eintrag[1] erg.append([row[0], longitude, latitude]) print(erg) print('---------------------------bearbeitet:', row[0], 'von:', y) return erg
class SudsClient: def __init__(self, url, name, args): self.client = Client(url, cache=None) self.name = name self.args = args def service(self): get_service = self.client.service.__getattr__(self.name)(self.args) return get_service def __repr__(self): parsed = self.client.dict(self.service()) return parsed['string']
def render(node): #sys.stderr.write('%s[%s]\n'%(node,type(node))) if type(node) in [Text]: return '%s' % node if type(node) == list: return list(map(render, node)) if hasattr(node, '__dict__'): node = Client.dict(node) if type(node) in [dict, OrderedDict]: d = dict() for key in node.keys(): d[key] = render(node[key]) return d return node
def login(Id): # this function logs into algosec and look for a user ID ip = "" username = "" #login information password = "" Request_id = Id[0] print Id client = FireFlowAPIClient(ip, username, password, verify_ssl=False) try: #gets an ID and uses it to get a change request from algosec change_request = client.get_change_request_by_id(Request_id) change_request = Client.dict(change_request) return change_request except: # error for missing or invalid ID'S print "ID was not found " + Request_id return 1
def update_or_create_instance(self, record): """Creates and returns an instance if it does not already exist.""" result = None api_instance = Client.dict(record) try: instance_pk = api_instance[self.lookup_key] instance = self.model_class.objects.get( **{self.db_lookup_key: instance_pk}) except self.model_class.DoesNotExist: instance = self.model_class() result = CREATED try: self._assign_field_data(instance, api_instance) # This will return the created instance, the updated instance, or # if the instance is skipped an unsaved copy of the instance. if result == CREATED: if self.model_class is models.Ticket: instance.save(force_insert=True) else: instance.save() elif instance.tracker.changed(): instance.save() result = UPDATED else: result = SKIPPED except IntegrityError as e: msg = "IntegrityError while attempting to create {}." \ " Error: {}".format(self.model_class, e) logger.error(msg) raise InvalidObjectException(msg) if result == CREATED: result_log = 'Created' elif result == UPDATED: result_log = 'Updated' else: result_log = 'Skipped' logger.info('{}: {} {}'.format(result_log, self.model_class.__bases__[0].__name__, instance)) return instance, result
def get_project_list(self, username, password): projects = [] for project in client.service.mc_projects_get_user_accessible( username, password): dict = Client.dict(project) id = dict['id'] name = dict['name'] status = dict['status']['name'] enabled = dict['enabled'] view_status = dict['view_state']['name'] description = dict['description'] projects.append( Project(id=str(id), name=str(name), status=str(status), enabled=enabled, view_status=str(view_status), description=str(description))) return projects
def run(self, inData): dictConfig = UtilsConfig.getTaskConfig('ISPyB') username = dictConfig['username'] password = dictConfig['password'] httpAuthenticated = HttpAuthenticated(username=username, password=password) wdsl = dictConfig['ispyb_ws_url'] + '/ispybWS/ToolsForCollectionWebService?wsdl' client = Client(wdsl, transport=httpAuthenticated, cache=None) manufacturer = inData['manufacturer'] model = inData['model'] mode = inData['mode'] detector = client.service.findDetectorByParam( "", manufacturer, model, mode ) if detector is not None: outData = Client.dict(detector) else: outData = {} return outData
def read_clients(): services = ClientRequest.ClientServiceMethods() #get all clients result = services.GetAllClients() client_dict = Client.dict(result) clients = client_dict['Clients'].Client player_names = set() players = dict() num_clients = len(clients) for i in range(num_clients) : client = clients[i] first_name = client.FirstName.lower() last_name = client.LastName.lower() id = client.UniqueID try : pin = str(id)[-4:] name = first_name + last_name if len(name) > 16: if len(last_name) > 16: name = last_name[0:15] else: temp = 16 - len(last_name) name = first_name[0:temp] + last_name if name in player_names: name += pin[-2:] player_names.add(name) except ValueError: pass finally: players[name] = player(name, id, pin) return players
class WebService(object): def __init__(self, url, use_real_url, **kwargs): self.use_real_url = use_real_url self.suds_client = Client(url, timeout=180, **kwargs) # default suds transport timeout is 90 seconds self.service_url = str(url.replace('?wsdl', '')) # to work around erp tunnel port not preserved bug def new_object_of_type(self, wsdl_type, returns_dict_object=False): suds_object = self.suds_client.factory.create(wsdl_type) if returns_dict_object: return DictObject(self.suds_client.dict(suds_object)) return suds_object def last_sent(self): return self.suds_client.last_sent() def last_received(self): return self.suds_client.last_received() def __getattr__(self, item): service = getattr(self.suds_client.service, item) if not self.use_real_url: service.method.location = self.service_url return service
def _cybersource_s2s_validate(self, tree): if self.state == 'done': _logger.warning( 'CyberSource: trying to validate an already validated tx (ref %s)' % self.reference) return True status_code = tree.get('reasonCode', 0) if status_code == self._cybersource_valid_tx_status: tx_id = Client.dict( tree.get('ccAuthReply')).get('reconciliationID') self.write({ 'acquirer_reference': tx_id, 'date': fields.Datetime.now(), }) self._set_transaction_done() return True else: self.write({'acquirer_reference': ""}) self._set_transaction_cancel() raise UserError( _('API CALL REJECTED. \nTRANSACTION CANCELLED. \nERROR CODE: %s, \nERROR DETAILS: %s!' % (status_code, cybersource_request.CYBERSOURCE_RESPONSES.get( str(status_code)))))
def _get_token(self): token = Client.dict(self._client.service.GetUserToken(self._user, self._pass)) token['expires'] = datetime.now() + timedelta(hours=24) self._token = token
class DespatchBaySDK: """ Client for despatchbay v15 api. https://github.com/despatchbay/despatchbay-api-v15/wiki """ def __init__(self, api_user, api_key, api_domain='api.despatchbay.com', despactchbay_api_version=MIN_SOAP_API_VERSION, documents_api_version=MIN_DOCUMENTS_API_VERSION): if despactchbay_api_version < MIN_SOAP_API_VERSION: raise exceptions.ApiException( "DespatchBay API version must be 15 or higher.") if documents_api_version < MIN_DOCUMENTS_API_VERSION: raise exceptions.ApiException( "Documents API version must be 1 or higher.") soap_url_template = 'http://{}/soap/v{}/{}?wsdl' documents_url = 'http://{}/documents/v{}'.format( api_domain, documents_api_version) account_url = soap_url_template.format(api_domain, despactchbay_api_version, 'account') shipping_url = soap_url_template.format(api_domain, despactchbay_api_version, 'shipping') addressing_url = soap_url_template.format(api_domain, despactchbay_api_version, 'addressing') tracking_url = soap_url_template.format(api_domain, despactchbay_api_version, 'tracking') self.account_client = Client(account_url, transport=self.create_transport( api_user, api_key)) self.addressing_client = Client(addressing_url, transport=self.create_transport( api_user, api_key)) self.shipping_client = Client(shipping_url, transport=self.create_transport( api_user, api_key)) self.tracking_client = Client(tracking_url, transport=self.create_transport( api_user, api_key)) self.pdf_client = documents_client.DocumentsClient( api_url=documents_url) @staticmethod def create_transport(username, password): """ HTTP transport providing authentication for suds. """ return HttpAuthenticated(username=username, password=password) # Shipping entities def parcel(self, **kwargs): """ Creates a dbp parcel entity """ return despatchbay_entities.Parcel(self, **kwargs) def address(self, **kwargs): """ Creates a dbp address entity """ return despatchbay_entities.Address(self, **kwargs) def recipient(self, **kwargs): """ Creates a dbp recipient address entity """ return despatchbay_entities.Recipient(self, **kwargs) def sender(self, **kwargs): """ Creates a dbp sender address entity """ return despatchbay_entities.Sender(self, **kwargs) def shipment_request(self, **kwargs): """ Creates a dbp shipment entity """ return despatchbay_entities.ShipmentRequest(self, **kwargs) # Account Services @try_except def get_account(self): """Calls GetAccount from the Despatch Bay Account Service.""" account_dict = self.account_client.dict( self.account_client.service.GetAccount()) return despatchbay_entities.Account.from_dict(self, account_dict) @try_except def get_account_balance(self): """ Calls GetBalance from the Despatch Bay Account Service. """ balance_dict = self.account_client.dict( self.account_client.service.GetAccountBalance()) return despatchbay_entities.AccountBalance.from_dict( self, balance_dict) @try_except def get_sender_addresses(self): """ Calls GetSenderAddresses from the Despatch Bay Account Service. """ sender_addresses_dict_list = [] for sender_address in self.account_client.service.GetSenderAddresses(): sender_address_dict = self.account_client.dict(sender_address) sender_addresses_dict_list.append( despatchbay_entities.Sender.from_dict(self, sender_address_dict)) return sender_addresses_dict_list @try_except def get_services(self): """ Calls GetServices from the Despatch Bay Account Service. """ service_list = [] for account_service in self.account_client.service.GetServices(): service_list.append( despatchbay_entities.Service.from_dict( self, self.account_client.dict(account_service))) return service_list @try_except def get_payment_methods(self): """ Calls GetPaymentMethods from the Despatch Bay Account Service. """ payment_methods = [] for payment_method in self.account_client.service.GetPaymentMethods(): payment_methods.append( despatchbay_entities.PaymentMethod.from_dict( self, self.account_client.dict(payment_method))) return payment_methods @try_except def enable_automatic_topups(self, minimum_balance=None, topup_amount=None, payment_method_id=None, automatic_topup_settings_object=None): """ Calls EnableAutomaticTopups from the Despatch Bay Account Service. Passing an automatic_topup_settings object takes priority over using individual arguments. """ if not automatic_topup_settings_object: automatic_topup_settings_object = despatchbay_entities.AutomaticTopupSettings( self, minimum_balance, topup_amount, payment_method_id) return self.account_client.service.EnableAutomaticTopups( automatic_topup_settings_object.to_soap_object()) @try_except def disable_automatic_topups(self): """ Calls DisableAutomaticTopups from the Despatch Bay Account Service. """ return self.account_client.service.DisableAutomaticTopups() # Addressing Services @try_except def find_address(self, postcode, property_string): """ Calls FindAddress from the Despatch Bay Addressing Service. """ found_address_dict = self.addressing_client.dict( self.addressing_client.service.FindAddress(postcode, property_string)) return despatchbay_entities.Address.from_dict(self, found_address_dict) @try_except def get_address_by_key(self, key): """ Calls GetAddressByKey from the Despatch Bay Addressing Service. """ found_address_dict = self.addressing_client.dict( self.addressing_client.service.GetAddressByKey(key)) return despatchbay_entities.Address.from_dict(self, found_address_dict) @try_except def get_address_keys_by_postcode(self, postcode): """ Calls GetAddressKeysFromPostcode from the Despatch Bay Addressing Service. """ address_keys_dict_list = [] for soap_address_key in self.addressing_client.service.GetAddressKeysByPostcode( postcode): address_key_dict = self.account_client.dict(soap_address_key) address_keys_dict_list.append( despatchbay_entities.AddressKey.from_dict( self, address_key_dict)) return address_keys_dict_list # Shipping services @try_except def get_available_services(self, shipment_request): """ Calls GetAvailableServices from the Despatch Bay Shipping Service. """ available_service_dict_list = [] for available_service in self.shipping_client.service.GetAvailableServices( shipment_request.to_soap_object()): available_service_dict = self.shipping_client.dict( available_service) available_service_dict_list.append( despatchbay_entities.Service.from_dict(self, available_service_dict)) return available_service_dict_list @try_except def get_available_collection_dates(self, sender_address, courier_id): """ Calls GetAvailableCollectionDates from the Despatch Bay Shipping Service. """ available_collection_dates_response = self.shipping_client.service.GetAvailableCollectionDates( sender_address.to_soap_object(), courier_id) available_collection_dates_list = [] for collection_date in available_collection_dates_response: collection_date_dict = self.shipping_client.dict(collection_date) available_collection_dates_list.append( despatchbay_entities.CollectionDate.from_dict( self, collection_date_dict)) return available_collection_dates_list @try_except def get_collection(self, collection_id): """ Calls GetCollection from the Despatch Bay Shipping Service. """ collection_dict = self.shipping_client.dict( self.shipping_client.service.GetCollection(collection_id)) return despatchbay_entities.Collection.from_dict(self, collection_dict) @try_except def get_collections(self): """ Calls GetCollections from the Despatch Bay Shipping Service. """ collections_dict_list = [] for found_collection in self.shipping_client.service.GetCollections(): collection_dict = self.shipping_client.dict(found_collection) collections_dict_list.append( despatchbay_entities.Collection.from_dict( self, collection_dict)) return collections_dict_list @try_except def get_shipment(self, shipment_id): """ Calls GetShipment from the Despatch Bay Shipping Service. """ shipment_dict = self.shipping_client.dict( self.shipping_client.service.GetShipment(shipment_id)) return despatchbay_entities.ShipmentReturn.from_dict( self, shipment_dict) @try_except def add_shipment(self, shipment_request): """ Calls AddShipment from the Despatch Bay Shipping Service. """ return self.shipping_client.service.AddShipment( shipment_request.to_soap_object()) @try_except def book_shipments(self, shipment_ids): """ Calls BookShipments from the Despatch Bay Shipping Service. """ array_of_shipment_id = self.shipping_client.factory.create( 'ns1:ArrayOfShipmentID') array_of_shipment_id.item = shipment_ids booked_shipments_list = [] for booked_shipment in self.shipping_client.service.BookShipments( array_of_shipment_id): booked_shipment_dict = self.shipping_client.dict(booked_shipment) booked_shipments_list.append( despatchbay_entities.ShipmentReturn.from_dict( self, booked_shipment_dict)) return booked_shipments_list @try_except def cancel_shipment(self, shipment_id): """ Calls CancelShipment from the Despatch Bay Shipping Service. """ return self.shipping_client.service.CancelShipment(shipment_id) # Tracking services @try_except def get_tracking(self, tracking_number): """ Calls GetTracking from the Despatch Bay Tracking Service. """ return self.tracking_client.service.GetTracking(tracking_number) # Documents services def get_labels(self, document_ids, **kwargs): """ Fetches labels from the Despatch Bay documents API. """ return self.pdf_client.get_labels(document_ids, **kwargs) def get_manifest(self, collection_document_id, **kwargs): """ Fetches manifests from the Despatch Bay documents API. """ return self.pdf_client.get_manifest(collection_document_id, **kwargs)
def upload_saved_list(self, tbl, list_name, folder_id, url_type, id_type='vanid', replace=False, **url_kwargs): """ .. warning:: .. deprecated:: 0.X Use :func:`parsons.VAN.upload_saved_list_rest` instead. Upload a saved list. Invalid or unmatched person id records will be ignored. Your api user must be shared on the target folder. `Args:` tbl: parsons.Table A parsons table object containing one column of person ids. list_name: str The saved list name. folder_id: int The folder id where the list will be stored. url_type: str The cloud file storage to use to post the file. Currently only ``S3``. id_type: str The primary key type. The options, beyond ``vanid`` are specific to your instance of VAN. replace: boolean Replace saved list if already exists. **url_kwargs: kwargs Arguments to configure your cloud storage url type. * S3 requires ``bucket`` argument and, if not stored as env variables ``aws_access_key`` and ``aws_secret_access_key``. `Returns:` dict Upload results information included the number of matched and saved records in your list. """ # Move to cloud storage file_name = str(uuid.uuid1()) url = cloud_storage.post_file(tbl, url_type, file_path=file_name + '.zip', **url_kwargs) logger.info(f'Table uploaded to {url_type}.') # VAN errors for this method are not particularly useful or helpful. For that reason, we # will check that the folder exists and if the list already exists. logger.info('Validating folder id and list name.') if folder_id not in [x['folderId'] for x in self.get_folders()]: raise ValueError( "Folder does not exist or is not shared with API user.") if not replace: if list_name in [ x['name'] for x in self.get_saved_lists(folder_id) ]: raise ValueError( "Saved list already exists. Set to replace argument to True or " "change list name.") # i think we dont need this if we have the warning in the funciton description, # perhapse a style/standanrds decision if id_type == 'vanid': logger.warning('The NVPVAN SOAP API is deprecated, consider using ' 'parsons.VAN.upload_saved_list_rest if you are ' 'uploading a list of vanids.') # Create XML xml = self.connection.soap_client.factory.create( 'CreateAndStoreSavedListMetaData') xml.SavedList._Name = list_name xml.DestinationFolder._ID = folder_id xml.SourceFile.FileName = file_name + '.csv' xml.SourceFile.FileUrl = url xml.SourceFile.FileCompression = 'zip' xml.Options.OverwriteExistingList = replace # Describe file file_desc = self.connection.soap_client.factory.create( 'SeparatedFileFormatDescription') file_desc._name = 'csv' file_desc.HasHeaderRow = True # Only support single column for now col = self.connection.soap_client.factory.create('Column') col.Name = id_type col.RefersTo._Path = f"Person[@PersonIDType=\'{id_type}\']" col._Index = '0' # Assemble request file_desc.Columns.Column.append(col) xml.SourceFile.Format = file_desc r = Client.dict( self.connection.soap_client.service.CreateAndStoreSavedList(xml)) if r: logger.info( f"Uploaded {r['ListSize']} records to {r['_Name']} saved list." ) return r
split_information = file() header = {} row = 1 #creates varables head_num = 0 metric_list = [] fail_request = [] #create varable for later file() print split_information request_list = [] for Id in split_information: if Id != "id": change_request = login(Id) if change_request != 1: try: test = change_request['trafficLines'] traffic = Client.dict( test[0]) #changes the traffic data into dictionary format del change_request['trafficLines'] change_request.update(traffic) except: pass metric_list.append(change_request) for metric in metric_list: key = metric.keys() metric = dict(metric) #converts the varable to a dictionary for keys in key: if header.has_key(keys): worksheet.write(row, header[keys], str(metric[keys])) else: #writes the data to a text file worksheet.write(0, head_num, keys) print metric[keys] worksheet.write(row, head_num, str(metric[keys]))
from suds.client import Client import csv url = "http://brickset.com/api/v2.asmx?WSDL" namespace = "http://brickset.com/api/" apikey = "LqqM-WlJg-Ik6b" username = "******" password = "******" brickset = Client(url) # print brickset themes = brickset.service.getThemes(apikey) theme = themes['themes'][0] with open("themes.csv", 'wb') as csvfile: csvwriter = csv.DictWriter(csvfile, brickset.dict(theme).keys().sort(), dialect='excel', quoting=csv.QUOTE_NONNUMERIC) csvwriter.writerow(["theme", "setCount", "subthemeCount", "yearFrom", "yearTo"]) for theme in themes['themes']: csvwriter.writerow([theme.theme, theme.setCount, theme.subthemeCount, theme.yearFrom, theme.yearTo])