-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathr-task.py
98 lines (81 loc) · 2.81 KB
/
r-task.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import os
import glob
import json
import shutil
import socket
import random
import subprocess
from flask_cors import CORS
from flask import Flask, request, render_template, jsonify, make_response
# This microservice accepts a POSTed JSON with the filenames and
# the contents of one JSON file and one R script.
# It executes the R script and returns the jsonified output of it.
# POST:
# {
# "datafile": "[The name of the JSON file]",
# "data": "[The content of the JSON file]",
# "codefile": "[The name of the R file]",
# "code": "[The content of the R file]"
# }
app = Flask(__name__)
CORS(app)
@app.route("/", methods=["POST","GET"])
def rtask():
# The current working directory
cwd = os.getcwd()
### POST ###
if request.method == "POST":
os.chdir(cwd)
# Create a randomly named temp_folder - avoiding any naming conflicts
temp_folder = str(random.randint(1000000000,9999999999))
os.makedirs(temp_folder)
# Take the posted json data
req = request.get_json()
# Get and save the JSON file
datafile = req["datafile"]
data = req["data"]
if not datafile == "":
df = open("{}/{}".format(temp_folder, datafile), "w+")
df.write(data)
df.close()
# Get and save the Python script
codefile = req["codefile"]
code = req["code"]
if codefile.endswith(".R") and len(codefile) > 2:
cf = open("{}/{}".format(temp_folder, codefile), "w+")
cf.write(code)
cf.close()
else:
# Remove temp_folder
shutil.rmtree(temp_folder)
return jsonify(output="Please enter a proper code filename ending with '.R'")
# Enter temp_files directory and execute code file
os.chdir(temp_folder)
# Try to run the code with subprocess (python3)
try:
process = subprocess.check_output(
["Rscript", codefile],
stderr=subprocess.STDOUT,
universal_newlines=True)
# Check for error message
except subprocess.CalledProcessError as e:
# Leave temp_folder
os.chdir(cwd)
# Remove temp_folder
shutil.rmtree(temp_folder)
return jsonify(output=e.output)
else:
# If run successfully
# Leave temp_folder
os.chdir(cwd)
# Remove temp_folder
shutil.rmtree(temp_folder)
# Return the output
return jsonify(output=process.rstrip())
### GET ###
else:
os.chdir(cwd)
# Render the native interface to communicate with the microservice
return render_template("r-task.html")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=50002, debug=True)