python - Return JSON and a File -


how can return json response , file response:

right this:

runnumber = "a0001" response = none try:     response = make_response("line one\r\nline two\r\n")     response.headers["content-disposition"] = "attachment; filename=" + runnumber + ".txt" except mycustomexception e:     response = jsonify(error=e.value, runnumber=runnumber) except:     raise return(response) 

but allows me return json or file. in cases, want return both.

[edit:] case want return json , file when there warning file contents user should check before using file.

if not possible, add warning contents of file.

you cannot return 2 responses. return one.

that means if really need return both json , file need come scheme lets return 2 in one response , let client separate out file , json parts again.

there no standard this. whatever come need documented clients handle explicitly.

you use custom header store json data, example:

response = make_response("line one\r\nline two\r\n") response.headers["content-disposition"] = "attachment; filename=" + runnumber + ".txt" response.headers['x-extra-info-json'] = json.dumps(some_object) 

or put file contents in json data. json isn't greatest format binary data, may want encode binary data base64 first:

filedata = "line one\r\nline two\r\n".encode('base64') return jsonify(name=runnumber + '.txt', data=filedata) 

or create multipart mime document, in same way post multipart/form-data body works.

what pick depends on use-cases (what kind of clients using api) , size of data (megabytes of file data in json response not workable).


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -