|
1 | | -from flask import Flask, request, jsonify, render_template |
| 1 | +from flask import Flask, request, jsonify, send_from_directory |
2 | 2 | from werkzeug.utils import secure_filename |
3 | 3 | import os |
| 4 | +from subprocess import call |
| 5 | +from pathlib import Path |
4 | 6 |
|
5 | | - |
| 7 | +EXECUTABLE_FOLDER = "./executable_files" |
| 8 | +DOWNLOAD_FOLDER = "./download_files" |
6 | 9 | UPLOAD_FOLDER = "./uploaded_files" |
7 | 10 |
|
8 | 11 | if not os.path.exists(UPLOAD_FOLDER): |
|
11 | 14 | app = Flask(__name__) |
12 | 15 | app.secret_key = "secret key" |
13 | 16 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER |
| 17 | +app.config['EXECUTABLE_FOLDER'] = EXECUTABLE_FOLDER |
| 18 | +app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER |
14 | 19 |
|
15 | 20 |
|
16 | 21 | @app.route('/upload', methods=['POST']) |
@@ -45,5 +50,53 @@ def upload(): |
45 | 50 | resp.status_code = 500 |
46 | 51 | return resp |
47 | 52 |
|
| 53 | + |
| 54 | +@app.route('/execute', methods=['POST']) |
| 55 | +def execute(): |
| 56 | + if 'file' not in request.files: |
| 57 | + resp = jsonify({'message' : 'No file in the request'}) |
| 58 | + resp.status_code = 400 |
| 59 | + return resp |
| 60 | + |
| 61 | + |
| 62 | + file = request.files['file'] |
| 63 | + if file.filename == '': |
| 64 | + resp = jsonify({'message' : 'No file selected for Executing'}) |
| 65 | + resp.status_code = 400 |
| 66 | + return resp |
| 67 | + |
| 68 | + errors = {} |
| 69 | + success = False |
| 70 | + |
| 71 | + |
| 72 | + if file: |
| 73 | + filename = secure_filename(file.filename) |
| 74 | + file.save(os.path.join(app.config['EXECUTABLE_FOLDER'], filename)) |
| 75 | + output_file = filename + ".out" |
| 76 | + path = app.config['EXECUTABLE_FOLDER']+"/"+filename |
| 77 | + call(["python3", path, ">", output_file, "&"]) |
| 78 | + success = True |
| 79 | + |
| 80 | + if success: |
| 81 | + resp = jsonify({'message' : 'Files successfully executed'}) |
| 82 | + resp.status_code = 201 |
| 83 | + return resp |
| 84 | + else: |
| 85 | + resp = jsonify(errors) |
| 86 | + resp.status_code = 500 |
| 87 | + return resp |
| 88 | + |
| 89 | + |
| 90 | + |
| 91 | +@app.route('/download/<file_name>', methods=['POST','GET']) |
| 92 | +def download(file_name): |
| 93 | + try: |
| 94 | + return send_from_directory(app.config["DOWNLOAD_FOLDER"], file_name, as_attachment=True) |
| 95 | + except: |
| 96 | + resp = jsonify({'message' : 'file not found'}) |
| 97 | + resp.status_code = 400 |
| 98 | + return resp |
| 99 | + |
| 100 | + |
48 | 101 | if __name__ == "__main__": |
49 | 102 | app.run(host="0.0.0.0") |
0 commit comments