In python How can I extract data from webservices response using suds - python

I am using python 2.71. I got this response from webservices call using python and suds library. I would like to extract the value of tag problemName. How can I do that ?
(200, (TESTResult){
ProblemList =
(ArrayList){
Items =
(ArrayOfAnyType){
Item[] =
(Problem){
comment = None
name = None
problemName = "Sad"
relation = "Mother"
source = "Provider"
},
(Problem){
comment = None
name = None
problemName = "Stress"
relation = "Father"
source = "Provider"
}
}
}
})

I was able to remove (200, (TESTResult) by calling webservice without faults=False parameter for example :
#client = Client(url, transport=t, faults=False)
client = Client(url, transport=t)
resp = client.service.getProblemHistory(ProblemRequest)
probs = resp.ProblemList.Items.Item
for prob in probs
print "problem : " , prob.problemName

Related

Python how to return a list to other functions?

I have been trying to return the list so other functions can access it. But in all the other functions the variables become undefined. The command should be "return twitchClipLinks" right?
def api():
#API via twitch to get the top clips of Just Chatting
API_ENDPOINT = 'https://api.twitch.tv/kraken/clips/top?game=Just%20Chatting&period=day&trending=false&limit=6'
ID = 'REMOVED'
auth = 'application/vnd.twitchtv.v5+json'
head = {
'Client-ID' : ID,
'Accept' : auth
}
r = requests.get(url = API_ENDPOINT, headers = head)
twitchClipLinks = []
data = r.json()
for link in data['clips']:
store = str(link['url'])
twitchClipLinks.append(store)
return twitchClipLinks
Inside every function, you have to add something like this: twitchClipLinks = api() Or you can define twitchClipLinks as a global variable and remove the return statement from ur api() function.

How to query the balance of a TRC20 token for a given TRX address?

I'd like to get the balance of a TRC20 token (in this case the WIN token) for a Tron wallet address that owns WIN tokens.
I'm using the Python module tron-api-python and based on what i've read on GitHub and the docs the code for that should look something like this:
from tronapi import Tron
# Source for ABI: https://tronscan.org/#/token20/TLa2f6VPqDgRE67v1736s7bJ8Ray5wYjU7/code
contract_abi = '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"value","type":"uint256"}],"name":"burnFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"account","type":"address"}],"name":"addMinter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"renounceMinter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"account","type":"address"}],"name":"isMinter","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"name","type":"string"},{"name":"symbol","type":"string"},{"name":"decimals","type":"uint8"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"account","type":"address"}],"name":"MinterAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"account","type":"address"}],"name":"MinterRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}]'
tron = Tron()
contract = tron.trx.contract("TLa2f6VPqDgRE67v1736s7bJ8Ray5wYjU7", abi=contract_abi)
balance = contract.functions.balanceOf("TXRZqGMEXsGTX6AQtcSgYknos93hqw18P7")
print(balance)
But the result i get is:
eth_abi.exceptions.NoEntriesFound: No matching entries for 'address' in encoder registry
You can use this API:
import requests
import json
def get_balance(address, token_symbol):
url = "https://apilist.tronscan.org/api/account"
payload = {
"address": address,
}
res = requests.get(url, params=payload)
trc20token_balances = json.loads(res.text)["trc20token_balances"]
token_balance = next((item for item in trc20token_balances if item["symbol"] == token_symbol), None)
if token_balance == None:
return 0
else:
return int(token_balance["balance"])
The previous response broadcasts a transaction to read a constant function; you don't need to do that if you're only going to read the balance.
Found it myself. This is not the code to get the balance but to send the WIN token so for this to return the balance the function_selector and the parameters would need to change but the rest should be fine since both is based on triggering a smart contract.
tron_kwargs = dict()
tron_kwargs["private_key"] = your_privkey
tron_kwargs["default_address"] = your_base58_address
tron = Tron(**tron_kwargs)
kwargs = dict()
kwargs["contract_address"] = tron.address.to_hex(wink_base58_contract_address)
kwargs["function_selector"] = "transfer(address,uint256)"
kwargs["fee_limit"] = 100000
kwargs["call_value"] = 0
kwargs["parameters"] = [
{
'type': 'address',
'value': tron.address.to_hex(recipients_base58_address)
},
{
'type': 'uint256',
'value': 8000000
}
]
raw_tx = tron.transaction_builder.trigger_smart_contract(**kwargs)
sign = tron.trx.sign(raw_tx["transaction"])
result = tron.trx.broadcast(sign)

Manipulating the double quotes when creating a request with python dumps

Looking for some advice customizing requests for json style syntax.
json.dumps will format the like this:
{"tenantid": 1, "name": "NewRoleName", "users": "[djones]"}
But the servers wants something like this:
{"tenantid": 1, "name": "NewRoleName", "users": ["djones"]}
Any easy way to manipulate the double quotes to be placed with in the square brackets?
payload = {}
funcURL = "roles"
if name is not None: payload.update({'name': name})
if userStore is not None: payload.update({'userStore': userStore})
if users is not None: payload.update({'users': "[" + users + "]"})
if tenantid is not None: payload.update({'tenantid': tenantid})
if permissions is not None: payload.update({'userClaims': permissions})
print users
print payload
payload = json.dumps(payload)
return self._call_url('POST', funcURL, payload)
_call_url uses requests to send the payload out:
response = requests.request( methodType, baseURL + "/" + funcURL, data=payload, headers=self.headers, timeout=timeout, verify=False)
Have you tried:
if users is not None: payload.update({'users': users})
This should work if users is something like users = ["djones","mjones","todd"]
The square brackets denote a list. So you have to put users into a list:
funcURL = "roles"
payload = {}
if name is not None:
payload['name'] = name
if userStore is not None:
payload['userStore'] = userStore
if users is not None:
payload['users'] = [users]
if tenantid is not None:
payload['tenantid'] = tenantid
if permissions is not None:
payload['userClaims'] = permissions
payload = json.dumps(payload)
return self._call_url('POST', funcURL, payload)

Suds Python Array Response

Using Python 2.7 and SUDS. How would I print just URL from these arrays/objects? I'd like to be able to pick any of the arrays/objects (such as URL) and just print an entire list of them instead of/or in addition to the response already being given from the server.
Here is my request:
from suds.client import Client
import logging
# Specify Login Information
developer_key = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
password = 'xxxxxxxx'
account_guid = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
sku = ['A30938', 'B84727']
# Specify URLs
wsdl_url = 'https://api.channeladvisor.com/ChannelAdvisorAPI/v6/InventoryService.asmx?WSDL'
service_url = 'https://api.channeladvisor.com/ChannelAdvisorAPI/v6/InventoryService.asmx'
# Initialize client.
client = Client(wsdl_url, location = service_url)
# Pass login information
login = client.factory.create('APICredentials')
login.DeveloperKey = developer_key
login.Password = password
client.set_options(soapheaders=login)
# Initiate request
for i in sku:
result = client.service.GetInventoryItemImageList(account_guid, i)
# Print the result to the screen.
print result
And here is the results:
(APIResultOfArrayOfImageInfoResponse){
Status = "Success"
MessageCode = 0
ResultData =
(ArrayOfImageInfoResponse){
ImageInfoResponse[] =
(ImageInfoResponse){
PlacementName = "ITEMIMAGEURL1"
FolderName = None
Url = "d3t71aa9ase5oz.cloudfront.net/12801479/images/bear_white.jpg"
},
(ImageInfoResponse){
PlacementName = "ITEMIMAGEURL2"
FolderName = None
Url = "d3t71aa9ase5oz.cloudfront.net/12801479/images/bear_black.jpg"
},
}
}
(APIResultOfArrayOfImageInfoResponse){
Status = "Success"
MessageCode = 0
ResultData =
(ArrayOfImageInfoResponse){
ImageInfoResponse[] =
(ImageInfoResponse){
PlacementName = "ITEMIMAGEURL1"
FolderName = None
Url = "http://d3t71aa9ase5oz.cloudfront.net/12801479/images/m89851.jpg"
},
}
}
Just iterate through the items and get the attribute you want. Something like:
for item in response:
for data in item.ResultData:
print data.Url

Python, suds, manage array answer

I'm using suds library to fetch a list of products from a webservice.
This is a sample code:
from suds.client import Client
url = 'WSDLURL'
client = Client(url)
result = client.service.Research('value')
Result contains:
(ArrayOfProducts){
Product[] =
(Product){
Id = 218
Code = "C024"
Name = "test2"
Avaiable = True
UrlDownload = None
MetaData =
(ArrayOfMetaData){
MetaData[] =
(MetaData){
CoderepositoryISO = "16701"
Title = "1ST"
},
}
},
(Product){
Id = 219
Code = "C025"
Name = "test3"
Avaiable = True
UrlDownload = None
MetaData =
(ArrayOfMetaData){
MetaData[] =
(MetaData){
CoderepositoryISO = "16702"
Title = "2ND"
},
}
},
...
There is a way, in python or suds, to access directly to the contained data cycling on the products with a for? (e.g.: Product.Id, Product.Code, etc.)
Perfect... Thanks to J.F. Sebastian I find the right way...
This is the working code:
from suds.client import Client
url = 'wsdl'
client = Client(url)
html_out = ""
result = client.service.Research('a')
for p in result.Product:
print p.Id
print p.Name

Categories

Resources