5

With server.py running:

from flask import Flask, request, Response, json

app = Flask(__name__)

@app.route('/test', methods=['GET','POST'])
def route():  
    open_read =  open(r'C:\log.log').read()
    dict_data = {'str': str(), 'list': list(), 'dict': dict()}
    return Response(json.dumps(dict_data), mimetype='text/plain')

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

I would like to send a client request and receive back the open_read and dict_data variables data.

Is there a way to return both variables to the client using flask.Response object?

client:

import json, requests  
response = requests.post('http://127.0.0.1:5000/test')
print '...response: %s' % response.json(), type(response.json())

FULLY WORKING SOLUTION IS POSTED BELOW:

Server:

from flask import Flask, request, Response, json
import base64

app = Flask(__name__)

@app.route('/test', methods=['GET','POST'])
def route():  
    open_read =  open('my_file.zip').read()
    encoded = base64.b64encode(open_read)
    dict_data = {'str': str(), 'list': list(), 'dict': dict(), 'encoded': encoded}
    return Response(json.dumps(dict_data), mimetype='text/plain')

if __name__ == '__main__':
    app.run('0.0.0.0', 5000)

Client:

response = requests.post('http://127.0.0.1:5000/test')
response_json = response.json()
encoded = response_json['encoded']

decoded = base64.b64decode(encoded)

dst_filepath = "my_zip.zip"
with open(dst_filepath, 'w') as _file:
    _file.write(decoded)
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • 3
    IIRC, HTTP Responses in general can only have one body - generally either JSON or the contents of a file, along with its metadata. If your client is built to handle a specific format, you can just make a new dictionary `{"dict_data": dict_data, "open_read": open_read}` - and convert `open_read` to base64 (for example) before sending, then convert it back from base64 after receipt by the client. Otherwise it might be possible to just add fields in `dict_data` to the response header and let the client dig through them? – Green Cloak Guy Nov 16 '18 at 06:00
  • Please post it as the answer so we could up vote it. – alphanumeric Nov 16 '18 at 06:31
  • @GreenCloakGuy is it possible for browser that download multiple file with one url(one request)? – KC. Nov 16 '18 at 10:18
  • I'm not sure, thats why I didn't put it as an answer – Green Cloak Guy Nov 16 '18 at 19:35

0 Answers0