如果文件不存在,请下载并使用Flask发送

时间:2019-07-03 13:04:45

标签: python-3.x flask

机器A(并且它是VM)正在请求机器Flask服务器上的资源B。 如果文件不在B上,则B请求C(文件所在的位置)。 问题是:在B下载完数据后如何将数据传输回A?

这是我的代码:

from flask import Flask, request, render_template
from pathlib import Path
from werkzeug import secure_filename    

import subprocess

app = Flask(__name__)
bashCommand="scp -i ~/.ssh/id_rsa ubuntu@machineC:/home/ubuntu/ostechnix.txt /home/adriano/"
file_content=""
@app.route('/', methods=['GET'])
def lora_frames_handler():
        if request.method == 'GET':
            print("Ca pop:")
            #received_json = request.get_json()
            #print(received_json)
        my_file = Path("/home/adriano/ostechnix.txt")
        if my_file.is_file():
            # file exists
            print("File present")
            file_content=""
        else:
            print("Not present")
            process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) #with this I get the file on local
            output, error = process.communicate()
        with open("/home/adriano/ostechnix.txt") as f:
                file_content=f.read()    #This doesn't work
        return file_content

    if __name__ == '__main__':
        app.run(host="0.0.0.0", port=8080)

感谢您的帮助,

Warok

1 个答案:

答案 0 :(得分:1)

您尝试过flask.send_file吗?

http://flask.pocoo.org/docs/1.0/api/#flask.send_file

这是概念证明:

from flask import Flask, jsonify, request, render_template, send_file
from pathlib import Path
import subprocess

app = Flask(__name__)


@app.route('/')
def proxy_file():
    file_to_send = Path('/path/to/file')
    if not file_to_send.exists():
        # file does not exist
        fetch_file()

    # now we have the file
    return send_file(str(file_to_send))

def fetch_file():
    command = 'command to fetch the file'
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()


if __name__ == "__main__":
    app.run()

如果您需要流传输scp的响应而不先保存响应(例如文件太大,或者您不希望客户端等到文件下载后),那么您需要一种不同的方法,如果您愿意,我可以澄清。