How can I use Json as Django view context - python

I have a string like:
daily_program = "{"Training Set":["abc","dxf","gfh"],"Nutrition Set":["acd","dbd","cdf"]}"
I want to use it as a context dictionary and pass it to the template in Django. Such as:
def program(request):
context = json.loads(daily_program)
return render_to_response('program.html',context,RequestContext(request))
Its acting like python Dict. when I print out the result. But I cant use it as a context in template such as:
<div>{{Training}}</div>
Is there any way to is use json object as a context dictionary ?

dialy_program should read like so, with single quotes '' to avoid a syntax error with building the string:
daily_program = '{"Training":["abc","dxf","gfh"],"Nutrition":["acd","dbd","cdf"]}'

Related

Added escaped quotes to JSON in Flask app with mongoDB

I am trying to create API for my Flask project. I have data stored in mongoDB and for building API I am using flask_restful. The problem is that in JSON are added escaped quotes and I cannot figure why and I rather have my JSON without them.
This is how my get function looks like:
from flask_restful import Resource
import json
from bson import json_util
class Harvests(Resource):
def get(self):
json_docs = []
for doc in db.collection.find():
json_doc = json.dumps(doc, default=json_util.default)
json_docs.append(json_doc)
return json_docs
In app.py it is just like that
api = Api(app)
api.add_resource(Harvests, '/api/harvests')
And I get JSON with escaped quotes (in browser or with curl)
[
"{\"_id\": {\"$oid\": \"5c05429cc4247917d66163a7\"},...
]
If I try this outside Flask (print JSON from mongo) and it works just fine. I tried use .replace(), but I think is not most elegant solution, but it did not work anyway. Any idea how I should get rid off these backslashes?
What you see is absolutely what you should expect to see according to your code, so I think there is a misunderstanding at some point. Let me explain what you are doing.
You convert each doc (a data structure) into a jsonified version (a string) of this data. Then you gather these strings in a list. Later you see this list, and of course you see a list of strings. Each of these strings contains a jsonified version of a data structure (a dictionary with opening braces, keys and values inside, and each key is a string itself with quotes, so these quotes are escaped within the jsonified string).
I recommend to collect your documents into a list and then convert that list to json instead:
def get(self):
docs = []
for doc in db.collection.find():
docs.append(doc)
return json.dumps(docs, default=json_util.default)
This way you get one json string representing the list of docs.
Maybe your framework is already applying a jsonifying automatically, in this case just don't do this step yourself:
return docs
Just use this instead.

Flask - How can I retrieve the value of input by the type?

How can I retrieve the value passed by POST request by type of input?
When I search, I only find the ones that retrieve the input name attribute (for example: request.form['text'], when the entry name is "text"). I'd like to redeem by type, not by name.
Note:
There are multiple input tags, not just one. In that way, if I'm not mistaken, there should be something like the getlist method.
I tried using request.get_data(as_text=True), but the type of output is unicode and I would like array.
#app.route('/finalizar', methods=['POST'])
def preencherExames():
if request.method == 'POST':
text = request.get_data(as_text=True)
return render_template('finalizar.html', title='Selecionar exames', results=text)
If I'm reading Flask internals correctly you don't have access to the type property of your form field when it gets to Flask
if you can modify names of the fields in your form I would suggest something like this:
for form_field_name in request.form.keys():
if form_field_name.endswith('_text'):
for value in request.form.getlist(form_field_name):
# process values
where you add suffix _text to your fields of the type text
I know it is ugly, but I hope it will help
Use getlist if you want a list of values:
request.form.getlist('name')

airflow rendered template becomes a string

I'm attempting to use the jinja templating to parse some json found in xcom into a dictionary. Note below that Operator and templated_field are psuedo-code.
def xcom_from_json(xcom):
xcom_loaded = json.loads(xcom)
logging.info(pformat(f'xcom loaded: {xcom_loaded}', indent=3))
return xcom_loaded
PythonOperator(python_callable=some_callable,
op_args=[f'{{{{ (ti.xcom_pull("{task_id}") | xcom_from_json)["data"]["stats"] }}}}'])
The above works, almost. In the some_callable method I get the parsed jinja, but it comes out as a stringified dict instead of a raw dict. This doesn't make sense, because you can see the structure being traversed as a dict in the jinja template. Does jinja stringify everything coming out of a template? If yes, is there a way to not do that?
A rendered jinja template is always going to return a string. What you can do instead is fetch the XCom value from within the python method instead.
def some_callable(task_id, **context):
stats = json.loads(context['ti'].xcom_pull(task_id)['data']['stats'])
PythonOperator(
...
python_callable=some_callable,
op_args=[f'{task_id}'],
provide_context=True)
Note that you must provide context, which gives the python method the same access to values a jinja template has.

Pass a variable to extract from JSON String in Python?

I have below JSON String. Now I want to extract each individual field from that JSON string.
So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.
Below is my python script -
#!/usr/bin/python
import json
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
def parse_json(data):
jj = json.loads(jsonData)
return jj['+data+']
print parse_json('pp')
Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -
return jj['+data+']
KeyError: '+data+'
Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?
You probably just want this:
return jj[data]
Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.
Just use data parameter itself.
Replace following line:
return jj['+data+'] # lookup with `+data+`, not `pp`
with:
return jj[data]

Python: list to JSON

I am trying to use Django with jquery UI autocomplete but having trouble sending response.
Here is my code:
def ajax_tags_autocomplete(request):
""" Autocomplete for tag list """
beginning_of_title = request.GET.get('term', '')
tags_found = Tag.objects.values_list('title', flat=True).filter(title__startswith=beginning_of_title)
return HttpResponse(json.dumps(tags_found), mimetype='application/json')
I get an error:
[u"php"] is not JSON serializable
Why? It is not possible to serialize a list? What should I pass to the serializer, then?
I would be greatful for any advice.
Are you sure it's actually a list containing unicode objects and not a list containing some database objects? The u"php" might just be the repr() of the object.
Try json.dumps([unicode(t) for t in tags_found]) or json.dumps(map(unicode, tags_found))

Categories

Resources