Django APIView data format from AJAX - json

I was trying to send an array of objects in views.py using APIView to insert multiple rows in 1 post request. This is my JavaScript data format:
const data = {
group_designation: [
{id: 1},
{id: 2},
{id: 3},
]
}
I run an insomnia app and it only accepts this kind of format:
{
"group_designation": [
{"id": 1},
{"id": 2},
]
}
However, if I send a post request using the javascript format stated above, it gives me a bad request error(400). This is the payload in network tab:
group_designation[0][id]: 1
group_designation[1][id]: 2
group_designation[2][id]: 3
In Django, this is the request.data result:
<QueryDict: {
'group_designation[0][id]': ['1'],
'group_designation[1][id]': ['2'],
'group_designation[2][id]': ['3']
}>
My code in Django:
def post(self, request):
temp_objects = []
new_data_format = {'group_designation': temp_objects}
serializer = GroupSerializer(data=new_data_format, many=True)
if serializer.is_valid(raise_exception=True):
group_data_saved = serializer.save()
return Response({
"success": "success!!!"
})
I was just trying to rewrite the data format so it will be saved but no luck trying. Please help. Thank you!

Related

How to get all the JSON values for the same keys iterated number of times using groovy?

def json = '{"book": [{"id": "01","language": "Java","edition": "third","author": "Herbert Schildt"},{"id": "07","language": "C++","edition": "second","author": "E.Balagurusamy"}]}'
Using Groovy code, how to get the "id" values printed for "book" array?
Output:
[01, 07]
This is the working example using your input JSON.
import groovy.json.*
def json = '''{"book": [
{"id": "01","language": "Java","edition": "third","author": "Herbert Schildt"},
{"id": "07","language": "C++","edition": "second","author": "E.Balagurusamy"}
]
}'''
def jsonObj = new JsonSlurper().parseText(json)
println jsonObj.book.id // This will return the list of all values of matching key.
Demo here on groovy console : https://groovyconsole.appspot.com/script/5178866532352000

How to get JSON data in an Odoo controller using type='json'?

A few days ago I did a similar question here: How to get JSON data in an Odoo controller?
But now, I need to create a controller which receives only JSON data. So, I am doing the request from a Python console, this way:
import requests
import json
url = 'http://localhost:8069/odoo/test'
headers = {'Content-Type': 'application/json'}
data = {
'name': 'Jane',
'email': 'jane.doe#gmail.com',
}
data_json = json.dumps(data)
r = requests.post(url=url, data=data_json, headers=headers)
I have created a controller which listens to http://localhost:8069/odoo/test, this way:
import openerp.http as http
from openerp.http import Response
import logging
_logger = logging.getLogger(__name__)
class WebFormController(http.Controller):
#http.route('/odoo/test', type='json',
auth='public', methods=['POST'], website=True)
def index(self, **args):
_logger.info('CONNECTION SUCCESSFUL')
_logger.info(args)
name = args.get('name', False)
email = args.get('email', False)
_logger.info(name)
_logger.info(email)
if not name:
Response.status = '400 Bad Request'
return '{"response": "OK"}'
The problem is that I am receiving an empty JSON in the controller. I can read CONNECTION SUCCESFUL in the log, with no error, but when I show args, I get {}, and obviously due to that, False when writing name and email.
If I pass the data as a Python dictionary or as a string, I get the following error:
Invalid JSON data: 'name=Jane&email=jane.doe%40gmail.com' or
Invalid JSON data: "{'name': 'Jane', 'email': 'jane.doe#gmail.com'}" respectively.
If I modify type='json' and I write type='http' instead, I get the following error:
Function declared as capable of handling request of type 'http' but called with a request of type 'json'.
I have read that may be this could be solved if the request is sent using the parameter json instead of data, this way:
r = requests.post(url=url, json=data_json, headers=headers)
Unfortunately, the server which is going to make the request has an old operating system which cannot update the python-requests package, so I cannot use json parameter since it did not exist at the version installed in that server.
Please, can anyone help me? I need get JSON data in the controller, not a string neither Python dictionaries.
You have just forgotten to put your data inside the params keywords:
Use this correct syntax :
data = {"params": dict(key="value")}
data = {
"params": {
"name":"prakashsharma",
"email":"prakashsharmacs24#gmail.com",
"phone":"+917859884833"
}
}
Please don't forget to use json.dumps(data) and 'Content-Type': 'application/json' while requesting a resource in json format.
I am damn sure your issue will be solved after using this one my friend... cheers :)!!
You can use below format for a POST request
{
"params" : {
"name" : "Order/1/18",
"session_id" : 1,
"customer_count" : 2,
"partner_id" : 9,
"lines": [
{
"product_id": 37,
"qty" : 2,
"price_unit" : 2,
"discount" : 10
}
],
"pos_reference" : 2,
"note" : "This is a test note"
}
}
Content type must be application/json
How odoo route will handle request ?
Route will help creating a POS order in odoo [POST]
#http.route(['/api/v1/resources/<string:api_key>/pos_order'],
auth="public",
website=False,
type="json",
csrf=False,
methods = ['POST'])
def create_update_pos_order(self, api_key=None, **kwargs):
print(kwargs.get('name')) -> Order/1/18
God Bless Forvas::
But for more clearity:
if you want to test through cURL:
curl -i -X POST -H "Content-Type: application/json" -d '{"params": {"name":"prakashsharma","email":"prakashsharmacs24#gmail.com","phone":"+917859884833"}}' 'http://localhost:8069/web/yourlistoner/'
if you want to test through python request:
import requests
headers = {
'Content-Type': 'application/json',
}
data = '{"params": {"name":"prakashsharma","email":"prakashsharmacs24#gmail.com","phone":"+917859884833"}}'
requests.post('http://localhost:8069/web/yourlistoner/', headers=headers, data=data)
the function in odoo will be something like
from odoo import http
import json
class YourClass(http.Controller):
#http.route('/web/yourlistoner/', type='json', auth="none", methods=['POST'],cors="*", csrf=False)
def listoner(self, **kw):
print http.request.params
print "lllllllllllllllllllll"
return json.dumps({"result":"Success"})

Working with JSON and Django

I am new to Python and Django. I am an IT professional that deploys software that monitors computers. The api outputs to JSON. I want to create a Django app that reads the api and outputs the data to an html page. Where do I get started? I think the idea is to write the JSON feed to a Django model. Any help/advice is greatly appreciated.
Here's a simple single file to extract the JSON data:
import urllib2
import json
def printResults(data):
theJSON = json.loads(data)
for i in theJSON[""]
def main():
urlData = ""
webUrl = urllib2.urlopen(urlData)
if (webUrl.getcode() == 200):
data = webUrl.read()
printResults(data)
else:
print "Received error"
if __name__ == '__main__':
main()
If you have an URL returning a json as response, you could try this:
import requests
import json
url = 'http://....' # Your api url
response = requests.get(url)
json_response = response.json()
Now json_response is a list containing dicts. Let's suppose you have this structure:
[
{
'code': ABC,
'avg': 14.5,
'max': 30
},
{
'code': XYZ,
'avg': 11.6,
'max': 21
},
...
]
You can iterate over the list and take every dict into a model.
from yourmodels import CurrentModel
...
for obj in json_response:
cm = CurrentModel()
cm.avg = obj['avg']
cm.max = obj['max']
cm.code = obj['code']
cm.save()
Or you could use a bulk method, but keep in mind that bulk_create does not trigger save method.

groovy.json.JsonSlurper parse JSON

I'm trying to parse a JSON-File in my gradle task.
CODE:
def jsonFile = "../files/json/myJSON.json"
def list = new JsonSlurper().parseText(jsonFile)
JSON - FILE
{
"prepare": {
"installed": [],
"uninstalled": []
},
"config": {
"files": []
}
}
But the code gives me the following exception:
Lexing failed on line: 1, column: 1, while reading '.', no possible valid JSON value or punctuation could be recognized.
And I don't understand why, I also validated my JSON-File on http://jsonlint.com/ and it says that it is a valid JSON!
Above code is trying to parse the string ../files/json/myJSON.json as JSON. Instead use:
def jsonFile = new File("../files/json/myJSON.json")
def map = new JsonSlurper().parse(jsonFile)

How do I `jsonify` a list in Flask? [duplicate]

This question already has answers here:
Return JSON response from Flask view
(15 answers)
Closed 5 years ago.
Currently Flask would raise an error when jsonifying a list.
I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following:
[
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
instead of
{ 'results': [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]}
on responding to a application/json request. How can I return a JSON list in Flask using Jsonify?
You can't but you can do it anyway like this. I needed this for jQuery-File-Upload
import json
# get this object
from flask import Response
#example data:
js = [ { "name" : filename, "size" : st.st_size ,
"url" : url_for('show', filename=filename)} ]
#then do this
return Response(json.dumps(js), mimetype='application/json')
jsonify prevents you from doing this in Flask 0.10 and lower for security reasons.
To do it anyway, just use json.dumps in the Python standard library.
http://docs.python.org/library/json.html#json.dumps
This is working for me. Which version of Flask are you using?
from flask import jsonify
...
#app.route('/test/json')
def test_json():
list = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return jsonify(results = list)
Flask's jsonify() method now serializes top-level arrays as of this commit, available in Flask 0.11 onwards.
For convenience, you can either pass in a Python list: jsonify([1,2,3])
Or pass in a series of args: jsonify(1,2,3)
Both will be serialized to a JSON top-level array: [1,2,3]
Details here: https://flask.palletsprojects.com/en/2.2.x/api/?highlight=jsonify#flask.json.jsonify**
Solved, no fuss. You can be lazy and use jsonify, all you need to do is pass in items=[your list].
Take a look here for the solution
https://github.com/mitsuhiko/flask/issues/510
A list in a flask can be easily jsonify using jsonify like:
from flask import Flask,jsonify
app = Flask(__name__)
tasks = [
{
'id':1,
'task':'this is first task'
},
{
'id':2,
'task':'this is another task'
}
]
#app.route('/app-name/api/v0.1/tasks',methods=['GET'])
def get_tasks():
return jsonify({'tasks':tasks}) #will return the json
if(__name__ == '__main__'):
app.run(debug = True)
If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):
return jsonify({'ans':bin}), 201
Finally, in your client you will obtain something like
{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }
josonify works... But if you intend to just pass an array without the 'results' key, you can use JSON library from python. The following conversion works for me.
import json
#app.route('/test/json')
def test_json():
mylist = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return json.dumps(mylist)