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
|
# coding=utf-8
import threading
import python.engine
from db.models import Problem
from . import problems
__all__ = ['PythonSession']
class PythonSession(object):
"""Abstracts a Python session.
Only public methods are available to the outside world due to the use of multiprocessing managers.
Therefore prefix any private methods with an underscore (_).
No properties are accessible; use getters and setters instead.
Values are passed by value instead of by reference (deep copy!).
"""
def __init__(self):
self._access_lock = threading.Lock()
self._interpreter = None
def create(self):
with self._access_lock:
if not self._interpreter:
self._interpreter = python.engine.create()
def pull(self):
with self._access_lock:
if self._interpreter is None:
return 'Python is not running'
return python.engine.pull(self._interpreter)
def push(self, stdin):
with self._access_lock:
if self._interpreter is not None:
python.engine.push(self._interpreter, stdin)
def destroy(self):
with self._access_lock:
if self._interpreter is not None:
python.engine.destroy(self._interpreter)
self._interpreter = None
def __del__(self):
if hasattr(self, '_interpreter') and self._interpreter is not None:
python.engine.destroy(self._interpreter)
self._interpreter = None
def hint(self, user_id, problem_id, program):
language, problem_group, problem = Problem.identifier(problem_id)
# Try problem-specific hints.
problem_module = problems.load_problem(language, problem_group, problem, 'common')
if hasattr(problem_module, 'hint'):
hints = problem_module.hint(program)
if hints:
return hints
# Finally return a generic "try thinking a bit" message.
return [{'id': 'no_hint'}]
def test(self, user_id, problem_id, program):
language, problem_group, problem = Problem.identifier(problem_id)
problem_module = problems.load_problem(language, problem_group, problem, 'common')
try:
n_correct, n_all = problem_module.test(program)
return [{'id': 'test_results', 'args': {'passed': n_correct, 'total': n_all}}]
except AttributeError as ex:
return [{'id': 'test_results', 'args': {'passed': 0, 'total': 0}}]
|