With Flask server configured to support compression:
server.py
import os
import json
import tempfile
from flask import Flask, request
from flask_compress import Compress
app = Flask(__name__)
app.config['COMPRESS_MIMETYPES'] = set(['text/html', 'text/css', 'text/xml', 'application/json', 'application/javascript'])
app.config['COMPRESS_LEVEL'] = 6
app.config['COMPRESS_MIN_SIZE'] = 500
Compress(app)
@app.route('/', methods=['GET', 'POST'])
def index():
print('get_json: %s get_data: %s' % (type(request.get_json()), type(request.get_data())) )
for key, value in request.files.items():
if value.content_type == 'application/json':
data = json.loads(value.stream.read())
print('got json data %s' % data)
elif value.content_type == 'application/octet-stream':
dst_filepath = os.path.join(tempfile.mktemp(), value.filename)
if not os.path.exists(os.path.dirname(dst_filepath)):
os.makedirs(os.path.dirname(dst_filepath))
with open(dst_filepath, 'wb') as fd:
for chunk in value:
fd.write(chunk)
print('saved file as %s' % dst_filepath)
return 'OK', 200
app.run('0.0.0.0', 80)
the client.py sends a singe request with a json dictionary and a file data.
client.py
import requests
import json
import os
payload = {"param_1": "value_1", "param_2": "value_2"}
filepath = '/file/path/to/local_file.zip'
data = {'json': ('some-json', json.dumps(payload), 'application/json'),
'file': (os.path.basename(filepath), open(filepath, 'rb'), 'application/octet-stream')}
response = requests.post('http://127.0.0.1:80/', files = data)
To minimize the upload time I would like to send the request with the file data (along with the json data) compressed. How to achieve it?
Edited later:
It looks like there is a headers argument for request.post() method that could be used to specify the encoding type.
response = requests.post('http://127.0.0.1:80/',
files = data,
headers = {'Accept-Encoding': 'gzip'})
But how do we compress the data dictionary that is used to store the file data and the json dictionary?