python - aiohttp.ClientSession().post - python

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.

Related

How to applying POST method using Python?

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)

Process JSON Responses, Editing and Sending

I am working with an API. I get a response from the API which looks like this:
from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url, auth=auth)
client = OAuth2Session(client_id, token=token, auto_refresh_url=token_url,token_updater=token_saver)
token_saver = []
device_policy = client.get('{URL}/v1?ids='+ids)
I get this response
[{'id': '',
'name': 'A Name',
'description': '',
'platform_name': 'Windows',
'groups': [],
'enabled': True,
'created_by': 'An Email',
'created_timestamp': '2019-03-28T12:51:30.989736386Z',
'modified_by': 'An Email ,
'modified_timestamp': '2019-11-19T21:14:53.0189419Z',
'settings': {'enforcement_mode': 'MONITOR_ENFORCE',
'end_user_notification': 'SILENT',
'classes': [{'id': 'ANY', 'action': 'FULL_ACCESS', 'exceptions': []},
{'id': 'IMAGING', 'action': 'FULL_ACCESS', 'exceptions': []},
{'id': 'MASS_STORAGE', 'action': 'BLOCK_ALL', 'exceptions': []},
{'id': 'MOBILE', 'action': 'BLOCK_ALL', 'exceptions': []},
{'id': 'PRINTER', 'action': 'FULL_ACCESS', 'exceptions': []},
{'id': 'WIRELESS', 'action': 'BLOCK_ALL', 'exceptions': []}]}}]
In each class there is list for hold exceptions. The API accepts a patch (not really a patch) that if this data is resubmitted with the exception field holding the contents of this function then an exception is accepted.
`
file_info = {
"class": "ANY",
"vendor_name": "",
"product_name": "",
"serial_number": serial_number,
"combined_id": "",
"action": "FULL_ACCESS",
"match_method": "VID_PID_SERIAL"
}
`
The challenge I have is accepting the first document and then adding the exception material to create a this patch request. I can "walk" the document but cannot work how to create a new body text to send. I think I want to do something like this but not using append as this throws an error.
new_walk_json = walk_json.append(['classes'][0]['exceptions']['Test'])
Realised .update function can used.

Telegram wrong URL host

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.

How to send a local image instead of URL to Microsoft Cognitive Vision API(analyze an image) using Python?

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
}
}

Send location ( lat & long ) to API AI

I'm using API AI to make a Facebook bot. After sharing my location in Facebook chat bot. I got a JSON like this:
{'message': {'attachments': [{'payload': {'coordinates': {'lat': 52.335001190772,'long': 4.8887078680234}},'title': 'Holiday Inn','type': 'location','url': 'https://www.facebook.com/l.php?u=https%3A%2F%2Fwww.bing.com%2Fmaps%2Fdefault.aspx%3Fv%3D2%26pc%3DFACEBK%26mid%3D8100%26where1%3DDe%2BBoelelaan%2B2%252C%2B1083%2BHJ%2BAmsterdam%252C%2BNetherlands%26FORM%3DFBKPL1%26mkt%3Den-US&h=mAQEt4NIX&s=1&enc=AZN97DQxpVq5xpkZqvgi3bMq2OVJNwWBOXOiIOW4FHx1-kgYHxTPKfFwRkUsl0ibr0K5GAquaEltxBMLGvjxmUbCa1AmptlN85rg4jLhDH6K0g'}],
According to that JSON, I have lat and long value:
payload = message['message']['attachments'][0]['payload']
lat = payload['coordinates']['lat']
long = payload['coordinates']['long']
What I want is to send those values to parameters in API AI. So I wrote a method to post that:
def post_location(self, text, lat, long):
return self.get(
params={
'query': text,
'parameters': {
'latitude': lat,
'longitude': long,
},
'lang': 'en'
}
)
And this is how my get looks like:
def get(self, params):
"""
Get connection with api ai
:rtype: object
"""
print(params)
request = requests.get(
url=self.url, params=params, headers=self.headers)
content = request.content.decode('utf-8')
try:
return json.loads(content)
except ValueError:
print('Invalid JSON')
Finally I call post_location method where I handle the facebook message and give it the values but when I run, only the text ( query ) is sent to API AI.
def _post_location_to_api(message, lat, long):
ai_api = AIApi()
return ai_api.post_location(message, lat, long)
location = _post_location_to_api(message['message']['attachments'][0]['type'], latitude, longitude)
print(location) gives me this:
{'id': 'd4374511-86ce-4ccb-b7b3-e813011a0998', 'sessionId': '00000000-0000-0000-0000-000000000000', 'timestamp': '2016-10-04T11:26:11.613Z', 'result': {'action': 'PlaceSearch', 'actionIncomplete': False, 'score': 0.51, 'contexts': [], 'fulfillment': {'speech': ''}, 'parameters': {'latitude': '', 'longitude': ''}, 'source': 'agent', 'resolvedQuery': 'location', 'metadata': {'intentName': 'I want to eat in Amsterdam', 'intentId': '89f515a6-f723-4df5-96b2-9e0f784747c6', 'webhookUsed': 'true', 'warning': 'IMPORTANT: Please use unique session ID for each client. Otherwise you may experience unstable behaviour.'}}, 'status': {'errorDetails': 'Webhook call failed. Status code 404. Error:404 Not Found', 'errorType': 'partial_content', 'code': 206}}
What did I do wrong?

Categories