I can't figure out how to force the MIME type application/json
for a view in Flask. Here is a simple view I've thrown together for demonstration purposes:
@app.route("/") def testView(): ret = '{"data": "JSON string example"}' return ret
The JSON string (held in variable ret
) is gathered from elsewhere (using stdout from another program using subprocess
) so I can't use jsonify
provided with Flask.
I've had a look at the "Returning Json" Documentation and this Stackoverflow question but I haven't had any luck so far. I've been looking around for awhile now & will continue searching but thought I'd ask here just in case anyone has come across this.
Thanks.
See the answer below
The solution:
@app.route("/") def testView(): ret = '{"data": "JSON string example"}' resp = Response(response=ret, status=200, mimetype="application/json") return resp
I found this website useful: Implementing a RESTful Web API with Python & Flask
If you use:
from flask import jsonify
and then in your code:
return jsonify(somedict)
then jsonify() automatically sets the mime type to 'application/json'
Edit:
This was previously considered a risk, but not anymore, and Flask has also updated its recommendation: "ECMAScript 5 closed this vulnerability, so only extremely old browsers are still vulnerable. All of these browsers have other more serious vulnerabilities, so this behavior was changed and jsonify() now supports serializing arrays." http://flask.pocoo.org/docs/1.0/security/#json-security
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With