Python 使Flask发送_文件更快

Python 使Flask发送_文件更快,python,file,flask,optimization,io,Python,File,Flask,Optimization,Io,我想写一个简单的函数。它将从远程服务器抓取文件,然后抛出paramiko,然后我想通过将url传递到我的浏览器来下载它。 但是flask.send_文件对我来说非常慢。 sftp连接需要约0.5秒,但发送_文件(io.BytesIO(file_obj.read())需要约15秒 下面是如何使用它 返回发送文件( io.BytesIO(文件_obj.read()), mimetype=mimetype, 如附件=真, 附件\文件名=附件\文件名 ) 导入io 从flask导入发送_文件,json

我想写一个简单的函数。它将从远程服务器抓取文件,然后抛出paramiko,然后我想通过将url传递到我的浏览器来下载它。 但是flask.send_文件对我来说非常慢。 sftp连接需要约0.5秒,但发送_文件(io.BytesIO(file_obj.read())需要约15秒

下面是如何使用它

返回发送文件(
io.BytesIO(文件_obj.read()),
mimetype=mimetype,
如附件=真,
附件\文件名=附件\文件名
)
导入io
从flask导入发送_文件,jsonify
进口帕拉米科
def sftp_连接(远程路径):
key=paramiko.RSAKey.from_private_key_文件(RSA_key)
使用paramiko.SSHClient()作为客户端:
client.set\缺少\主机\密钥\策略(paramiko.AutoAddPolicy())
client.connect(pkey=key,**服务器连接)
使用client.open_sftp()作为sftp:
尝试:
file_obj=sftp.file(远程路径,mode='rb')
除IOError外:
返回jsonify({
“错误”:True,
'消息':'目录中没有这样的文件'
})
返回发送文件(
io.BytesIO(文件_obj.read()),
mimetype=mimetype,
如附件=真,
附件\文件名=附件\文件名
)

好的,我不知道答案,但即使这样也比4倍快。 在这里为子孙后代居住

@app.route('/sftp/<path:remote_path>')
@file_cleanup
def file_download(remote_path, local_path, file_name):
key = paramiko.RSAKey.from_private_key_file(RSA_KEY)

with paramiko.SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(pkey=key, **SERVER_CONN)

    with client.open_sftp() as sftp:
        try:
            sftp.get(remote_path, local_path)
        except IOError:
            return jsonify({
                'error': True,
                'message': 'no such file in directory'
            })

return send_from_directory(
    directory=app.config['UPLOAD_FOLDER'],
    filename=file_name,
    as_attachment=True,
    attachment_filename=file_name,
)
def file_cleanup(func):
def decorated_func(*args, **kwargs):
    file_name = get_file_name(kwargs['remote_path'])
    local_path = Path(app.config['UPLOAD_FOLDER'], file_name)

    kwargs['file_name'] = file_name
    kwargs['local_path'] = local_path

    result = func(*args, **kwargs)

    os.remove(local_path)
    return result
return decorated_func