forked from nawalgupta/PythonBuddy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
272 lines (237 loc) · 7.53 KB
/
app.py
File metadata and controls
272 lines (237 loc) · 7.53 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Created originally by Ethan Chiu 10/25/16
v2.0.0 created on 8/4/18
Complete redesign for efficiency and scalability
Uses Python 3 now
"""
from flask import Flask, render_template, request, jsonify, session
from flask_socketio import SocketIO
import eventlet.wsgi
import tempfile
import mmap
import os
from datetime import datetime
from pylint import epylint as lint
from subprocess import Popen, PIPE, STDOUT
from multiprocessing import Pool, cpu_count
# Configure Flask App
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
socketio = SocketIO(app)
# Get number of cores for multiprocessing
num_cores = cpu_count()
@app.route('/')
def index():
"""Display home page
:return: index.html
Initializes session variables for tracking time between running code.
"""
session["count"] = 0
session["time_now"] = datetime.now()
return render_template("index.html")
@app.route('/check_code')
def check_code():
"""Run pylint on code and get output
:return: JSON object of pylint errors
{
{
"code":...,
"error": ...,
"message": ...,
"line": ...,
"error_info": ...,
}
...
}
For more customization, please look at Pylint's library code:
https://github.com/PyCQA/pylint/blob/master/pylint/lint.py
"""
#Get textarea text from AJAX call
text = request.args.get('text')
# Session to handle multiple users at one time
session["code"] = text
text = session["code"]
output = evaluate_pylint(text)
# MANAGER.astroid_cache.clear()
return jsonify(output)
# Run python in secure system
@app.route('/run_code')
def run_code():
"""Run python 3 code
:return: JSON object of python 3 output
{
...
}
"""
# Don't run too many times
if slow():
return jsonify("Running code too much within a short time period. Please wait a few seconds before clicking \"Run\" each time.")
session["time_now"] = datetime.now()
output = None
cmd = 'python ' + session["file_name"]
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
return jsonify(output.decode('utf-8'))
# Slow down if user clicks "Run" too many times
def slow():
session["count"] += 1
time = datetime.now() - session["time_now"]
if float(session["count"]) / float(time.total_seconds()) > 5:
return True
return False
def evaluate_pylint(text):
"""Create temp files for pylint parsing on user code
:param text: user code
:return: dictionary of pylint errors:
{
{
"code":...,
"error": ...,
"message": ...,
"line": ...,
"error_info": ...,
}
...
}
"""
# Open temp file for specific session.
# IF it doesn't exist (aka the key doesn't exist), create one
try:
session["file_name"]
f = open(session["file_name"], "w")
for t in text:
f.write(t)
f.flush()
except Exception as e:
with tempfile.NamedTemporaryFile(delete=False) as temp:
session["file_name"] = temp.name
for t in text:
temp.write(t.encode("utf-8"))
temp.flush()
try:
ARGS = " -r n --disable=R,C"
(pylint_stdout, pylint_stderr) = lint.py_run(session["file_name"]+ARGS, return_std=True)
except Exception as e:
raise Exception(e)
if pylint_stderr.getvalue():
raise Exception("Issue with pylint configuration")
formatted_dict = format_errors(pylint_stdout.getvalue())
return formatted_dict
def process_error(error):
"""Formats error message into dictionary
:param error: pylint error full text
:return: dictionary of error as:
{
"code":...,
"error": ...,
"message": ...,
"line": ...,
"error_info": ...,
}
"""
# Return None if not an error or warning
if error == " " or error is None:
return None
list_words = error.split()
if len(list_words) < 3:
return None
if error.find("Your code has been rated at") > -1:
return None
line_num = error.split(":")[1]
# list_words.pop(0)
error_yet = False
message_yet = False
first_time = True
i = 0
# error_code=None
length = len(list_words)
while i < length:
word = list_words[i]
if (word == "error" or word == "warning") and first_time:
error_yet = True
first_time = False
i += 1
continue
if error_yet:
error_code = word[1:-1]
error_string = list_words[i+1][:-1]
i = i + 3
error_yet = False
message_yet = True
continue
if message_yet:
full_message = ' '.join(list_words[i:length-1])
break
i += 1
error_info = find_error(error_code)
return {
"code": error_code,
"error": error_string,
"message": full_message,
"line": line_num,
"error_info": error_info,
}
def format_errors(pylint_text):
"""Format errors into parsable nested dictionary
:param pylint_text: original pylint output
:return: dictionary of errors as:
{
{
"code":...,
"error": ...,
"message": ...,
"line": ...,
"error_info": ...,
}
...
}
"""
errors_list = pylint_text.splitlines(True)
# If there is not an error, return nothing
if "--------------------------------------------------------------------" in errors_list[1] and \
"Your code has been rated at" in errors_list[2] and "module" not in errors_list[0]:
return None
errors_list.pop(0)
pylint_dict = {}
try:
pool = Pool(num_cores)
pylint_dict = pool.map(process_error, errors_list)
finally:
pool.close()
pool.join()
return pylint_dict
# count = 0
# for error in errors_list:
# pylint_dict[count]=process_error(error)
# count +=1
return pylint_dict
def find_error(id):
"""Find relevant info about pylint error
:param id: pylint error id
:return: returns error message description
pylint_errors.txt is the result from "pylint --list-msgs"
"""
file = open('pylint_errors.txt', 'r')
s = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
location = s.find(id.encode())
if location != -1:
search_text = s[location:]
lines = search_text.splitlines(True)
error_message = []
for l in lines:
if l.startswith(':'.encode()):
full_message = b''.join(error_message)
full_message = full_message.decode('utf-8')
replaced = id+"):"
full_message = full_message.replace(replaced, "")
full_message = full_message.replace("Used", "Occurs")
return full_message
error_message.append(l)
return "No information at the moment"
@socketio.on('disconnect', namespace='/check_disconnect')
def disconnect():
"""Remove temp file associated with current session"""
os.remove(session["file_name"])
if __name__ == "__main__":
"""Initialize app"""
socketio.run(app)