I am trying to upload a video in Video Indexer API using Python:
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'multipart/form-data',
'Ocp-Apim-Subscription-Key': '******************',
}
params = urllib.parse.urlencode({
# Request parameters
'name': 'xxxx',
'privacy': 'Private',
'language': 'English',
})
try:
conn = http.client.HTTPSConnection('videobreakdown.azure-api.net')
conn.request("POST", "/Breakdowns/Api/Partner/Breakdowns?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
But I am not able to specify how to give the video file in the {body} section.
Kindly help me.
This works for me:
import requests
import urllib.parse
import json
headers = {
'Ocp-Apim-Subscription-Key': 'YOUR-API-KEY',
}
form_data = {'file': open('YOUR-VIDEO.mp4', 'rb')}
params = urllib.parse.urlencode({
'name': 'video.mp4',
'privacy': 'Private',
'language': 'English',
})
try:
url = 'https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns?'
r = requests.post(url, params=params, files=form_data, headers=headers)
print(r.url)
print(json.dumps(r.json(), indent=2))
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
Related
I would like to add content type explicity for multipart form data before sending post request
Below is my sample code i managed to add conten type for file data but couldn't figure out how to add content type correctly for json data, i would like to add "application/json; charset=utf-8" for json data
import requests
import json
import traceback
def uploadLogs(fileName):
f = open(fileName, 'rb')
payload = { "var1":"this", "var2" : "that"
}
files = {'file': ('current', f, "text/plain; charset=us-ascii")}
data = {'info': json.dumps(payload)}
headers = {'type': 'myReport', "Keep-Alive": "timeout=100"}
try:
url = "http://localhost:8009/upload"
response = requests.post(url, data=data, files=files, headers=headers)
print(response.request.body)
print(response.request.headers)
print(response.status_code)
if (response != None and (response.status_code == 200 or
response.status_code == 201)):
return True
except:
traceback.print_exc()
return False
filename = "C:\\sample.txt"
print(uploadLogs(filename))
If someone knows how to do please suggest
Trying to get information with post request but it returns RESPONSE [500]. I have tried to use the get response and it returns response 200 code. I copied the form_data from the website and included in my code.
import requests, json
from bs4 import BeautifulSoup as bs
from requests.utils import quote
url = 'https://mpcr.cbar.az/service/mpcr.publicSearchApplication'
tax_ids = [
'1000276532',
]
data = {
'searchFilter': {"fields":"{\"orgTin\":\"%s\"}"},
'compId': 'frontend',
'access_token': '123',
'refresh_token': '123',
'token': '123',
'requestNumber': '1p5i9m5s9T9W8',
'_token': 'MQ2cZyD092qFKknKpZMV0w2ksNhqWj17PSl6iaCG',
}
with requests.Session() as s:
for i in tax_ids:
data["searchFilter"] = quote(json.dumps(data["searchFilter"]["fields"] % i))
print(data)
print("--" * 10)
r = s.post(url, data=data)
print(r)
I am still facing the error in the verification process
{"error":{"code":"BadRequest","message":"SpeakerInvalid"}}'
My audio is correct as it is getting enrolled easily
##code for API CALL speaker verification
import http.client, urllib.request, urllib.parse, urllib.error, base64
subscription_key = 'XXXXXXXXXXXXXXXXXXXXXXX'
headers = {
# Request headers
"Content-Type": 'multipart/form-data',
"Ocp-Apim-Subscription-Key": subscription_key,
}
params = urllib.parse.urlencode({
'verificationProfileId':'445b849b-6418-4443-961b-77bd88196223',
})
#body = {
#}
try:
conn = http.client.HTTPSConnection('speaker-recognition-api.cognitiveservices.azure.com')
body = open('pp.wav','rb') //pp.wav is my audio file
conn.request("POST", "/spid/v1.0/verify?verificationProfileId=445b849b-6418-4443-961b-77bd88196223?%s" % params, body, headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
I could reproduce your problem. You are getting this error cause there is a ? in the end of your url, however behind verify there is already a ?. So if you want to add params to your request url you should use & just like the sample code in this API doc:Speaker Recognition - Verification .
Below is my work code.
try:
conn = http.client.HTTPSConnection('geospeaker.cognitiveservices.azure.com')
body=open("output4.wav","rb")
conn.request("POST", "/spid/v1.0/verify?verificationProfileId=1ae143b0-c301-4345-9295-3e34ad367092?%s" % params, body, headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except OSError as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
I trying work with Poloniex API. And I try get balances via Trading API methods. And I try do it with requests library like this:
import requests
import hmac
import hashlib
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post('https://poloniex.com/tradingApi', data=post_data, headers=headers, timeout=20)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
With this code I always get error with message: "Request: {'error': 'Invalid command.'}". What I do wrong?
From other side code below returns data without any problem! Look at this, please:
import requests
import hmac
import hashlib
import json
import time
import urllib
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
req = urllib.request.Request('https://poloniex.com/tradingApi', data=post_data, headers=headers)
res = urllib.request.urlopen(req, timeout=20)
Ret_data = json.loads(res.read().decode('utf-8'))
print('Request: {0}'.format(Ret_data))
return Ret_data
I using Python 3.6
It's best to let requests handle post data because it creates the appropriate headers. Other than that i don't see anything wrong with your code.
def setPrivateCommand(self):
poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
post_data = urllib.parse.urlencode(poloniex_data).encode()
sig = hmac.new(
str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512
).hexdigest()
headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
polo_request = requests.post(
'https://poloniex.com/tradingApi', data=poloniex_data, headers=headers, timeout=20
)
polo_request = polo_request.json()
print('Request: {0}'.format(polo_request))
return polo_request
Or you could specify the 'Content-Type' in headers if you want to have a string in data, example,
headers = {
'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey'],
'Content-Type': 'application/x-www-form-urlencoded'
}
polo_request = requests.post(
'http://httpbin.org/anything', data=post_data, headers=headers, timeout=20
)
Im trying to get the emotions from a video
Below is my code,
Always when I run this code i get this error
b'{"error":{"code":"BadArgument","message":"Failed to deserialize JSON request."}}' any idea why?
import http.client, urllib.request, urllib.parse, urllib.error, base64, sys
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxx',
}
params = urllib.parse.urlencode({
})
body = "{ 'url': 'http://www.dropbox.com/s/zfmaswf8s9c58om/blog2.mp4' }"
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/emotion/v1.0/recognizeinvideo?%s" % params, "
{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print(e.args)
You forgot to substitute the placeholder {body} with the real thing.
conn.request("POST", "/emotion/v1.0/recognizeinvideo?%s" % params, body, headers)