jsonify response mime type
According to the jQuery-File-Upload docs Iframe based uploads require a Content-type of text/plain or text/html for the JSON response
So I can't use jsonify as it sets the response mime type to application/json and must use code like this
resp = make_response(json.dumps({'error': 'File too big'}))
if request.headers.get('Accept', '').find('application/json') > -1:
resp.mimetype = 'application/json'
else:
resp.mimetype = 'text/plain'
return resp
In instead of
return jsonify({'error': 'File too big'})
Am I missing something? How clueless would I be if I were to suggest adding some option to jsonify to customize the response mime type depending on the requested mime type?
Did you really have to support browsers that require IFrames for file uploads? :) http://caniuse.com/xhr2
Also, you usually need/want to wrap the response in a textarea, too, when using the iframe method...
IE <= 9 is still more than 30% market share. I didn't understand the second part. You mean that if I use the response in a text area I cant send a json formated response? Notice that even if the response mime type is text/plain it is still json.
Looks that the better way it's improve jsonify with a option parameter for have a custom response mime type.
I think your code can be abbreviated to
resp = jsonify({'error': 'File too big'})
if 'application/json' not in request.headers.get('Accept', ''):
resp.mimetype = 'text/plain'
return resp
I'm :+1: on the proposal.
I think your code can be abbreviated to... Nice catch.
My ideia is to have two named parameters; alternate=None and force_alternate=False. If application/json is not in the incoming Accept header jsonify will set the mimetype to the alternate one if alternate is not None . if force_alternate then it will set the mimetype to the alternate value regardless of the incoming Accept header. if alternate is None and force_alternate then no mimetype header is generated.
Right now I have no time to the coding and repository work. So anyone be free to use this however it sees fit.
Okay, i am retracting my :+1:. If we would add features that handle the Accept header to Flask, i think we should start with adding a feature to the routing system which i would call "Accept-based matching", which operates similar to Werkzeug's "host-based matching".
However, all of this is out-of-scope for Flask IMO. Flask-Restful and a few others have filled this gap in a much nicer way than a microframework could ever support.
What we could do, however, is emit a warning or even an exception if the response mimetype is not in the Accept header. I think this kind of thing is not usecase specific and always a good idea.
You can already override the mimetype so I don't see this as something that needs to be in Flask itself. Especially if it's just a workaround for limitations in browsers that will go away.