【问题标题】:make Flask send_file faster使 Flask send_file 更快
【发布时间】:2019-07-25 16:17:44
【问题描述】:

我想写一个简单的函数。它会从远程服务器获取文件 throw paramiko,然后我想通过将 url 传递给我的浏览器来下载它。 但是 flask.send_file 对我来说工作得非常慢。 sftp 连接需要 ~0.5s 但 send_file(io.BytesIO(file_obj.read())) 需要 ~15s。

这里是如何使用它

return send_file(
       io.BytesIO(file_obj.read()),
       mimetype=mimetype,
       as_attachment=True,
       attachment_filename=attachment_filename
   )
import io

from flask import send_file, jsonify
import paramiko


def sftp_conn(remote_path):
   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:
               file_obj = sftp.file(remote_path, mode='rb')
           except IOError:
               return jsonify({
                   'error': True,
                   'message': 'no such file in directory'
               })
           return send_file(
               io.BytesIO(file_obj.read()),
               mimetype=mimetype,
               as_attachment=True,
               attachment_filename=attachment_filename
           )

【问题讨论】:

    标签: python file flask optimization io


    【解决方案1】:

    好的,我不知道答案,但即使这样也快 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,
    )
    

    这是@file_cleanup 装饰器

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-24
      • 2016-06-13
      • 2023-01-27
      • 2021-05-18
      • 2020-11-11
      • 1970-01-01
      • 2021-07-04
      • 2022-01-21
      相关资源
      最近更新 更多