can't access json object from python method - python

I've looked at many answers showing how to access a json in a python method however I can't seem to get mine to work.
Here is my ajax call
var data = {
'customer': customer,
'custID': custID,
'date': date,
'jobNum': jobNum,
'deviceID': deviceID
}
//create customer
if (custID === undefined) {
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
}
else {
//empty
}
and here is my python method:
#view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
response = request.POST
myObject = json.loads(response)
#print myObject["customer"]
test = "hello"
return dict(test=test)
somewhat new to python so pardon my limited understanding. How can I get my json and access the object properties? all i get in my cmd when i tried print was ValueError: No JSON object could be decoded

pyramid has native JSON request support. Set the contentType parameter to application/json to tell the server that you are sending JSON, preferably with a character set (UTF8):
$.ajax({
url: "http://127.0.0.1:6543/test",
type: "POST",
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
dataType: 'json',
success: function(response, textStatus, jqXHR) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
and on the server side use request.json_body:
#view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
myObject = request.json_body
print myObject["customer"]
test = "hello"
return dict(test=test)

Related

Getting multiple response while calling python API from Angular

While calling the python API from angular 10. I am getting multiple response. How to overcome it.
Python API Response from Angular Service call:
1. Object { type: 0 } # how to avoid this additional response
2. Object { headers: {…}, status: 201, statusText: "Created", url: "https://*********/1bcd2a20-dd60-4cfe-984f-7f3607f01e7c", ok: true, type: 4, body: "{\"status\":{}}" }
Angular Service Call:
postCall(identifier): Observable<HttpEvent<{}>> {
let token1 = localStorage.getItem('token');
const headerSettings: { [name: string]: string | string[]; } = {};
headerSettings['Authorization'] = 'Bearer ' + token1;
const req = new HttpRequest('GET', 'https://***********/'+identifier, null, {
reportProgress: false,
responseType: 'text'
});
const newHeader = new HttpHeaders(headerSettings);
let changedRequest = req.clone({
headers: newHeader
});
return this.http.request(changedRequest);
}

Python string is null but also isn't None nor empty string

class StartAnalysis(BaseHandler):
def post(self):
playlist = self.request.get('playlist')
language = self.request.get('language')
If I make a POST request without this playlist field, then this happens:
>>> playlist
null
>>> type(playlist)
<type 'unicode'>
>>> playlist is None
False
>>> not playlist
False
>>> playlist == ''
False
>>> playlist == u''
False
How am I supposed to check that it's None? And why is it saying that it's null and not None?
I'm using AppEngine.
My javascript code making the POST request:
let params = new URLSearchParams(location.search);
let url_id = params.get('id');
let url_language = params.get('language');
const url = 'http://localhost:8080/start-analysis?playlist=' + url_id + '&language=' + url_language;
$.ajax({
url: url,
type: 'POST',
success: function(results) {
...
},
error: function(error) {
...
}
});
I changed to using application/json for the POST requests instead of the default application/x-www-form-urlencoded and that seemed to fix the problem of the request sending the string "null" instead of just an empty string when one of the parameters was empty or missing.
let params = new URLSearchParams(location.search);
let url_id = params.get('id');
let url_language = params.get('language');
const url = 'http://localhost:8080/start-analysis';
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({'playlist': url_id,'language': url_language}),
success: function(results) {
...
},
error: function(response, status, error) {
...
}
});
And the backend receives it like:
class StartAnalysis(BaseHandler):
def post(self):
data = json.loads(self.request.body)
playlist = data['playlist']
language = data['language']

error 405 get method not allowed

Angularjs code
var app = angular.module('myApp', []);
app.factory('httpSend', ['$http', '$q', function($http, $q) {
var app = {};
app.sendToServer = function(data) {
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-type': 'application/x-www-form.urlencoded;'
}
}).then(function(response) {
debugger
var result = data;
});
}
app.getfromServer = function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
return app;
}]);
app.controller('myCtrl', ['$scope', '$http', 'httpSend', '$filter', function($scope, $http, httpSend, $filter) {
$scope.names = ["ankit patidar", "adhishi ahari", "kritin joshi", "kautilya bharadwaj", "punita ojha", "manvi agarwal", "apeksha purohit", "shipra jain", "mansi nangawat", "praveen soni"];
$scope.data = [];
$scope.names.forEach(function(name) {
$scope.data.push({
name: name,
checkin: "",
checkout: ""
})
});
$scope.login = [];
$scope.check = function(name, doing) {
debugger
name[doing] = new Date();
name[doing] = $filter('date')(name[doing], 'dd-MM-yyyy hh:mm:ss');
$scope.login.push(angular.copy(name));
if (doing == "checkout") {
var q = JSON.stringify($scope.login);
httpSend.sendToServer(q);
}
}
$scope.getData = function() {
httpSend.getfromServer();
}
}]);
`
Python Code
def get(self):
logging.info('get is triggered')
obj = CheckIn.query().fetch()
emp_obj = []
for x in obj:
logging.info('I am inside for loop ')
emp_obj.append({
'name': x.name,
'Check_in': x.inDate,
'check_out': x.outDate
})
logging.info('I am inside emp_obj')
self.response.write(json.dumps(emp_obj))
i need to fetch all the data stored on ndb datastore on front end view thats why i m using http get method but error is showed method not allowed. can u please help e despite using query fetch and showing its response on python ad triggering get method, why error is coming, is there a mistake in control flow or something is missing in my get method, as for now i m able to post nd store data
Change your factory to the following. Don't use the same variable app that you are using for initialising your module for your controller logic.
app.factory('httpSend',['$http', '$q',function($http, $q){
return {
'sendToServer': function(data) {
var def = $q.defer();
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
debugger
var result = response.data;
def.resolve(result );
});
return def.promise;
},
'getfromServer': function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
}
}]);

AJAX/PYTHON : how to send json value to server

I am a new to Ajax/Python, I don't know how to POST a json value to my python server.
Python code:
#app.route('/ajouterContact', methods = ['POST'])
def ajouterContact():
data = json.loads(request.data)
#nom = request.form['nomContact'];
contact.append(data)
ajouter.make_response(json.dumps(contact), 201)
ajouter.headers['Content-Type'] = 'application/json'
JS code
$('#buttonAjouter').click(function() {
var nom = 'Tom';
var myObj = new Object();
myObj.nom = nom;
var jsonText = JSON.stringify(myObj);
var i = 0;
$.ajax({
url: '/ajouterContact',
data: jsonText,
type: 'POST',
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
I am getting this error on server side :
ValueError: No JSON object could be decoded
If anyone can help me on this..
Thank you!
You need to provide the contentType in your ajax request:
contentType: 'application/json;charset=UTF-8',
Then in your server try to debug something like this:
request.json

read json object that has two arrays in python using GAE

I created a json object in jquery and sent it via ajax as a post request. I logged both the arrays and it has the correct format.
$('#submittt').on('click', function () {
var names = [];
var times = [];
$(".input-medium.name").each(function() {
names.push($(this).val());
});
$(".input-medium.time").each(function() {
times.push(parseInt($(this).val()));
});
console.log(JSON.stringify(names));
console.log(JSON.stringify(times));
var data = {"names":names, "times":times};
console.log(data);
$.ajax({
url: "/step/" + vid,
type: "POST",
data: 'data=' + JSON.stringify(data),
dataType: "json",
});
Now I am trying to get the json object in python (I am using GAE) and access its 2 arrays.
I believe I am supposed to do something like
json_raw = self.request.get('data')
jsonObj = json.loads(json_raw)
namelist = jsonObj[0]['names']
print namelist
But this isn't working, it says it can't decode the json object. Anyone know what I am doing wrong?
In your JavaScript, instead of
data: 'data=' + JSON.stringify(data),
do
data: JSON.stringify(data),
And in your Python remove the [0] when retrieving namelist.

Categories