southeastasia.api.cognitive.microsoft.com not working - azure-cognitive-services

import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.parse.urlencode({
# Request parameters
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': '{string}',
'recognitionModel': 'recognition_01',
'returnRecognitionModel': 'false',
})
try:
conn =http.client.HTTPSConnection('southeastasia.api.cognitive.microsoft.com')
conn.request("POST", "/face/v1.0/detect?%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))
The above code is not working.
I gave correct 1key1 value
I am getting:
[Errno 11002] getaddrinfo failed

Related

FastAPI and Axios POST request misconfiguration

I have a FastAPI backend configured as such:
#app.post("/engines/completions")
async def read_completions(
# engine_id:str,
prompt: Optional[str] = None,
max_tokens: Optional[int] = 16,
temperature: Optional[float] = 1.0,
top_p: Optional[float] = 1.0,
top_k: Optional[int] = 40,
n: Optional[int] = 1,
stream: Optional[bool] = False,
logprobs: Optional[int] = None,
echo: Optional[bool] = False,
stop: Optional[list] = None,
presence_penalty: Optional[float] = 0.0001,
frequency_penalty: Optional[float] = 0.0001,
best_of: Optional[int] = 1,
recursive_depth: Optional[int] = 0,
recursive_refresh: Optional[int] = 0,
logit_bias: Optional[Dict[str, float]] = None,
):
and an Axios request configured like this:
let stop = "stuff";
let prompt ="test";
let url = "http://localhost:8000/engines/completions";
const options = {
method: "POST",
headers: { "content-type": "application/json"},
timeout: 2000000,
body: {stop, prompt},
url,
};
axios(options)
My request goes through without getting a 442 error, but prompt and stop attributes would result in None in my read_completions function. What am I doing wrong?
Use data instead of body on your axios' options.
See Request Config on axios documentation,
My request will go through without a 442
Your request goes through, as all parameters are defined as optional. Thus, not receiving these parameters, the server won't complain.
but prompt and stop will evaluate as None in my read_completions
function.
They are both None (null), as the server never received any values for them. Your endpoint expects these parameters being Query parameters, however, your client sends (or actually, attempts to send) body parameters.
Option 1
Adjust your endpoint to expect Form data. Also, if you are going to define a parameter to be a List, please have a look at this on how to do that properly.
from typing import Optional, List
#app.post("/engines/completions")
def read_completions(
prompt: Optional[str] = Form(None),
stop: Optional[List[str]] = Form(None)
):
return {"prompt": prompt, "stop list": stop}
Then, your client side should look like this:
function uploadFormData() {
var formData = new FormData();
var alphaArray = ['A', 'B', 'C','D','E'];
for (var i = 0; i < alphaArray.length; i++) {
formData.append('stop', alphaArray [i]);
}
formData.append("prompt", "test");
axios({
method: 'post',
url: '/engines/completions',
data: formData,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
Option 2
Adjust your endpoint to expect JSON (body) parameters. In FastAPI, you could do that using either Body parameters or Pydantic models. The example below uses the latter.
from pydantic import BaseModel
from typing import Optional, List
class Item(BaseModel):
prompt: str = None
stop: Optional[List[str]] = None
#app.post("/engines/completions")
def read_completions(item: Item):
return {"prompt": item.prompt, "stop list": item.stop}
Finally, the client side should look like the below:
function uploadJSONdata() {
axios({
method: 'post',
url: '/engines/completions',
data: JSON.stringify({"prompt": "test", "stop": ['A', 'B', 'C','D','E']}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}

Lua: How to parse http post result?

I am writing a http client in lua to consume a rest web service.
The webservice result should be in this json format:
{
"code": "123456789",
"valid_until": "09/09/2020"
}
This is my lua script:
param_1 = arg[1];
param_2 = arg[2];
http = require("socket.http");
ltn12 = require("ltn12");
path = "http://www.url.com:8080/api/";
body = [[ {"number_id":"b8ce37fb-2061-4aea-975b-57a8e2d355ce","param_1":"]]..param_1..[[","param_2":"]]..param_2..[["} ]];
response_body = { }
res, code, response_haders, status = http.request {
url = path,
method = "POST",
headers =
{
["X-Access-Key"] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
["Content-Type"] = "application/json",
["Content-Length"] = body:len()
},
source = ltn12.source.string(body),
}
print("res:"..res);
print("code:"..code);
print("status:"..status);
when I run my script this is the results I got:
res:1
code:201
statusHTTP/1.0 201 CREATED
Why I getting 1 as result, What should I do to parse the result?

Python : POST a Multipart-Encoded File

Trying to upload a file using requests module, but encountered Internal Server Error Its the same using poster module too:
import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
files={'file': open(r'Users/.../test.zip', 'rb')}
headers_info = {
'content-type': "multipart/form-data; boundary=---12345",
'x-api-service-version': "1.0",
'connection': "Keep-Alive",
'authorization': "Basic XXXXXXX",
'x-file-format': "decrypted",
'cache-control': "no-cache",
}
response = requests.post(url, data = payload , headers=headers_info , params=querystring , files=files)
print response.status_code
print response.text
I tested the api with POSTMAN (chrome extension to test rest API) and it seems to work fine with postman i get a success response and the file is uploaded.
The postman code for python shows :
import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
headers = {
'content-type': "multipart/form-data; boundary=---12345",
'accept-encoding': "gzip, deflate",
'x-api-service-version': "1.0",
'connection': "Keep-Alive",
'authorization': "Basic XXXXXXX",
'x-file-format': "decrypted",
'cache-control': "no-cache",
'postman-token': "XXXXXXX"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
Any suggestions for the same ? Am I missing something obvious? Thanks for any pointers you can share!
You don't have to specify 'content-type': "multipart/form-data; boundary=---12345", as well as empty data. Try to send request without headers
response = requests.post(url, params=querystring , files=files)
If you fail you might try to add 'authorization': "Basic XXXXXXX", 'postman-token': "XXXXXXX" headers

Hubot with slack adapter - cannot perform rtm.start

I'm trying to have hubot + slack on my local machine.
installed hubot and slack client.
running:
bin\hubot -a slack
and got error (after adding log messages to the script)
INFO Connecting...
INFO { ok: false, error: { [Error: socket hang up] code:
'ECONNRESET' } }
from reading code in node_modules\slack-client\src\client.js
found the problem occurs in a POST request:
Client.prototype.login = function() {
this.logger.info('Connecting...');
return this._apiCall('rtm.start', {
agent: 'node-slack'
}, this._onLogin); };
Client.prototype._apiCall = function(method, params, callback) {
var options, post_data, req;
params['token'] = this.token;
post_data = querystring.stringify(params);
options = {
hostname: this.host,
method: 'POST',
path: '/api/' + method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
req = https.request(options);
tried to do: Node.js POST causes [Error: socket hang up] code: 'ECONNRESET'
with no success

Add timeout to HTTP request in Coffeescript

I need to modify some Coffeescript to include a timeout for HTTP requests. Below is the code. I have tried adding a 'timeout' property to the requestOptions dictionary but no luck!
Below is the code which you can also find on Github (https://github.com/pcrawfor/iap_verifier/blob/master/src/iap_verifier.coffee#L144)
###
verifyReceipt
Verifies an In App Purchase receipt string against Apple's servers
params:
receipt - the receipt string
isBase64 - Is the receipt already encoded in base64? Optional, defaults to false.
cb - callback function that will return the status code and results for the verification call
###
verifyReceipt: (receipt, isBase64, cb) ->
if cb is undefined
cb = isBase64
isBase64 = false
data =
'receipt-data': ""
#verifyWithRetry(data, receipt, isBase64, cb)
###
verifyWithRetry
Verify with retry will automatically call the Apple Sandbox verification server in the event that a 21007 error code is returned.
This error code is an indication that the app may be receiving app store review requests.
###
verifyWithRetry: (receiptData, receipt, isBase64, cb) ->
encoded = null
if isBase64
encoded = receipt
else
buffer = new Buffer(receipt)
encoded = buffer.toString('base64')
receiptData['receipt-data'] = encoded
#verify receiptData, #requestOptions(), (valid, msg, data) =>
# on a 21007 error retry the request for the Sandbox environment (if the current environment is Production)
if (21007 == data.status) && (#productionHost == #host)
# retry...
if #debug then console.log("Retry on Sandbox")
options = #requestOptions()
options.host = #sandboxHost
#verify receiptData, options, (valid, msg, data) ->
if #debug then console.log("STATUS #{data.status}")
cb(valid, msg, data)
else
if #debug then console.log "else"
cb(valid, msg, data)
###
verify the receipt data
###
verify: (data, options, cb) ->
if #debug then console.log("verify!")
post_data = JSON.stringify(data)
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
request = https.request options, (response) =>
if #debug then console.log("statusCode: #{response.statusCode}")
if #debug then console.log("headers: #{response.headers}")
apple_response_arr = []
response.on 'data', (data) =>
if #debug then console.log("data #{data}")
if response.statusCode != 200
if #debug then console.log("error: " + data)
return cb(false, "error", null)
apple_response_arr.push(data)
response.on 'end', () =>
totalData = apple_response_arr.join('')
if #debug then console.log "end: apple response: #{totalData}"
responseData = JSON.parse(totalData)
#processStatus(responseData, cb)
response.on 'timeout', () =>
console.log('timeout')
return cb(false, "error", null)
request.write(post_data)
request.end()
request.on 'error', (err) ->
if #debug then console.log("In App purchase verification error: #{err}")
processStatus: (data, cb) ->
# evaluate status code and take an action, write any new receipts to the database
if #debug then console.log("Process status #{data.status}")
#todo: check status code and react appropriately
response = #responseCodes[data.status]
# Try not to blow up if we encounter an unknown/unexepected status code
unless response
response =
valid: false
error: true
message: "Unknown status code: " + data.status
cb(response.valid, response.message, data)
requestOptions: ->
options =
host: #host
port: #port
path: #path
method: #method
# timeout: 100 // didn't work :(
module.exports = IAPVerifier

Resources