-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-v2.py
86 lines (70 loc) · 2.4 KB
/
api-v2.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
from os import error
from flask import Flask, jsonify, request
from flask import Response
from flask_cors import CORS
import sys
from io import StringIO
import contextlib
import traceback
class InterpreterError(Exception): pass
app = Flask(__name__)
cors = CORS(app, resources={r"/tester": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
def execute_code(code, inputs):
res = ""
res_list = []
te = 1
for i in inputs:
if te != 1: res += "\n"
res += "---TEST " + str(te) + " (input = " + str(i) + ")---"
aux = {}
try:
codeObejct = compile("input = " + str(i) + "\n" + code, 'sumstring', 'exec')
loc = {}
exec(codeObejct, globals(), loc)
return_workaround = loc['output']
to_print = loc['to_print']
for printer in to_print:
res += "\n> " + str(printer)
res += "\nYOUR SOLUTION: " + str(return_workaround)
res_list.append(return_workaround)
except SyntaxError as err:
error_class = err.__class__.__name__
detail = err.args[0]
line_number = err.lineno
res += "\nERROR:\n%s at line %d of %s: %s" % (error_class, line_number-2, "source string", detail)
break
except Exception as err:
error_class = err.__class__.__name__
detail = err.args[0]
cl, exc, tb = sys.exc_info()
line_number = traceback.extract_tb(tb)[-1][1]
res += "\nERROR:\n%s at line %d of %s: %s" % (error_class, line_number-2, "source string", detail)
break
te += 1
return (res, res_list)
#Testing Route
@app.route('/', methods=['GET'])
def getDefault():
return jsonify({'response': 'Hello to my users api!'})
#Testing Route
@app.route('/tester', methods=['POST'])
def tester():
inputs = request.json['inputs']
solutions = request.json['solutions']
code = request.json['code']
"""
Example
{
"inputs": [0,1,2,3],
"solutions": [0,2,4,6],
"code": "output = input*2"
}
"""
var = execute_code("to_print = []\n" + code.replace("print", "to_print.append"), inputs)
equal = True
if var[1] != solutions:
equal = False
return jsonify({'console': var[0], 'result':equal, 'solution': var[1]})
if __name__ == '__main__':
app.run(debug=True, port=8000)