Azure Translator batch translate document problem - azure

I'm experiencing this error - ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
I have given the right key and endpoint for my Translator and the Storage account SAS URLs for the source and target containers but for some reason I'm still having this issue. (I'm following the instructions on the azure translator docs for the document batch translation.)
The code is below.
import requests
endpoint = "https://cb-translator.cognitiveservices.azure.com/translator/text/batch/v1.0"
key = '67a1fe4288d140b3b76b5419dfca8d30'
path = '/batches'
constructed_url = endpoint + path
payload= {
"inputs": [
{
"source": {
"sourceUrl": "https://cbtranslatorstorage.blob.core.windows.net/sourcedocs?sp=rl&st=2022-08-30T08:55:52Z&se=2022-08-30T16:55:52Z&spr=https&sv=2021-06-08&sr=c&sig=DuSh20d9LX3iOAt6Tmrgpv39LHX7IKfIbSj0TjMyxXA%3D"
},
"targets": [
{
"targetUrl": "https://cbtranslatorstorage.blob.core.windows.net/translateddocs?sp=rwl&st=2022-08-30T08:57:23Z&se=2022-08-30T16:57:23Z&spr=https&sv=2021-06-08&sr=c&sig=NyyrHbMpUr2NzHD0y2q2RTPYPDcOFhRHT%2BgpI1%2F7KOU%3D",
"language": "en"
}
]
}
]
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/json'
}
response = requests.post(constructed_url, headers=headers, json=payload)
print(f'response status code: {response.status_code}\nresponse status: {response.reason}\nresponse headers: {response.headers}')

Related

Microsoft Graph add row into sharepoint excel file (The argument is invalid or missing or has an incorrect format)

So I am trying to add a row of data into an excel file via the microsoft graph API.
I was able to successfully set up the authentication and get tokens, read the excel file, etc.
I was also able to run the request to add a new row via Microsoft's graph explorer tool and it worked there perfectly, adding the row via postman and microsoft graph api worked fine.
https://developer.microsoft.com/en-us/graph/graph-explorer
Example request: https://graph.microsoft.com/v1.0/me/drive/items/${ItemId}/workbook/worksheets/Sheet1/tables/${tableId}/rows/add
This worked perfectly from postman and the graph explorer, but when I tried to do this from my localhost (react OR nodejs) it throws "The argument is invalid or missing or has an incorrect format"
Here is my code for the request
const accessToken = await Providers.globalProvider.getAccessToken({ scopes: ['User.Read', 'Files.ReadWrite'] })
const bearer = `Bearer ${accessToken}`;
let headers = new Headers();
headers.append("Authorization", bearer);
const options = {
method: "POST,
headers: headers,
body: {
"values": [
[
"column1", "column2", "column3"
]
]
}
};
const addResponse = await fetch(SHAREPOINT_URL, secondOptions);
And the error message I receive
{
"error": {
"code": "InvalidArgument",
"message": "The argument is invalid or missing or has an incorrect format.",
"innerError": {
"code": "invalidArgument",
"message": "The argument is invalid or missing or has an incorrect format.",
"date": "2023-02-16T12:53:56",
"request-id": "{request-id}",
"client-request-id": "{client-request-id}"
}
}
}
After some thought I realized the only difference between the postman POST request and my react one was the body object.
The answer was converting the javascript object body to a JSON.stringify(bodyObj). Kind of assumed it would automatically do that, but there it is!
let bodyObj = {
values: [
[
"1", "2", "3"
]
]
}
let options = {
method: "POST",
headers: headers,
body: JSON.stringify(bodyObj),
};
Your code looks good except the fact that you defined const options but in fetch you are passing secondOptions instead of options.
Try to use options
const addResponse = await fetch(SHAREPOINT_URL, options);

Why would a server deny a request?

I am working on a chrome extension that creates an Anki card and adds it to my desk.
Right now am I trying to get the request to work using the Anki API.
For some reason the server is denying my request.
Here is my code (JavaScript) to create a card and send it as a request to the localhost:
async function createCard() {
// Set the Anki API endpoint URL
const baseURL = 'http://localhost:8765';
// Set the Anki API action, version and params
const card = {
"action": "addNote",
"version": 6,
"params": {
"note": {
"deckName": "Default",
"modelName": "Basic",
"fields": {
"Front": "front content",
"Back": "back content"
},
"options": {
"allowDuplicate": false,
"duplicateScope": "deck",
"duplicateScopeOptions": {
"deckName": "Default",
"checkChildren": false,
"checkAllModels": false
}
}
}
}
};
// Send the request to the Anki API
try {
const response = await fetch(baseURL, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(card)
});
// Check the status code of the response
if (response.ok) {
console.log('Card created successfully');
} else {
console.error(`Error creating card: ${response.statusText}`);
}
} catch (error) {
console.error(`Error creating card: ${error}`);
}
}
(The card by now is hardcoded.)
When I execute this code I get 2 errors thrown by chrome:
POST http://localhost:8765/ net::ERR_ABORTED 403 (Forbidden)
Error creating card:
The first error happens on the fetch function
and the second error at "console.error('Error creating card: ${response.statusText}');"
I suggest that the second error appears due to the first one.
Since I am new to computer science, all I tried so far is checking the logs of ANKI to find information about the error, but I couldn't find something. I tried different syntax to create the card since I pass this into the fetch function where the error occurs.
The localhost is running while I am working on this, so the server is accessible.
My solution is setting the webCorsOriginList config of AnkiConnect as "*"
"webCorsOriginList": ["*"]
It will allow CORS for all domains.

How to trigger airflow dag with REST API (I get "Property is read-only - 'state'", error)

I am trying to trigger airflow dags with REST API. It does not work. I get an ERROR 400 with response:
{
"detail": "Property is read-only - 'state'",
"status": 400,
"title": "Bad Request",
"type": "https://airflow.apache.org/docs/2.0.1/stable-rest-api-ref.html#section/Errors/BadRequest"
}
I tried it via CURL and with Python requests module and results are the same.
Example:
import requests
headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
}
auth = ('test', 'test')
import json
body = {
"conf": {},
"dag_run_id": "string",
"execution_date": "2021-04-15T14:04:43.602Z",
"state": "success"
}
req = requests.post("http://127.0.0.1:8080/api/v1/dags/sleeper/dagRuns",
headers=headers, auth=auth, data=json.dumps(body))
Do I need to specify something in Airflow config or in Dag to make it possible to run it?
Because as I understand there is something with permissions ?
"Property is read-only - 'state'",
Try removing the state key from the body.
i.e.
body = {
"conf": {},
"dag_run_id": "string",
"execution_date": "2021-04-15T14:04:43.602Z"
}
The Airflow REST API docs for that endpoint says state is required in the body, however you shouldn't need to include that in your request. I've tested it locally (Airflow v2.0.1) without state in the body of the request and it appears to work!
Could solve it, with:
import requests
import json
headers = {
'accept': 'application/json',
'Content-Type': 'application/json',
}
auth = ('test', 'test')
body = {
"conf": {},
}
r = requests.post("http://127.0.0.1:8080/api/v1/dags/sleeper/dagRuns",
headers=headers,
auth=auth,
data=json.dumps(body)
)
See link: http://localhost:8080/api/v1/ui/#/DAGRun/post_dag_run

PouchDB basic auth does not work with sync gateway

When I try to sync from PouchDB to couchbase server using sync gateway I am getting following error:
XMLHttpRequest cannot load http://localhost:4984/test/. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
I try to set the header even then I am not able to get rid of this error.
Here is my sync gateway config file
sync-gateway-config.json::
{
"log":["*"],
"databases": {
"buildercycle": {
"server":"http://localhost:8091",
"bucket": "default",
"users": {
"GUEST": {
"disabled": false,
"admin_channels": ["*"]
}
},
"sync":`function(doc, oldDoc) {
if (doc.type == "sports"){
channel(doc.type);
access(doc.owner,doc.type);
} else {
channel(doc.type);
access(doc.owner,doc.type);
}
}`
}
},
"CORS": {
"Origin": ["http://localhost:8000","http://localhost:8083", "http://localhost:4985"],
"LoginOrigin": ["http://localhost:8000","http://localhost:8083","http://localhost:4985"],
"Headers": ["Content-Type"],
"MaxAge": 17280000
}
}
I am trying to sync my PouchDB in following way:
remoteCouch="http://"+user+":"+pass+"#localhost:4984/buildercycle";
console.log(remoteCouch);
var opts = {live: true,withCredentials: true};
db.sync(remoteCouch,opts,'error');
i am passing user(user1) and password(password) which is defined in following sync_gateway admin URL
http://localhost:4985/_admin/db/test/users
I am unable to pin point the error, Please help
Add authorization in headers
"Headers": ["Content-Type","authorization"],
I think cors header is not getting set properly in your case.

Unexpected grunt-http error when posting to Atlassian Confluence api

Attempting to create a wiki page on an Atlassian wiki. I previously was using a python script and this code worked no problem:
data = json.dumps({"type":"page", "data":"testData", "title":postTitle,"space":{"key":"EB"}, "body":{"storage":{"value": content,"representation":"storage"}}})
r = requests.post("https://estech.atlassian.net/wiki/rest/api/content/", data=data, headers=headers, auth=(confluenceLogin['username'], confluenceLogin['password']))
Now I'm trying to use the following grunt task configuration:
http: {
atlassianwiki: {
options: {
uri: atlassianURL + "/wiki/rest/api/content/",
headers: {"Content-Type": "application/json"},
auth: {
"user": confluencelogin,
"pass": confluencepass
},
method:"POST",
body: JSON.stringify(wikijson)
}
}
}
with wikijson looking like:
wikijson = {
"type": "page",
"data": "testData",
"title": "testtitle",
"space": {key:"EB"},
"body": {
"storage": {
"value": "<p>testing posting</p>",
"representation": "storage"
}
}
}
And I get the following error when this task runs:
Fatal error: 500 {"statusCode":500, "message":"java.io.EOFException: No content to map to Object due to end of input"}
Upon a bit of google-fu, I found that some people claim they fixed this by adding "--post302" to their curl command line. But I don't really know or understand how that applies here.
i was fighting with confluence REST API and in my case the problem was in content-type header, but you seem to have it already.
I didn't try to create new page but to update existing one
Confluence API seemed a little bit magic to me, so i just leave here all steps i had to make before it started working, maybe one of them will help you.
function composeRequest(method) {
var auth = new Buffer(user + ':' + pass).toString('base64');
var request = {
host: 'confluence.myserver.com',
port: 443,
contentType: "application/json; charset=utf-8",
'path': path,
method: method || "GET",
headers: {
'Authorization': 'Basic ' + auth,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
requestCert: true,
agent: false
};
return request;
}
And it appeared that page update request JSON MUST contain
pageId (even it is inside path, you need to repeat it)
type
title
version (it's weird, but you should set it. 0 or 1, i don't remember)
And when your data if filled, you should convert it to string and fill content-type field in your request!
data = JSON.stringify(data);
request.headers['Content-Length'] = data.length;
https.request(request, respondHandler)

Resources