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'}]
Related
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)
Let say, I have a list data for example:
data = [
{'id': 1, 'name': 'brad', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}},
{'id': 2, 'name': 'sylvia', 'color': 'blue', 'tags': [], 'author': {'name': 'user'}},
{'id': 3, 'name': 'sylwia', 'color': 'green', 'tags': [], 'author': {'name': 'admin'}},
{'id': 4, 'name': 'shane', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}},
{'id': 5, 'name': 'shane', 'color': 'red', 'tags': ['python', 'django'], 'author': {'name': 'user'}}
]
and I want to make it ORM'able, such as what Django has doing:
ModelName.objects.filter(color__icontains="gree")
And this what I have do;
import operator
from collections import namedtuple
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
class DataQuerySet:
"""
Custom ORM for List dict data,
https://stackoverflow.com/a/58351973/6396981
"""
allowed_operations = {
'gt': operator.gt,
'lt': operator.lt,
'eq': operator.eq,
'icontains': operator.contains
}
def __init__(self, data):
self.data = data
def all(self):
return self.data
def filter(self, **kwargs):
"""
>>> kwargs = {'name': 'sylwia', 'id__gt': 1}
>>> DataQuerySet().filter(**kwargs)
[{'id': 3, 'name': 'sylwia', 'color': 'green'}]
"""
operation = namedtuple('Q', 'op key value')
def parse_filter(item):
"""item is expected to be a tuple with exactly two elements
>>> parse_filter(('id__gt', 2))
Q(op=<built-in function gt>, key='id', value=2)
>>> parse_filter(('id__ ', 2))
Q(op=<built-in function eq>, key='id', value=2)
>>> parse_filter(('color__bad', 'red'))
Traceback (most recent call last):
...
AssertionError: 'bad' operation is not allowed
"""
key, *op = item[0].split('__')
# no value after __ means exact value query, e.g. name='sylvia'
op = ''.join(op).strip() or 'eq'
assert op in self.allowed_operations, f'{repr(op)} operation is not allowed'
return operation(self.allowed_operations[op], key, item[1])
filtered_data = self.data.copy()
for item in map(parse_filter, kwargs.items()):
filtered_data = [
entry for entry in filtered_data
if item.op(entry[item.key], item.value)
]
return filtered_data
def get(self, **kwargs):
"""
>>> DataQuerySet().get(id=3)
[{'id': 3, 'name': 'sylwia', 'color': 'green'}]
"""
operation = namedtuple('Q', 'op key value')
def parse_get(item):
key, *op = item[0].split('__')
return operation(self.allowed_operations['eq'], key, item[1])
filtered_data = self.data.copy()
for item in map(parse_get, kwargs.items()):
filtered_data = [
entry for entry in filtered_data
if item.op(entry[item.key], item.value)
]
if len(filtered_data) > 1:
raise MultipleObjectsReturned(filtered_data)
elif len(filtered_data) < 1:
raise ObjectDoesNotExist(kwargs)
return filtered_data[0]
And to use it:
class DataModel:
def __init__(self, data):
self._data = DataQuerySet(data)
#property
def objects(self):
return self._data
data = [
{'id': 1, 'name': 'brad', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}},
{'id': 2, 'name': 'sylvia', 'color': 'blue', 'tags': [], 'author': {'name': 'user'}},
{'id': 3, 'name': 'sylwia', 'color': 'green', 'tags': [], 'author': {'name': 'admin'}},
{'id': 4, 'name': 'shane', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}},
{'id': 5, 'name': 'shane', 'color': 'red', 'tags': ['python', 'django'], 'author': {'name': 'user'}}
]
d = DataModel(data)
print(d.objects.filter(id__gt=2))
print(d.objects.filter(color='green'))
print(d.objects.filter(color__icontains='gree'))
print(d.objects.get(id=1))
Above tests is just work properly, but seems we have a problem when we want to do more:
print(d.objects.filter(tags__in=['python']))
print(d.objects.filter(author__name='admin'))
print(d.objects.filter(author__name__icontains='use'))
Finally, I found a nice module to handle that case, it called with reobject, and here is the test:
from reobject.models import Model, Field
from reobject.query.parser import Q as Query
data = [
{'name': 'brad', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}},
{'name': 'sylvia', 'color': 'blue', 'tags': [], 'author': {'name': 'user'}},
{'name': 'sylwia', 'color': 'green', 'tags': [], 'author': {'name': 'admin'}},
{'name': 'shane', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}},
{'name': 'shane', 'color': 'red', 'tags': ['python', 'django'], 'author': {'name': 'user'}}
]
class Book(Model):
name = Field()
color = Field()
tags = Field()
author = Field()
for item in data:
Book(**item)
Book.objects.all()
Book.objects.get(name='brad')
Book.objects.filter(name='brad')
Book.objects.filter(author__name='admin')
Book.objects.filter(tags__contains='python')
Book.objects.filter(Query(author__name='admin') | Query(author__name='user'))
Meanwhile, it still doesn't support with id or pk fields.
Mybe because it already taken.
js part
$('#btnUpdate').click(function(){
var formData = JSON.stringify($("#contrast_rule_set").serializeArray());
$.ajax({
type: "POST",
url: "./contrast_rule_set",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
})
python part
#app.route('/get_test', methods=['GET','POST'])
def get_test():
web_form_data = request.json
print(web_form_data)
print(type(web_form_data))
print(jsonify(web_form_data))
print(json.dumps(web_form_data))
python print console like
[{'name': 'logic_1', 'value': '1'}, {'name': 'StudyDescription_1', 'value': ''}, {'name': 'SeriesDescription_1', 'value': 'C\\+'}, {'name': 'ImageComments_1', 'value': ''}, {'name': 'logic_2', 'value': '1'}, {'name': 'StudyDescription_2', 'value': '\\-C'}, {'name': 'SeriesDescription_2', 'value': '\\-C'}, {'name': 'ImageComments_2', 'value': '\\-C'}, {'name': 'logic_3', 'value': '1'}, {'name': 'StudyDescription_3', 'value': ''}, {'name': 'SeriesDescription_3', 'value': '\\+C'}, {'name': 'ImageComments_3', 'value': '\\+C'}]
<class 'list'>
how to get list to json data type (or converter ) (html side code adjust or python side code adjust? )
then hope to get data like json type (data is from my another json file )
{
'Logic': 'AND',
'StudyDescription': '',
'SeriesDescription': 'C\+',
'ImageComments': ''
},
{
'Logic': 'NOT',
'StudyDescription': '\-C',
'SeriesDescription': '\-C',
'ImageComments': '\-C'
},
{
'Logic': 'AND',
'StudyDescription': '',
'SeriesDescription': '\+C',
'ImageComments': '\+C'
}
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
}
}