我正在创建一个在本地使用的微服务。从某些输入我每次都生成一个大矩阵。现在我使用json传输数据,但它真的很慢,成为我的应用程序的瓶颈。
这是我的客户方:
headers={'Content-Type': 'application/json'}
data = {'model': 'model_4', \
'input': "this is my input."}
r = requests.post("http://10.0.1.6:3000/api/getFeatureMatrix", headers=headers, data=json.dumps(data))
answer = json.loads(r.text)
我的服务器类似于:
app = Flask(__name__, static_url_path='', static_folder='public')
@app.route('/api/getFeatureMatrix', methods = ['POST'])
def get_feature_matrix():
arguments = request.get_json()
#processing ... generating matrix
return jsonify(matrix=matrix.tolist())
如何发送大型矩阵?
答案 0 :(得分:1)
最后我最终使用
np.save(matrix_path, mat)
return send_file(matrix_path+'.npy')
在客户端,我在加载矩阵之前保存矩阵。
答案 1 :(得分:0)
我认为问题在于矩阵需要时间来生成。这是一个CPU绑定的应用程序
一种解决方案是异步处理请求。意思是:
服务器接收请求并返回202 ACCEPTED以及客户端可以检查矩阵创建进度的链接
客户端检查他得到的返回网址:
但是,Flask一次处理一个请求。所以你需要使用多线程或多处理或greenthreads。
答案 2 :(得分:0)
在客户端,您可以执行以下操作:
with open('binariy.file', 'rb') as f:
file = f.read()
response = requests.post('/endpoint', data=file)
并在服务器端:
import numpy as np
...
@app.route('/endpoint', methods=['POST'])
def endpoint():
filestr = request.data
file = np.fromstring(filestr)