I have struggled with gettting bad response while I request POST method in Python.
API DOCS : https://docs.wemix.com/v/en/dapp-developer/api-reference/account-apis#get-wemix-balance-for-a-single-address
For example, body data is like
data = {
'addresses': [
'0xaC45d8b7ED8bDCBaF5F59F4622F9B351CDb9E956',
'0x5b2d775cA52Ad27524e3581980D56694D9E1A83C',
'0xc000250d0CdFb43e2F5C03f6ea73807e0694e795',
'0x501226d260513C4B6f2Ef67B6213AF5A9e3cdC7B',
'0x779a605C753cea01d23D9BB7a5F961A8AF315011',
'0x8FEC9850DAd02AB726b6822927c8B402bC993d58',
'0xeFE753A89B5f1836A44744DF626F5E47eeDa18F7',
'0xf9F20C6dbaF7D70FCEADDDBD13d9Bcb6b66298DA',
'0x290Fa3FE65dF509cb27bA55b493841cB92DA083B',
'0x2ED5972f39109D1818024bF84Ce8F2230c4d99D9',
'0xbed789c6008f788a28fc222c83082d67033daf7f',
'0x1393bba2f90fe4d040bf70c24183dd6e27274de5',
'0xb93de30f956a03d8c597ba0c7a7d08cf4644a571',
'0xf68aed73c86127de4047533da58b419e1aca7c0a'
]
}
I tried to get balance of each addresses.
url = 'https://explorerapi.wemix.com/v1/accounts/balance'
headers = {
'api-key': API_KEY
}
response = requests.get(url, headers=headers, json=data)
But, response is
{'status': '404',
'message': "Maybe you're requesting not supported http method"}
I could get right response when I use Postman.
How can I fix it correctly?
You can try:
import json
url = 'https://explorerapi.wemix.com/v1/accounts/balance'
headers = {
'api-key': '1ba5e446edf1997f67b51bf9e60b3fbba6fa1bf84301115292805d7e24f43539',
'Content-Type': 'application/json', # Mandatory, check documentation
}
response = requests.post(url, headers=headers, data=json.dumps(data))
Output:
>>> response.json()
{'status': '200',
'message': 'success',
'results': {'data': [{'address': '0xaC45d8b7ED8bDCBaF5F59F4622F9B351CDb9E956',
'balance': '50000000000000000000'},
{'address': '0x5b2d775cA52Ad27524e3581980D56694D9E1A83C',
'balance': '50000000000000000000'},
{'address': '0xc000250d0CdFb43e2F5C03f6ea73807e0694e795',
'balance': '50000000000000000000'},
{'address': '0x501226d260513C4B6f2Ef67B6213AF5A9e3cdC7B',
'balance': '50000000000000000000'},
{'address': '0x779a605C753cea01d23D9BB7a5F961A8AF315011',
'balance': '50000000000000000000'},
{'address': '0x8FEC9850DAd02AB726b6822927c8B402bC993d58',
'balance': '50000000000000000000'},
{'address': '0xeFE753A89B5f1836A44744DF626F5E47eeDa18F7',
'balance': '50000000000000000000'},
{'address': '0xf9F20C6dbaF7D70FCEADDDBD13d9Bcb6b66298DA',
'balance': '50000000000000000000'},
{'address': '0x290Fa3FE65dF509cb27bA55b493841cB92DA083B', 'balance': '0'},
{'address': '0x2ED5972f39109D1818024bF84Ce8F2230c4d99D9', 'balance': '0'},
{'address': '0xBEd789c6008F788a28fc222C83082D67033Daf7F',
'balance': '60000000000000000000000000'},
{'address': '0x1393BBA2F90fE4D040Bf70C24183Dd6e27274DE5',
'balance': '783714822540624807922423'},
{'address': '0xb93de30f956A03D8c597Ba0c7A7d08Cf4644a571',
'balance': '499998995799999999958000'},
{'address': '0xF68AEd73c86127dE4047533Da58b419E1AcA7c0A',
'balance': '500000089500000000000000'}]}}
Shortcut:
url = 'https://explorerapi.wemix.com/v1/accounts/balance'
headers = {
'api-key': '1ba5e446edf1997f67b51bf9e60b3fbba6fa1bf84301115292805d7e24f43539',
}
response = requests.post(url, headers=headers, json=data)
Related
So, I had this code and it worked perfectly fine:
def upload_to_imgur(url):
j1 = requests.post(
"https://api.imgur.com/3/upload.json",
headers=headers,
data={
'key': api_key,
'image': b64encode(requests.get(url).content),
'type': 'base64',
'name': '1.jpg',
'title': 'Picture no. 1'
}
)
data = json.loads(j1.text)['data']
return data['link']
Now, I wanted to make all this async, but that doesn't really seem to work. Here's my current code:
async def async_upload_to_imgur(url):
image = await get_as_base64(url)
j1 = await aiohttp.ClientSession().post(
"https://api.imgur.com/3/upload.json",
headers=headers,
data={
'key': api_key,
'image': image,
'type': 'base64',
'name': '1.jpg',
'title': 'Picture no. 1'
}
)
data = await j1.json()
return data['link']
The get_as_base64-function is not the issue.
Header and Api Key are the same
This is the output when I print "data" in the second example.
{'data': {'error': {'code': 1001, 'message': 'File was not uploaded correctly', 'type': 'Exception_Logged', 'exception': {}}, 'request': '/3/upload.json', 'method': 'POST'}, 'success': False, 'status': 500}
It has to be the get_as_base64, for 2 reasons -:
1.) It says the file was not uploaded correctly meaning it doesn't support the URL or something like that
2.) I think you need to link a file not a link containing the file in it.
I am having a json data coming through API and i need to print some specific values through it and i am using the code to get the same but its giving me keyerror : results
import json
import requests
headers = {"Content-Type":"application/json","Accept":"application/json"}
r = requests.get('API', headers=headers)
data=r.text
parse_json=json.loads(data)
for result in parse_json['results']:
for cpu in result['cpumfs']:
print(cpu.get('pct_im_utilization'))
Below is the json data :
{'d': {'__count': '0', 'results': [{'ID': '6085', 'Name': 'device1', 'DisplayName': None, 'DisplayDescription': None, 'cpumfs': {'results': [{'ID': '6117', 'Timestamp': '1649157300', 'DeviceItemID': '6085', 'pct_im_Utilization': '4.0'}, {'ID': '6117', 'Timestamp': '1649157600', 'DeviceItemID': '6085', 'pct_im_Utilization': '1.0'}, {'ID': '6117', 'Timestamp': '1649157900', 'DeviceItemID': '6085', 'pct_im_Utilization': '4.0'}, {'ID': '6117', 'Timestamp': '1649158200', 'DeviceItemID': '6085', 'pct_im_Utilization': '1.0'},
I need to get printed Name of the device ,Timestamp,pct_im_utlization
Am having a problem passing a CSV file that has been converted to a dict file in a post request as a payload in Python. But when I print the payload I got the expected dictionary output but when I now pass the payload as data I got an error that Error: too many values to unpack (expected 2)".
What does this mean . Below is a snapshot of my code:
import requests, json, csv
url = "https://192.168.15.4/web_api/v1.6.1/login"
payload= "{\r\n \"user\" : \"admin\",\r\n \"password\" : \"****\"\r\n}"
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload, verify=False)
response_dict = json.loads(response.text)
session_id = response_dict['sid']
print(response_dict['sid'])
url = "https://192.168.15.4/web_api/v1.6.1/publish"
payload="{ }"
headers = {
'Content-Type': 'application/json',
'X-chkp-sid': session_id
}
response = requests.request("POST", url, headers=headers, data=payload, verify=False)
data = open("C:/Users/OdedinaP/Python_Learning/Add-Multi-Host/add_mutli_host.csv")
csv_reader = csv.DictReader(data)
csv_data = list(csv_reader)[0:20]
csvJson_data = json.dumps(csv_data)
for row in csv_data:
csvJson_data = {json.dumps(csv_data)}
payload = (csv_data)
headers = {
'Content-Type': 'application/json',
'X-chkp-sid': session_id
}
#print(payload)
url = "https://192.168.15.4/web_api/v1.6.1/add-host"
response = requests.request("POST", url, headers=headers, data=payload, verify=False)
print(response.text)
When I comment out the last two lines and uncomment the print(payload) I got the expected output for the payload below:
[{'name': 'PC1', 'ip-address': '192.168.10.1', 'color': 'Yellow'},
{'name': 'PC2', 'ip-address': '192.168.10.2', 'color': 'Yellow'},
{'name': 'PC3', 'ip-address': '192.168.10.3', 'color': 'Yellow'},
{'name': 'PC4', 'ip-address': '192.168.10.4', 'color': 'Yellow'},
{'name': 'PC5', 'ip-address': '192.168.10.5', 'color': 'Yellow'},
{'name': 'PC6', 'ip-address': '192.168.10.6', 'color': 'Yellow'},
{'name': 'PC7', 'ip-address': '192.168.10.7', 'color': 'Yellow'},
{'name': 'PC8', 'ip-address': '192.168.10.8', 'color': 'Yellow'},
{'name': 'PC9', 'ip-address': '192.168.10.9', 'color': 'Yellow'},
{'name': 'PC10', 'ip-address': '192.168.10.10', 'color': 'Yellow'},
{'name': 'PC11', 'ip-address': '192.168.10.11', 'color': 'Yellow'},
{'name': 'PC12', 'ip-address': '192.168.10.12', 'color': 'Yellow'},
{'name': 'PC13', 'ip-address': '192.168.10.13', 'color': 'Yellow'},
{'name': 'PC14', 'ip-address': '192.168.10.14', 'color': 'Yellow'},
{'name': 'PC15', 'ip-address': '192.168.10.15', 'color': 'Yellow'},
{'name': 'PC16', 'ip-address': '192.168.10.16', 'color': 'Yellow'},
{'name': 'PC17', 'ip-address': '192.168.10.17', 'color': 'Yellow'},
{'name': 'PC18', 'ip-address': '192.168.10.18', 'color': 'Yellow'},
{'name': 'PC19', 'ip-address': '192.168.10.19', 'color': 'Yellow'},
{'name': 'PC20', 'ip-address': '192.168.10.20', 'color': 'Yellow'}]
I'm making bots. I tried every thing and this my code:
def send_photo(chat_id, location , reply_markup=None):
url = URL + "sendPhoto?chat_id={}&photo={}".format(chat_id,open('1.jpg', 'rb'))
if reply_markup:
url += "&reply_markup={}".format(reply_markup)
print(get_url(url))
get_url(url)
My file is in my .py folder and I double checked every thing, I even used photo telegram id's and url's and I'm still getting:
{"ok":false,"error_code":400,"description":"Bad Request: wrong URL host"}
#https://core.telegram.org/bots/api#sendphoto
import requests
import json
token = 'Token'
def send_photo(chat_id, photo, caption='', parse_mode=None, disable_notification=False, reply_to_message_id=0, reply_markup=None):
with open(photo, 'rb') as file:
response = requests.post(
'https://api.telegram.org/bot{token}/sendPhoto?'.format(token=token),
data={
'chat_id':chat_id, #Integer or String
'caption':caption, #String
'parse_mode': parse_mode, #String https://core.telegram.org/bots/api#formatting-options
'disable_notification': disable_notification, #Boolean
'reply_to_message_id': reply_to_message_id, #Integer
'reply_markup': json.dumps(reply_markup) if reply_markup is not None else reply_markup, #List
},
files={
'photo': file.read()
}
)
file.close()
if response.status_code == 200:
return json.loads(response.text)
reply_markup = {
'inline_keyboard':[
[
{'text':'stackoverflow', 'url':'https://stackoverflow.com'}
]
]
}
print(send_photo('802959264', 'test.png', caption='caption', reply_markup=reply_markup))
This is the output
{'ok': True, 'result': {'message_id': 10, 'from': {'id': 1157936984, 'is_bot': True, 'first_name': 'test', 'username': 'RoomSupervisorBot'}, 'chat': {'id': 802959264, 'firs
t_name': 'milad', 'username': 'milad_dev', 'type': 'private'}, 'date': 1597892647, 'photo': [{'file_id': 'AgACAgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_oAtOUhUwAArO0MRuwP_BR0owk2ZSqQ
RdwWPEiXQADAQADAgADbQADaNoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2jaBAAB', 'file_size': 8226, 'width': 320, 'height': 180}, {'file_id': 'AgACAgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_
oAtOUhUwAArO0MRuwP_BR0owk2ZSqQRdwWPEiXQADAQADAgADeAADadoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2naBAAB', 'file_size': 35836, 'width': 800, 'height': 450}, {'file_id': 'AgAC
AgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_oAtOUhUwAArO0MRuwP_BR0owk2ZSqQRdwWPEiXQADAQADAgADeQADatoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2raBAAB', 'file_size': 78830, 'width': 1280, '
height': 720}, {'file_id': 'AgACAgQAAxkDAAMKXz3oJ8X-3jkfsP8GgT_oAtOUhUwAArO0MRuwP_BR0owk2ZSqQRdwWPEiXQADAQADAgADdwADZtoEAAEbBA', 'file_unique_id': 'AQADcFjxIl0AA2baBAAB', 'fil
e_size': 88002, 'width': 1366, 'height': 768}], 'caption': 'caption', 'reply_markup': {'inline_keyboard': [[{'text': 'stackoverflow', 'url': 'https://stackoverflow.com'}]]}}}
Kindly use http url instead of local,
It will work else
upload the file first and then get the file_id
then send that file id to the bot.
Am trying to play with Vision API(analyze an image) of Microsoft Cognitive Services. Am wondering how to send a local image through rest API calls to Vision API and request for the results from it using Python. Can anyone help me with this please?
The Testing opting provided by Microsoft on their site only takes URL, I Tried to convert my local path to URL and give it as input but that doesn't work.
You can see the full code here: https://github.com/miparnisari/Cognitive-Vision-Python/blob/master/Jupyter%20Notebook/Computer%20Vision%20API%20Example.ipynb
But the gist of it:
import requests # pip3 install requests
region = "YOUR-API-REGION" #For example, "westus"
api_key = "YOUR-API-KEY"
path_to_file = "C:/Users/mparnisari/Desktop/test.jpg"
# Read file
with open(path_to_file, 'rb') as f:
data = f.read()
# Set request headers
headers = dict()
headers['Ocp-Apim-Subscription-Key'] = api_key
headers['Content-Type'] = 'application/octet-stream'
# Set request querystring parameters
params = {'visualFeatures': 'Color,Categories,Tags,Description,ImageType,Faces,Adult'}
# Make request and process response
response = requests.request('post', "https://{}.api.cognitive.microsoft.com/vision/v1.0/analyze".format(region), data=data, headers=headers, params=params)
if response.status_code == 200 or response.status_code == 201:
if 'content-length' in response.headers and int(response.headers['content-length']) == 0:
result = None
elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str):
if 'application/json' in response.headers['content-type'].lower():
result = response.json() if response.content else None
elif 'image' in response.headers['content-type'].lower():
result = response.content
print(result)
else:
print("Error code: %d" % response.status_code)
print("Message: %s" % response.json())
This will print something like this:
{
'categories': [{
'name': 'others_',
'score': 0.0078125
}, {
'name': 'outdoor_',
'score': 0.0078125
}, {
'name': 'people_',
'score': 0.4140625
}],
'adult': {
'isAdultContent': False,
'isRacyContent': False,
'adultScore': 0.022686801850795746,
'racyScore': 0.016844550147652626
},
'tags': [{
'name': 'outdoor',
'confidence': 0.9997920393943787
}, {
'name': 'sky',
'confidence': 0.9985970854759216
}, {
'name': 'person',
'confidence': 0.997259259223938
}, {
'name': 'woman',
'confidence': 0.944902777671814
}, {
'name': 'posing',
'confidence': 0.8417303562164307
}, {
'name': 'day',
'confidence': 0.2061375379562378
}],
'description': {
'tags': ['outdoor', 'person', 'woman', 'snow', 'posing', 'standing', 'skiing', 'holding', 'lady', 'photo', 'smiling', 'top', 'wearing', 'girl', 'mountain', 'sitting', 'young', 'people', 'sun', 'slope', 'hill', 'man', 'covered', 'umbrella', 'red', 'white'],
'captions': [{
'text': 'a woman posing for a picture',
'confidence': 0.9654204679303702
}]
},
'metadata': {
'width': 3264,
'height': 1836,
'format': 'Jpeg'
},
'faces': [{
'age': 26,
'gender': 'Female',
'faceRectangle': {
'left': 597,
'top': 2151,
'width': 780,
'height': 780
}
}],
'color': {
'dominantColorForeground': 'White',
'dominantColorBackground': 'White',
'dominantColors': ['White', 'Grey'],
'accentColor': '486E83',
'isBWImg': False
},
'imageType': {
'clipArtType': 0,
'lineDrawingType': 0
}
}