Server connection and read/write value - python

I want to read write value from a PLC through API (RESTful like) provide by constructor.
First step is authentification
Ajax code
$.ajax({
url: "http://192.168.10.11/sdcard/cpt/app/signin.php",
type: 'POST', dataType: 'json',data: {
'user[name]': 'admin',
'user[password]': 'hellocpt'
}
}).done(function(data) {
console.debug("signin done");
});
Next I can read value from JSON
var url='http://192.168.10.11/sdcard/cpt/app/data_api.php?
url=/app/objects/EasyIO/Ramp.out';
$.ajax(
{url: url, type: 'GET', dataType: 'json'}
).done(function(data) {console.debug(data);});
Response
{
"response" : {
"resultCode" : 0, // '0' for success, other numbers for
failure
"data" : [ // sedona object data is orgnized in list
{ // every object's data is a dictionary
"path" : "/EasyIO/Ramp", //sedona object's path
"slots" : [ //slots data is organized as a list
{
"value" : "49.000000", // 'out' slot's value
"slotType" : "property", // this slot is a
property
"name" : "out", // slot's name"type" : "float" // slot value's data type
}
]
}
]
}
}
Commande
var url = 'http://192.168.10.11/sdcard/cpt/app/data_api.php';
$.ajax({url: url,
type: 'POST',
dataType: 'json',
data: {
path: '/app/objects/EasyIO/WriteIn.in',
type: 'int',
value: '100',
slotType: 'property'
}
}).done(function(data) {
console.debug(data);
});
Response
{
"response" : {
"resultCode" : 0, // '0' for success, other numbers for
failure
"value" : "100", // slot value has been changed to '100'
"type" : "int", // slot data type is 'int'
"path" : "/app/objects/EasyIO/WriteIn.in" //slot's path
}
}
This API documentation
This my python3 code test
import os
import requests
import pycurl
import json
import urllib
from urllib.request import urlopen
headers = {
'X-Requested-With': 'XMLHttpRequest',
}
data = [
('user[name]', 'admin'),
('user[password]', 'hellocpt'),
]
response = requests.post('http://192.168.0.230/sdcard/cpt/app/signin.php', headers=headers, data=data)
print("Code Status du POST: ",response.status_code)
print(response.content)
cookies = {
}
params = (
('url', '/app/objects/EasyIO/Ramp.out'),
)
responseget = requests.get('http://192.168.0.230/sdcard/cpt/app/data_api.php', headers=headers, params=params, cookies=cookies)
print("\n\nCode Status du GET: ",responseget.status_code)
print(responseget.content)
and my output
Code Status du POST: 200
b'{"redirectUrl": "http://192.168.0.230/sdcard/cpt/dashboard/index.php" }'
Code Status du GET: 200
b'{"redirect": "http://192.168.0.230/sdcard/cpt/app/signin.php"}'
My problem is I don't understand why my POST command working but when I make a GET command I see redirection to signin page link. Why there is a logout?
Anyone can help?
Thanks

When you are sending your second request (GET), how will the server know that you have signed in before? The server sends you back something in the first request which you should send back to the server in your second request so the server can authenticate you.
I wasn't able to find out how your API is working using the ajax codes you have posted because the returned data is not shown in the first request but if we assume that the authentication is cookie based then instead of an empty cookie you should replace this line :
cookies = {
}
with this :
cookies = response.cookies
But this is only an example, your API might return a token instead of using cookies or some other type of authentication which is specified in the documentation.
EDIT : I was able to open the pdf file which contains the API documentation and it seems that the authentication is cookie based so the solution should work.

Related

Getting 401 error : "invalid_client" in django-oauth-toolit

I am trying to have an Ouath2 access token based authentication. I am using django-oauth-toolkit for that. I have registered my app on http://localhost:8000/o/applications.
However, When I tried to hit the URL http://localhost:8000/o/token/ from the react-app . I got 401.
Here is my the useEffect hook that I used for calling that URL :
useEffect(() => {
// axios.get("api/tests")
// .then((res)=>{
// setUsers(JSON.stringify(res.data))
// })
fetch("http://localhost:8000/o/token/", {
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: client_id,
client_secret: client_secret
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${btoa(client_id+":"+client_secret)}`}
,
method: "POST"
}).then((res)=>{
console.log(res)
})
}, [])
Will look forward to some comments and solutions.
I got the solution. Actually I was Using the encrypted version of the client secret. I forgot to copy it before saving. Once it is saved the value is encrypted. So it's better to copy it somewhere prior saving it.

Can I get this Python code snippet translated for usage with Axios+Vue?

The code snippet is simply about performing a post request to a machine learning model endpoint and logging out the response if successful.
import urllib.request
import json
import os
import ssl
def allowSelfSignedHttps(allowed):
# bypass the server certificate verification on client side
if allowed and not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
ssl._create_default_https_context = ssl._create_unverified_context
allowSelfSignedHttps(True) # this line is needed if you use self-signed certificate in your scoring service.
# Request data goes here
# The example below assumes JSON formatting which may be updated
# depending on the format your endpoint expects.
# More information can be found here:
# https://learn.microsoft.com/azure/machine-learning/how-to-deploy-advanced-entry-script
data = {
"Inputs": {
"data": [
{
"test_date": "2000-01-01T00:00:00.000Z",
"cough": false,
"fever": 0,
"sore_throat": false,
"shortness_of_breath": 0,
"head_ache": 0,
"age_60_and_above": "example_value",
"gender": "example_value"
}
]
},
"GlobalParameters": {
"method": "predict"
}
}
body = str.encode(json.dumps(data))
url = 'http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score'
api_key = '' # Replace this with the API key for the web service
# The azureml-model-deployment header will force the request to go to a specific deployment.
# Remove this header to have the request observe the endpoint traffic rules
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
print(result)
except urllib.error.HTTPError as error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(error.read().decode("utf8", 'ignore'))
I have tried this, but I keep getting
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score. (Reason: CORS request did not succeed). Status code: (null)."
function predict() {
axios
.post(
"http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score",
{
Inputs: {
data: [
{
cough: S1Val.value,
fever: S2Val.value,
sore_throat: S3Val.value,
shortness_of_breath: S4Val.value,
head_ache: S5Val.value,
age_60_and_above: a1.value,
gender: a2.value,
},
],
},
GlobalParameters: {
method: "predict",
},
},
{
headers: {
"Access-Control-Allow-Orgin": "*",
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
Also note that this endpoint doesn't require any authentication that's why I didn't append an API key to the Bearer when performing the request.

POST to Python Flask server from Node / Express: OSError: Invalid chunk header

I am trying to post some json to a python flask server and am getting the following error:
OSError: Invalid chunk header
header params
let apiParams = {
host: "0.0.0.0",
port: "5000",
path: "/",
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
the post request:
generatePostRequest(apiParams) {
let req = http.request(apiParams, function (res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (body) {
console.log('Body: ' + body);
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
});
return req;
}
let req = this.generatePostRequest(apiParams);
req.write(JSON.stringify({text:"this is only a test"}));
console.log output
Headers: {"content-type":"application/json","content-length":"37","server":"Werkzeug/0.14.1 Python/3.7.0","date":"Fri, 12 Oct 2018 17:46:23 GMT"}
Body: {"message": "Internal Server Error"}
simple get request works
getRequest() {
let res = fetch('http://0.0.0.0:5000')
.then((response) => {
return response.json();
})
.then(function(data){
console.log(data);
return data;
})
.catch(function(e) {
console.log(e);
});
return res;
}
UPDATE
per suggestion in comments below (thank you #robertklep) I updated the following:
let req = this.generatePostRequest(apiParams);
req.write(json);
req.end();
It works now!
When you're using req.write(), Node.js will default to using "chunked transfer encoding", which means that each call to req.write() will send a chunk of data to the HTTP server, preceded by a bytecount.
My guess is that Werkzeug is timing out, because you're not ending the request (so Werkzeug is expecting a new chunk, or an end-of-request, but isn't getting it and at some point it throws an error).
To end the request, you need to explicitly call req.end() when you're done:
let req = this.generatePostRequest(apiParams);
req.write(JSON.stringify({text:"this is only a test"}));
req.end();
Or, if you have a fixed amount of data to send, you can combined req.write and req.end:
let req = this.generatePostRequest(apiParams);
req.end(JSON.stringify({text:"this is only a test"}));

Node JS and Python - POST image from Node JS to Python REST API

I have a Node JS application. I want to send an image from the Node JS application to a REST API which is written in Python. The key and the inputs needed by the Python REST API are as follows
My problem is that I am able to POST a simple 'Hello World' string with the code I have written and get a response. However, when I try to send an image something goes wrong and I get no response.
var http = require('http');
var querystring = require('querystring');
// This is some dummy string data
var postData = querystring.stringify({
msg: 'hello world'
});
var fs = require('fs')
, path = require('path')
, certFile = path.resolve(__dirname, 'ssl/client.crt')
, keyFile = path.resolve(__dirname, 'ssl/client.key')
, caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
, request = require('request');
// I want to send an image from one server to another. What changes should I make to the options below for POSTing image data
var options = {
hostname: '127.0.0.1',
port: 8888,
path : '/predict',
//image: fs.createReadStream('car.jpg'), //Should I give something like this??
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': postData.length
}
};
var req = http.request(options, function (res) {
console.log('STATUS:', res.statusCode);
console.log('HEADERS:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY:', chunk);
});
res.on('end', function () {
console.log('No more data in response.');
});
});
req.on('error', function (e) {
console.log('Problem with request:', e.message);
});
req.write(postData);
req.end();
Please let me know what changes I have to make to this code to post an image.I read about the use of multer package. However, the examples that I came across were using JS on both ends. Since for me, I have a Python REST API , I cannot use that. PLease help since I have been struggling with it for some time now.
Edit 1: Based on #Jana's suggestion, I added the multipart within the options and tried, where image is the key and the value is fs.createReadStream('car.jpg') . However, at the python end, it does not get the 'image' key because of which I get a False response. What am I missing?
var options = {
hostname: '127.0.0.1',
port: 8888,
path : '/predict',
//image: fs.createReadStream('car.jpg'), //Should I give something like this??
multipart: [
{
'content-type': 'application/json',
body: JSON.stringify({'image': fs.createReadStream('car.jpg') })
}
],
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
//'Content-Length': postImageData.length
}
};
Check this,
`request({
method: 'POST',
uri: 'http://127.0.0.1:8888/predict',
multipart: [{
'content-type': 'application/json',
body: JSON.stringify({
"key": "value"
})
},
{
body: fs.createReadStream('car.jpg')
}
],
},
function(error, response, body) {
if (error) {
return console.error('upload failed:', error);
}
console.log('Upload successful! Server responded with:', body);
})`
And also you can get the best examples from its own documentation Request - Simplified HTTP client

How to use header key from the api to authenticate URL in iOS Swift?

I am using Alamofire for the HTTP networking in my app. But in my api which is written in python have an header key for getting request, if there is a key then only give response. Now I want to use that header key in my iOS app with Alamofire, I am not getting it how to implement. Below is my code of normal without any key implementation:
Alamofire.request(.GET,"http://name/user_data/\(userName)#someURL.com").responseJSON { response in // 1
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result)
}
I have a key as "appkey" and value as a "test" in my api. If anyone can help. Thank you!
This should work
let headers = [
"appkey": "test"
]
Alamofire.request(.GET, "http://name/user_data/\(userName)#someURL.com", parameters: nil, encoding: .URL, headers: headers).responseJSON {
response in
//handle response
}
let headers: HTTPHeaders = [
"Accept": "application/json",
"appkey": "test"
]
Alamofire.request("http://name/user_data/\(userName)#someURL.com", headers: headers).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result)
}

Categories

Resources