I want to get an JSON response from the API and give a response with the selected field. I have fetched the response but I am not able to create a response with the new value. I am very new to python world and in learning stage.
def search(request):
if request.method == 'POST':
searchQry = request.POST.get("searchQry","")
nodeIP = settings.NODEIP
params = {'search':searchQry}
apiResponse = requests.get(url = nodeIP, params = params)
data = apiResponse.json()
newArray = {}
nodeName = 'RPID'
if nodeName == 'RPID':
for x in data:
newArray['cphNumber'] = x["data"]["cphNumber"]
newArray['farmName'] = x['data']['farmName']
newArray['addressLine1'] = x['data']['addressLine1']
return HttpResponse(json.dumps(newArray))
else:
return HttpResponse('Unauthrozed Access')
My response array looks likes this :
[{"data": {"cphNumber": "321","farmName": "313","addressLine1": "13","addressLine2": "13","region": "13", "postalCode": "13"},"id": "4c1b935664e6f684e89ee363f473ce3567599d4b9da0f5889565d5b6f0b84440"},{"data": {"cphNumber": "321","farmName": "313","addressLine1": "13","addressLine2": "13","region": "13","postalCode": "13"},"id": "7cbe7be9797896545410ed6c4dcc18064525037bc19fbe9272f9baabbb3216ec"},{"data": { "cphNumber": "321","farmName": "313","addressLine1": "13","addressLine2": "13","region": "13","postalCode": "13"},"id": "7df10c0b7b84434d5ace6811a1b2752a5e5bca13b691399ccac2a6ee79d17797"}]
In response I am getting only one array. I know I have to do something like newArray[0]['cphNumber'] But I am getting an error. Can you please help me to solve this .
Related
I am using fetch on the frontend to send data to my flask backend in order to make a movie seat booking. The whole process works fine until the client awaits the response, which is "undefined" . So , basically the database saves the data , the only problem is the response which is sent to the client. I used jsonify which usually works fine. Can anybody tell me what I am missing? Thanks in advance.
Here is the JS code :
function sendReservationToServer() {
const selectedSeats = sessionStorage.getItem('selectedSeats')
const reservation = { userId, selectedSeats, showTimeId, movieHallId }
fetch('/bookSeats', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(reservation)
}).then(response => {
response.json()
}).then(data => {
theatreHall.innerHTML = `${data} <br> <a href='/home'>Back to main menu</a>`
console.log(`${data}`)
}).catch(err => infoMsg.textContent = err)
sessionStorage.clear()
}
And this is the flask controller which handles the request:
#app.route("/bookSeats", methods=["POST"])
def book_seats():
selected_seats = request.json
user_id = selected_seats.get('userId')
seats = json.loads(selected_seats.get('selectedSeats'))
movie_hall_id = selected_seats.get('movieHallId')
seat_ids = []
showtime_id = selected_seats.get('showTimeId')
for seat in seats:
seat_ids.append(db.session.query(Seat).filter(
Seat.seat_number == seat).filter(Seat.movie_hall_id == movie_hall_id).all()[0].stid)
for seat in seat_ids:
reserved_seat = ReservedSeat(
seat_id=seat, show_time=showtime_id, user=user_id)
db.session.add(reserved_seat)
db.session.commit()
reservation = Reservation(
user=user_id, show_time=showtime_id, number_of_tickets=len(seat_ids))
db.session.add(reservation)
db.session.commit()
message = f'{seats} booked successfully'
return jsonify(message)
data is undefined because the first then does not return anything. Either make it return response.json() or move everything in the second then to the first and replace data with response.json().
Django can only concatenate str (not "list") to str
Error Messages.......
I have some code like this:
function form_submit() {
var arr_category = new Array();
var arr_lawyer = new Array();
var data = new Object();
$('input[name^="category_idx"]').each(function() {
arr_category.push($(this).val());
});
$('input[name^="lawyer_idx"]').each(function() {
arr_lawyer.push($(this).val());
});
console.log("arr_category=="+arr_category);
console.log("arr_lawyer=="+arr_lawyer);
if (confirm('edit??') == true) {
data.arr_category = arr_category;
data.arr_lawyer = arr_lawyer;
call_ajax('/admin/lawyer/recommend_add', data);
//alert("arr_lawyer=="+arr_lawyer);
}
}
Am I doing well in jquery?
look at console.log
arr_category==1,2,3,4,5,6,7,8,9
arr_lawyer==64,37,57,58,130,62,38,51,110
admin_view.py
#csrf_exempt
def recommend_add(request):
print("TEST BANG VALUE------------")
if request.is_ajax() and request.method == "POST":
arr_category = request.GET.getlist('arr_category[]')
print("arr_category------------" + arr_category)
code = 0
msg = "TEST."
data = json.dumps({
'code': code,
'msg': msg,
#'retURL': retURL
})
return HttpResponse(data, content_type='application/json')
I want to print.
error message
TypeError: can only concatenate str (not "list") to str
How can I do that?
In case if you want to return a python interpreter error message to jquery's ajax call then you can use the below syntax.
def recommend_add(request):
print("TEST BANG VALUE------------")
if request.is_ajax() and request.method == "POST":
try:
arr_category = request.GET.getlist('arr_category[]')
print("arr_category------------" + arr_category)
code = 0
msg = "Success"
except Exception as e:
code = '' # anything you want as per your internal logic in case of error.
msg = str(e)
data = json.dumps({
'code': code,
'msg': msg,
#'retURL': retURL
})
return HttpResponse(data, content_type='application/json')
Please ignore my indentation.
in your print code try this
print("arr_category------------:", arr_category)
I am working on a python django web app in which I want to implement internationalization and auto translate the whole app into french or chinese.
I took reference from this site https://www.metod.io/en/blog/2015/05/05/django-i18n-part-1/
But whenever I try to run the app it shows this error:
500: ValueError at /en/get_dashboard_data/ The view
dashboard.views.getDashboardData didn't return an HttpResponse object.
It returned None instead.
And url get_dashboard_data is fetching data through ajax.
url(r'^get_dashboard_data/$', views.getDashboardData, name='getDashboardData'),
view
#login_required(login_url='/')
def getDashboardData(request):
dbname = request.user.username
if request.method == 'POST' and request.is_ajax():
if request.POST.get('action') == 'sale_chart_data':
data = DashboardData(dbname).getSaleChartData()
channel_list = data[0]
data_list = data[1]
print 123, data_list, channel_list
return HttpResponse(json.dumps({'channel_list':channel_list, 'data_list':data_list}), content_type='application/json')
if request.POST.get('action') == 'get_sale_numbers':
sale_data = DashboardData(dbname).getSaleNumbers()
return HttpResponse(json.dumps({'sale_number_data':sale_data}), content_type='application/json')
if request.POST.get('action') == 'get_inventory_numbers':
inventory_data = DashboardData(dbname).getInventoryData()
return HttpResponse(json.dumps({'inventory_data':inventory_data}), content_type='application/json')
if request.POST.get('action') == 'get_order_numbers':
order_data = DashboardData(dbname).getOrderData()
return HttpResponse(json.dumps({'order_data':order_data}), content_type='application/json')
if request.POST.get('action') == 'get_hourly_data':
order_data = DashboardData(dbname).getHourlyData()
sale_data = order_data[1]
count_data = order_data[0]
return HttpResponse(json.dumps({'sale_data':sale_data, 'count_data':count_data}), content_type='application/json')
if request.POST.get('action') == 'top_performers':
data = DashboardData(dbname).getTopPerformers()
inventory_count_dict = data[0]
current_month_dict = data[1]
last_month_dict = data[2]
current_quarter_dict = data[3]
current_year_dict = data[4]
channel_list = data[5]
return HttpResponse(json.dumps({'inventory_count_dict':inventory_count_dict,'current_month_dict':current_month_dict,'last_month_dict':last_month_dict,'current_quarter_dict':current_quarter_dict,'current_year_dict':current_year_dict,'channel_list':channel_list}), content_type='application/json')
if request.POST.get('action') == 'top_products':
product_data = DashboardData(dbname).getTopProducts()
return HttpResponse(json.dumps({'product_data':product_data}), content_type='application/json')
javascript
function getSaleChart(){
$.ajax({
url : "/get_dashboard_data/",
type : "POST",
data : {action:'sale_chart_data'},
success : function(response) {
channel_list = response.channel_list;
data_list = response.data_list;
c3.generate({
bindto: '#sale-chart-30-days',
data:{
x: 'dates',
xFormat: '%b %d',
columns: data_list,
colors:{
Flipkart: '#1AB394',
Paytm: '#BABABA'
},
type: 'bar',
groups: [ channel_list ]
},
axis: {
x: {
type: 'timeseries'
}
}
});
},
error : function(xhr,errmsg,err) {
toastr["error"]("Something Broke.", "Oops !!!.");
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
This is why you should really practice more defensive programming. Though you insist that the request method is POST and it is ajax and the action is sale_chart_data one of the three isn't what you expect it to be.
Your function really should be like follows. It's plain old good practice.
def getDashboardData(request):
dbname = request.user.username
if request.method == 'POST' and request.is_ajax():
action = request.POST.get('action')
if action == 'sale_chart_data':
data = DashboardData(dbname).getSaleChartData()
....
...
# other if conditions here
else :
return HttpResponse(json.dumps({'message':'Unknown action {0}'.format(action)}), content_type='application/json')
else :
return HttpResponse(json.dumps({'message':'Only ajax post supported'}), content_type='application/json')
And then you ought to set break points and evaluate the request to figure out what exactly is happening in this particular request.
My guess would be that your JavaScript does indeed make a POST request to /get_dashboard_data/ but it receives a redirect response (HTTP 301 or 302) to /en/get_dashboard_data/ due to some kind of i18n middleware.
The browser follows the redirect, but the new request to /en/get_dashboard_data/ is a GET request.
Edit:
When following a redirect, the browser will always perform the second request as GET, there is no way to prevent that. You have several options to solve this:
make the initial request to the right application. This means you have to pass your i18n URL into your JavaScript instead of hardcoding it. You can add something like this to your template:
<script>var dashBoardDataUrl = "{% url "name-of-dashboard-url" %}"</script>
as your "actions" just get code, you could just accept a GET request and read the action from query paramters
Split that view into several smaller views that accept GET request so you have something that resembles a REST API.
I am working on project which is giving XML and JSON type of response. I need to take only JSON response from SOAPUI to process for next step.
Is there any SOAPUI api available to get only JSON type of response by groovy script.
Thanks in advance.
Please check this response SoapUI Groovy Script’s JSON Responses Is Empty When Using Testrunner
import groovy.json.JsonSlurper
//provide the correct rest test step name
def stepName='testStepForPing'
def step = context.testCase.getTestStepByName(stepName)
def response = new String(step.testRequest.messageExchange.response.responseContent)
log.info response
def json = new JsonSlurper().parseText(response)
Assuming it's a REST service, by default this approach will fetch the response in JSON format.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def response = groovyUtils.getXmlHolder("RequestStepName#Response")
// as a string -> def response = context.expand('${RequestStepName#Response}')
You can get it as xml using #ResponseAsXml.
In the SOAPUI Javascript context I developed this algorithm.
var xmlHolder = com.eviware.soapui.support.XmlHolder(messageExchange.responseContent);
var nodes = xmlHolder.getDomNodes("//SOAP-ENV:Envelope/SOAP-ENV:Body/ns:xxxxxx");
var obj = {};
toJsonObject(nodes[0], obj);
function toJsonObject(xmlObject, jsonObject) {
for (var i = 0; i < xmlObject.getLength(); i++) {
var node = xmlObject.item(i);
if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
if (node.getLength() == 1) {
if (node.hasChildNodes()) {
jsonObject[node.getNodeName()] = String(node.item(0).getNodeValue());
}
} else {
if (node.hasChildNodes()) {
jsonObject[node.getNodeName()] = {};
jsonObject[node.getNodeName()] = toJsonObject(node, jsonObject[node.getNodeName()]);
}
}
}
}
return jsonObject;
}
log.info(JSON.stringify(obj));
context.setProperty('JSON: ', JSON.stringify(obj));
In my django-piston handler functions, it looks like I can basically do two things. Either I can return a specific status code with some non-formatted content:
def create(...):
...
resp = rc.BAD_REQUEST
resp.content = 'Some string error message'
return resp
Or I can return a dictionary of error messsages, which can be formatted according to the specified emitter, but with a 200 status code:
def create(...):
...
return error_dict
How can I return a dictionary or model object, formatted by the specified emitter, but with a customized status code?
How about this?
def create(...):
...
resp = rc.BAD_REQUEST
resp.content = error_dict
return resp
In order to solve this, I added a new function to the my subclass of the BaseHandler, although it could just be added to any handler. The function manually calls the emitter to properly format the content, then adds the content-type and status code.
class MyBaseHandler(BaseHandler):
def render_response(self, request, response, content):
em_info = None
for ext in Emitter.EMITTERS:
if request.path.find('.'+ext) > -1:
em_info = Emitter.get(ext)
if not em_info:
return rc.NOT_FOUND
RequestEmitter = em_info[0]
emitter = RequestEmitter(content, typemapper, self, self.fields, False)
response.content = emitter.render(request)
response['Content-Type'] = em_info[1]
return response
Called like so:
def create(...):
...
return self.render_response(request, rc.BAD_REQUEST, error_dict)