Issue
Machine A (and it's a VM) is requesting a resource on machine B which is a Flask server. If the file is not present on B, B request C(where the file is). The question is: how to transfer data back to A after B downloaded it?
Here is my code:
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)
Thanks for the help
Solution
Did you try flask.send_file
?
http://flask.pocoo.org/docs/1.0/api/#flask.send_file
Here's a proof of concept:
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()
If you need to stream the response from scp
without saving it first (like when the file is too large, or you dont want the client to wait until file is downloaded), then you need a different approach, which I can clarify if you like.
Answered By - abdusco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.