How do I get the JSON values from the response in Groovy - javascript

I'm using the below function in Jenkins Shared Library.
/* The below function will list the groups */
def list_groups(server_url,each_group_name,authentication){
def groups_url = server_url + "/api/v1/groups"
def response = httpRequest consoleLogResponseBody: true,
contentType: 'APPLICATION_JSON',
customHeaders: [[maskValue: false, name: 'Authorization', value: authentication]],
httpMode: 'GET', ignoreSslErrors: true, responseHandle: 'NONE', url: groups_url,
validResponseCodes: '100:599'
if(response.status == 404){
throw new Exception("Server url not found! Please provide correct server URL.")
}
else{
if(response.status == 400 || response.status == 403){
throw new Exception("Invalid Access token or Access token expired!")
}
}
def result = readJSON text: """${response.content}"""
}
=====================================================================
I'm getting the below response,
Response Code: HTTP/1.1 200 OK
Response:
[{"id":2,"name":"Default User"},{"id":3,"name":"fos"},{"id":4,"name": "kXR"},{"id":5,"name": "Sgh"},{"id":6,"name":"ksn"},{"id":7,"name":"ALb"}]
Success: Status code 200 is in the accepted range: 100:599
Requirement:
I need to get the last output from the JSON body (id & name) ---> {"id":7,"name":"ALb"} from the response and to be printed and stored in a variable using groovy.

First, you need to Parse the response String to a JSON object, for this you can either use Jenkins native method readJSON, or something like JsonSlurperClassic. Then you can use JSON path expressions to extract the values. Check the following example.
def jsonObj = readJSON text: response.getContent()
def id = jsonObj.id[-1]
def name = jsonObj.name[-1]
echo "ID: $id | NAME: $name"

Related

Not able to retrieve data values from Ajax GET call into Django view

I am trying to query the employee list based on parameter I send
through ajax call inside data, but it giving me an error (i want it
through GET req only )
Js ajax func
$(document).ready(function () {
$(".call_ajax").click(function () {
$.ajax({
url: "/employee_list",
type: "GET",
contentType: "application/json",
dataType: "json",
data: {
designation: "soft eng",
},
headers: {
"X-CSRFToken": csrftoken,
Authorization: my_token,
},
success: function (data) {
console.log(data);
},
error: function (xhr) {
//Do Something to handle error
console.log(xhr.error);
},
});
});
my view
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.data['designation']
print(data_)
employees = Employee.objects.all()
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
error i am getting in browser
GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error)
error in Django log
File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list
data_ = request.data['designation']
KeyError: 'designation'
request.data returns the parsed content of the request body.
This is similar to the standard request.POST and request.FILES
You can use request.GET.get('designation')
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.GET.get('designation') # Here I made changes
print(data_)
employees = Employee.objects.filter(designation=data_) # Map parsed data with database field
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
or
You can override get_queryset method. As for query string parameters request.data holds POST data, you can get query string params through request.query_params
def get_queryset(self):
data = self.request.query_params.get('designation')
queryset = Model.objects.filter() # use whatever you want filter
return queryset
To know more about request.data and request.query_params, here is the link
Request parsing link
It is most probably because you are using GET, but the data resides in body. Have a look at this. To try to fix this, change your request method to POST:
$.ajax({
url: "/employee_list",
type: "POST",
...

Python return to fetch JS function

I have a JS calling a Python function. Here is the JS call :
fetch('/ws/invoice/checkDoublon', {
method : 'POST',
headers : {
'Content-Type': 'application/json'
},
body : JSON.stringify({
'invoiceNumber' : invoiceNumber.val(),
'vatNumber' : vatNumber.val(),
'id' : $('#pdfId').val()
})
}).then(function(response) {
console.log(response)
});
My Python code is like this (i'm using Flask) :
#bp.route('/ws/invoice/checkDoublon', methods=['POST'])
#login_required
def checkInvoiceDoublon():
if request.method == 'POST':
data = request.get_json()
invoiceNumber = data['invoiceNumber']
vatNumber = data['vatNumber']
invoiceId = data['id']
_vars = init()
_db = _vars[0]
_cfg = _vars[1].cfg
# Check if there is already an invoice with the same vat_number and invoice number. If so, verify the rowid to avoid detection of the facture currently processing
res = _db.select({
'select' : ['rowid, count(*) as nbInvoice'],
'table' : ['invoices'],
'where' : ['supplier_VAT = ?', 'invoiceNumber = ?'],
'data' : [vatNumber, invoiceNumber]
})[0]
if res['nbInvoice'] == 1 and res['rowid'] != invoiceId or res['nbInvoice'] > 1 :
return 'Duplicate', 200
else:
return 'Not duplicate', 200
All of this works but the console.log(response) doesn't show at all the custom return I want from Python "Not duplicate" or "Duplicate". It only show OK as response.statusText because I return the HTTP code 200
How could I retrieve a custom message on my JS code ? It could be great if it's using fetch and not ajax
Thanks in advance
this is because fetch return a Response on which you need to call either .text() or .json() the two returning a Promise containing your data as an object or a string depending on the one you've chosen
your js would look something like this
fetch('/ws/invoice/checkDoublon', {
method : 'POST',
headers : {
'Content-Type': 'application/json'
},
body : JSON.stringify({
'invoiceNumber' : invoiceNumber.val(),
'vatNumber' : vatNumber.val(),
'id' : $('#pdfId').val()
})
}).then(function(response) {
response.json().then(function(data) {
// here data is the object containing your datas
})
// or
response.text().then(function(value) {
// here value is the string returned by your python script
let data = JSON.parse(value) // this line transform the string into the same object you get by calling .json() above
})
});
You need to return a valid JSON Response from your Flask backend
You can take it in a promise pipe line and extract all data :
The python server for my code is this

Python 2.7 - Access Javascript file object in Django

I am building an app that sends multiple files as email attachments, using jQuery and Django 1.9.
I store the files in a buffer that the user can add and delete from, and sending them over a POST Ajax request as such:
//Build the message
message_buffer.forEach(function(entry){
body += '\n' + entry;
});
var files = $.merge(attachment_buffer.photos, attachment_buffer.documents);
var form = new FormData();
form.append("csrfmiddlewaretoken", csrf_token);
form.append("client_id", client_id);
form.append("subject", subject);
form.append("body", body);
form.append("files", files);
$.ajax({
url: window.location.origin + '/dashboard/ajax/send_message',
method: "post",
data: form,
processData: false,
contentType: false,
cache: false,
beforeSend: function(){
//Block UI
},
success: function(data){
if(data.status == 'success'){
console.log(data);
//Show success and clear all the data stores.
} else {
console.log(data.message);
}
},
error: function(err){
console.log(err.responseText);
}
});
Problem is when i get this buffer (a list of JS file objects) in my django view, they are gotten as unicode and i dont know how to parse them.
I need to be able to attach the files to the django EmailMessage instance like this:
for attachment in attachments:
mail.attach(attachment.name, attachment.read(), attachment.content_type)
The Django view code is:
if request.method == "POST":
client_id = request.POST['client_id']
subject = request.POST['subject']
body = request.POST['body']
attachments = []
if 'files' in request.POST.keys() and request.POST['files'] != '':
attachments = request.POST['files']
client = Client.get_client_by_id(request.user, client_id)
if client:
email_helper = EmailHelper()
email_sent = email_helper.send_email_with_attachments(request, client, subject, body, attachments)
And the email method:
def send_email_with_attachments(self, request, client, subject, message, attachments, from_email=settings.EMAIL_HOST_USER):
"""
Sends a simple text mail with attachments
:param request:
:param client:
:param subject:
:param message:
:param from_email:
:param attachments:
:return:
"""
# print type(encoding.smart_bytes(attachments))
# # for attachment in attachments:
# # print json.loads(attachment)
# #
# return False
try:
mail = EmailMessage(
self.clean_email_params(subject),
self.clean_email_params(message),
self.clean_email_params(from_email),
self.clean_email_params([client.email]),
reply_to=[from_email]
)
for attachment in attachments:
mail.attach(attachment.name, attachment.read(), attachment.content_type)
mail.send()
try:
# Log the sent email
email_log = SentEmailsLog()
email_log.user = request.user
email_log.client = client
email_log.subject = self.clean_email_params(subject)
email_log.content = self.clean_email_params(message)
email_log.to_email = str(self.clean_email_params([client.email]))
email_log.from_email = self.clean_email_params(from_email)
email_log.host_email = settings.EMAIL_HOST_USER
email_log.attachments = 'No'
email_log.save()
except Exception, e:
ErrorLogHelper.log_error(error_message=e, calling_function="EmailHelper.send_email_with_attachments")
return True
except Exception, e:
ErrorLogHelper.log_error(error_message=e, calling_function="EmailHelper.send_email_with_attachments")
return False
Please advice, thank you.
Try to explicitly encode your request body in view.py, like so:
body = request.POST['body'].encode('utf8')

Ajax response status 200 but shows error message

I'm getting status as 200 but it's printing message present inside error message alert("error...");. Why so?
function makeSelect() {
var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
var url = "http://dukano.co/sakhidev/retailon/productoption/values";
alert(url);
var jsondata = $j('#customoption').serialize();
alert("jsondata: " + JSON.stringify(jsondata));
$j.ajax({
type : 'POST',
url : url,
data : jsondata,
dataType : 'json',
success : function(response) {
console.log("calling");
console.log(response);
alert("call success");
alert("response data:" + JSON.stringify(response));
if (response.status == 200) {
console.log("yes");
} else if (response.status == "error") {
console.log("no");
}
},
error : function(response) {
alert("error...");
alert("response:" + JSON.stringify(response));
console.log(response);
}
});
}
Magento's controller function returning json value
public function valuesAction(){
$blouseoption = $this->getRequest()->getParam('blouseoption');
$sareefinishing = $this->getRequest()->getParam('sareefinishing');
$data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
Mage::dispatchEvent('product_custom_option', $data);
$jsonData = json_encode(array($blouseoption, $sareefinishing));
$this->getResponse()->clearHeaders()
->setHeader('Content-type','application/json',true);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
$this->getResponse()->sendResponse();
}
As you are using
dataType: "json"
this evaluates the response as JSON and returns a JavaScript object.any malformed JSON is rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Make sure that the server returns valid JSON. empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
try to check the textStatus in the error.
error : function(jqXHR,textStatus,errorThrown)
{console.log(textStatus)}
if this prints "parsererror" then of course you have problem with your returning json. please check that.
More Info
Alternative answer
Instead of returning status 200 with empty response, you can return status 204 and not return any response. Status 204 is for No Content. JQuery should not throw any error in this case.

Django/python is converting my post data from JavaScript

When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending:
info {'mid':1,'sid':27,'name':'aa','desc':'Enter info' }
Yet when I access it in the django request I am seeing:
u'{\'mid\':1,\'sid\':27,\'name\':\'aa\',\'desc\':\'Enter Info\'}
When I try to parse this with json.loads it dies with an invalid JSON message.
I am posting with:
data.info = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }";
$.ajax({url: cmdAjaxAddress,
type: "POST",
data: data,
success: function(txt) {
result = txt;
},
async: false });
I am reading the POST in django like this:
if request.is_ajax() and request.method == 'POST':
infoJson = request.POST['info']
info = json.loads(infoJson);
Any help would be appreciated.
How are you encoding your JSON string? The single quotes need to be double quotes, per the spec:
In [40]: s1 = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }"
In [41]: simplejson.loads(s1)
JSONDecodeError: Expecting property name: line 1 column 1 (char 1)
In [42]: s2 = '{"mid":1,"sid":27,"name":"aa","desc":"Enter info" }'
In [43]: simplejson.loads(s2)
Out[43]: {'desc': 'Enter info', 'mid': 1, 'name': 'aa', 'sid': 27}

Categories

Resources