How to receive dictionary in post data python - python

I'm trying to send array as a parameter to the api which is using python and django framework.
Here's my client side code that is being used to access the api:
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
data: {user:{name:'Rohit Khatri', age:20, father_name:'S.K'},type:'info'},
complete: function(response) {
console.log(response);
}
);
Here's the view where I'm trying to access the request parameters
def get_users(request):
print(request.POST.get('ids'))
and when I try to access ids parameter, It gives None.
If anyone has faced the same problem, please help me.

You can try getting the list as follows:
request.POST.getlist('ids[]')
Note: You will be better off if you send/receive your data as JSON. You first need to set the Accept and Content-Type headers to application/json while sending the request and then convert the json to python object using json.loads. Example as follows:
Javascript/AJAX
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
contentType: 'application/json'
data: {ids:[1,2,3,4,5],type:'info'},
complete: function(response) {
console.log(response);
}
);
Django
import json
def get_users(request):
ids = request.POST.get('ids')
if ids:
ids = json.loads(ids)
Update:
In case you need to use more complicated data such as an object (dictionary) using json will be your best bet and it will work pretty similar to the above example.
Javascript/AJAX
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
contentType: 'application/json'
data: {ids:{"x":"a", "y":"b", "z":"c"}, type:'info'},
complete: function(response) {
console.log(response);
}
);
Django
import json
def get_users(request):
ids = request.POST.get('ids')
if ids:
ids = json.loads(ids)

Related

Fetching data after a certain time interval(10 sec) from a continuously increasing database like mysql using flask

I want to create an api using python and flask that fetches data in regular time interval(10 sec) from a continuously increasing database where data is continuously coming and stored.I don't want to fetch the old data which were already fetched.
Say you currently have an API endpoint that returns all the database stored data:
#app.route('/data', methods=['post'])
def data():
all_the_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=all_the_data)
So your ajax call currently doing something like:
$.ajax({
type: "POST",
url: "/data",
dataType: "json",
success: function(data) {
console.log(data);
update_graph(data);
}
});
You just need a way for the system to filter what's going out, back to the client-- so we instead of querying all the data, we can filter based on a reference:
#app.route('/data', methods=['post'])
def data():
client_data = request.json
reference = client_data.get('reference')
if reference:
# we have a reference, so lets filter the query:
query_data = Data.query.filter(Data.id>reference).order_by(Data.created.desc()).all()
else:
# no reference, so send the lot!
query_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=query_data)
Then your ajax request needs to get the last reference from the last query it did-- and supply that to the API endpoint:
$.ajax({
type: "POST",
url: "/data",
data: JSON.stringify({ reference: 999 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log(data)
update_graph(data["results"]);
}
});
So you just need to work out how to get that reference value from the last set of values you recieved (the API could send that back as another key, or you could poll your current set within javascript, etc).

Unable to receive data from AJAX call [Flask]

What I Am Trying To Do: Receive data from AJAX to Flask. Eventually, I would like to send token data (Which will come from stripe) to the flask side
The Problem: I can't print any data to the console. So I'm assuming data is not being passed through.
I am unable to receive data from my Ajax call. I have been searching for some time now and I haven't found a fix. I've seen multiple different solutions for others but none of them worked for me. I'm am trying to implement a custom Stripe payment flow.
What I plan to do eventually is to pass in all the data I need (in the token) through the 'data' parameter in JSON format. Here are the different sides of code
index.html
var handler = StripeCheckout.configure({
key: 'test_key',
image: 'image_url',
locale: 'auto',
token: function(token) {
$.ajax({
url: '/charge',
data: {
'token': '(data im trying to access/print in app.py)'
},
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log("ERROR");
console.log(error);
},
dataType: "json",
contentType: "application/json"
});
}
});
app.py
from flask import Flask, request
import json
#app.route('/charge', methods=['POST'])
def charge():
# Grab token information
token = request.form['token']
# The line below never prints to console
print(token)
# This test print statement below never prints to console
print("This print statement never runs")
Nothing prints to the console. I've wasted so much time on this so any leads or pointers would be greatly appreciated!
UPDATES
I did some updates suggested by #Daniel Roseman but nothing at all prints to the console.
Try the following code
In javascript:
var data = {token: token}
$.ajax({
url: '/charge',
data: JSON.stringify(data),
type: 'POST',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log("ERROR");
console.log(error);
},
dataType: "json",
contentType: 'application/json;charset=UTF-8',
});
In controller [charge method]:
from flask import Flask
from flask import render_template, request, jsonify
#app.route('/charge', methods=['POST'])
def charge():
# Grab token information
token = request.json['token']
# This is the expected token from json
print(token)
# This test print statement below now prints to console
print("This print statement now runs surely")
# return JSON
return jsonify(
code=0,
msg="Success"
)
You're not posting JSON.
Instead of accessing request.get_json(), you can just access the individual elements from the request.form dictionary. In this case:
token = request.form['token']

Asynchronously update page with data that are stored by middleware

I have middleware, that stores all http requests into DB.
Also I have view, that fetches data from DB and put this data into the context.
views.py
def requests(request):
http_requests = WebRequest.objects.all()
context = {
"http_requests": http_requests
}
return render(request, "requests.html", context)
How can I asynchronously update data on this page as new requests come in (so, new requests should appear on this page asynchronously)? Can I use only Django features to achieve such behavior or I need to use some javascript libraries?
It depends on how much time you want to spend on the project. As Lorenzo stated, it might make sense to create an API and have javascript-frameworks (e.g. emberjs or angularjs) handle the asynchronity. I dont think you can handle this with pure django...
If you don't have time and are in for some 'hack' you could just replace the content of your page by polling the url and replacing the whole document with the response:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
$('body').html(response);
}
});
This is NOT clean, but should work as a quick an dirty trick...
EDIT: If you only want to exchange certain parts of your site, you can break it down to just add elements to the page:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
var newlyAddedRows = // find your newly added rows through some jquery
newlyAddedRows.forEach(function(row){
$('#request-holder').append(row);
});
}
});
OR WITH JSON
$.ajax({
type: "GET",
url: "<url_to_your_requests_api_endpoint>",
success: function(response){
var requestRows = response.requestItems
var $requestsHolder = $('#request-holder');
$requestHolder.empty();
requestRows.forEach(function(row){
requestsHolder.append('<div class="request-row">' + <visualize your data somehow> + '</div>'); //e.g. row.timestamp if you have that in your json
});
}
});

Receiving a 2-D list as request parameters in Python Flask

I am attempting to receive a 2-D list in my flask application. The json object sent is as follows:
function someFunction() {
var two_d_arr = [[a,1],[b,2],[c,3]];
var data = {
'arr' : two_d_arr
};
$.ajax({
url: 'http://localhost:5025/',
dataType: 'jsonp',
data: data,
success: function(response) {
alert(response);
}
});
}
I have tried various times to retrieve these tuples as a list and am failing. The way I would want to see them is a list as follows:
lst = [[a,1],[b,2],[c,3]]
When I print request.data I get the following output (formatted for easy reading):
ImmutableMultiDict([(
'callback', u'jQuery1113017347401613369584_1450454196704'),
('liveCells[2][]', u'c'), ('liveCells[2][]', u'3'),
('liveCells[1][]', u'b'), ('liveCells[1][]', u'2'),
('liveCells[0][]', u'a'), ('liveCells[0][]', u'1')
])
I have tried various ways to extract just the list (request.form.getlist, request.args.getList) etc.
You are not encoding the request to JSON. You are only specifying what you expect to receive from the server (because you expect JSONP jQuery is including a callback parameter).
Encode to JSON on the client side:
$.ajax({
url: 'http://localhost:5025/',
data: JSON.stringify(data),
success: function(response) {
alert(response);
}
});
I omitted the dataType argument, only set one if jQuery can't autodetect the response type.
On the server side, read the response with request.get_json().

Receive JSON in python Bottle

I am trying to do a JSON post to my Bottle server.
from bottle import request, route, run
#route('/feedback', method='POST')
def feedback():
data = request.json
print data
run(host='localhost',port=8080)
In the client side, I have
$('#user_feedback').submit(function() {
var feedback = {"id": 1}
$.ajax({
type: "POST",
url: "http://localhost:8080/feedback",
data: feedback
});
return false;
});
I am returning false here because I don't want the page to be redirected.
However, the data I received in my Bottle server is always None when printed out.
Please help. Thank you.
request.json expects the content type of the request to be application/json .
So to make it work, you should set the contentType property of your request to application/json and stringify your data :
$.ajax({
type:"POST",
contentType: "application/json",
url:"/feedback",
data: JSON.stringify(feedback)
});

Categories

Resources