Python Flask Basics Character Builder Cookies

Lewis Cowles
Lewis Cowles
74,901 Points

Why is jsonify not being used?

So basically over the weekend I was playing with flask (prior to taking your awesome course), but there are a few things I have noticed I think could make it more beginner friendly, such as import'ing jsonify from flask, and using it's magic to avoid the whole complex type nonsense of ImmutableMultiDicts, converting tuples to dicts etc

Here is a piece of code I used to dump out info on various python objects to json, so I could learn the data-structure of flask request object and generally play with flask... (Aplogies for line-lengths etc, I have very little flask experience and mostly code Python during weekends for hobby projects NFP work etc)

from flask import Flask
from flask import request
from flask import jsonify
from flask import json
from flask import g
import logging
import time

app = Flask(__name__)

def hello():
    return "Hello World"

@app.route("/debug", methods=['GET', 'POST','PUT'])
def debug():
    return jsonify({'ip': request.remote_addr,'args':request.args,"HTTPMethod":request.method,"formdata":request.form,'files':repr(request.files)}), 200

def before_request():
    g.start = time.time()

def after_request(response):
    d = json.loads( response.get_data() )
    d['executiontime'] = ( time.time() - g.start )
    response.set_data( json.dumps(d) )
    return response

def internal_error(error):
    return "500 error"

if __name__ == "__main__":'', port=8080)

2 Answers

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Yes, jsonify would have hidden the work going on behind the scenes of converting ImmutableMultiDIct to dict so we could turn it into json. Now, why did I not use jsonify? Because it would hide the word going on... :)

Basically, I want to make sure you know what's going on. None of this should be magic. Also, jsonify() just creates a response. We need to be able to read and write JSON outside of the response (we never actually return JSON, we just stick it into a cookie). We could have used flask.json but, with json built into Python, why not use the default, always available one?

Lewis Cowles
Lewis Cowles
74,901 Points

Hi Kenneth,

Great points, I had no clue jsonify returned a response object (obviously I have always returned it's result lol). Flask is really awesome though and there were some little tricks I have picked up from your courses to help me to push some of my proof of concepts to the next level, so thanks and also thanks for reaching out to me! Hope your looking forward to Xmas or at least the season in the even you don't celebrate ;)