33from django .conf import settings
44from .models import Exercise
55import ast
6+ import sys
67import json
8+ import tempfile
9+ from pylint import epylint as lint
10+ from django .views .decorators .csrf import csrf_exempt
711
812#TODO: Too many hardcoded strings, review
913def index (request ):
@@ -30,3 +34,50 @@ def request_code(request, exercise_id):
3034 if difficulty != None :
3135 print ('EXERCISE: ' , exercise_id , 'DIFFICULTY: ' , difficulty )
3236 return HttpResponse (data , content_type = "text/plain" )
37+
38+ @csrf_exempt
39+ def evaluate_style (request ):
40+ print ("1º" )
41+ try :
42+ python_code = get_python_code (request )
43+ code_file = tempfile .NamedTemporaryFile (delete = False )
44+ code_file .write (python_code .encode ())
45+ code_file .seek (0 )
46+ options = code_file .name + ' --enable=similarities' + " --disable=C0114,C0116"
47+ (stdout , stderr ) = lint .py_run (options , return_std = True )
48+ code_file .seek (0 )
49+ code_file .close ()
50+ result = stdout .getvalue ()
51+ name = code_file .name .split ('/' )[- 1 ]
52+ result = result [(result .find (name ) + len (name ) - 1 ):]
53+ result = result .replace (code_file .name , 'mycode' )
54+ result = result [result .find ('\n ' ):]
55+ init_index = result .find ('rated at ' )
56+ score = - 1
57+ if init_index != - 1 :
58+ init_index += len ('rated at ' )
59+ final_index = result .find ('/10' , init_index )
60+ score = round (float (result [init_index :final_index ]) * 10 , 2 )
61+ response = HttpResponse (result + "\n " + str (score ), content_type = "text/plain" )
62+ return response
63+ except Exception as ex :
64+ print ("2º" )
65+ print (ex )
66+ response = HttpResponse ("Error" , content_type = "text/plain" )
67+ return response
68+
69+
70+
71+
72+ def get_python_code (request ):
73+ python_code = request .GET .get ('python_code' , None )
74+ if not python_code :
75+ body_unicode = request .body .decode ('utf-8' )
76+ body_unicode = body_unicode [0 :18 ] + body_unicode [18 : len (body_unicode ) - 2 ].replace ('"' ,
77+ "'" ) + body_unicode [- 2 :]
78+ body = json .loads (body_unicode , strict = False )
79+ python_code = body ['python_code' ]
80+ python_code = python_code .lstrip ('\\ ' ).lstrip ('"' )
81+ python_code = python_code .replace ('\\ n' , '\n ' )
82+ python_code = python_code .replace ('\\ "' , '"' ).replace ("\\ '" , "'" )
83+ return python_code
0 commit comments