Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

python - Forcing application/json MIME type in a view (Flask)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...