使用py_compile时没有使用SyntaxError

时间:2016-02-10 08:46:30

标签: python python-2.7 api django-rest-framework

我在python中的一个类中定义了以下函数,我正在尝试从外部源编译python代码。 python代码进来,写入文件然后将文件发送到下面的函数。 当我试图将该函数称为:

self._check_code_for_errors(source_file)

它不执行except块,我正在捕获SyntaxError异常。

def _check_code_for_errors(self, source_file):
    try:
        file_ = open(source_file.name, 'r')
        py_compile.compile(file_.name)
    except SyntaxError:
        return {'errors': 'You have a problem in your syntax'}
    except (OSError, IOError):
        return {'errors': 'Some error has occurred, please try again'}

更新

class ValidatePythonCodeViewSet(generics.CreateAPIView):
    parser_classes = (PlainTextParser, )
    """
    The view set below accepts code from post request, executes it and then
    returns the appropriate results (error or output)
    """

    def _write_code_to_file(self, source):
        # file is a reserved word in python 2.x, so using file_
        with open('tempPythonCode.py', 'w') as file_:
            file_.write(source)

        return file_

    def _check_code_for_errors(self, source_file):
        try:
            file_ = open(source_file.name, 'r')
            py_compile.compile(file_.name, doraise=True)
        except py_compile.PyCompileError:
            return {'errors': 'You have a problem in your syntax'}

    def post(self, request, *args, **kwargs):
        source = request.data

        if not source:
            raise InformationMissingInRequestError()
        else:
            source_file = self._write_code_to_file(source)
            response = self._check_code_for_errors(source_file)

        if response.get('errors', None):
            return Response(response, status=status.HTTP_400_BAD_REQUEST)
        else:
            #execute code here and return
            pass

        return Response(response, status=status.HTTP_200_OK)

我正在提出的要求是: Request

回溯

  File "tempPythonCode.py", line 1
    import os\nprint 'hi
                       ^
SyntaxError: unexpected character after line continuation character

Internal Server Error: /api/python/
Traceback (most recent call last):
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
    response = self.handle_exception(exc)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/dhruuv/projects/PythonEval/api/views.py", line 44, in post
    if response.get('errors', None):
AttributeError: 'NoneType' object has no attribute 'get'
[10/Feb/2016 09:45:44] "POST /api/python/ HTTP/1.1" 500 87401

更新2

我在ipdb中尝试过,效果很好!

In [5]: try:
    py_compile.compile('testing.py', doraise=True)
except py_compile.PyCompileError:
    print 'dfsssssssssssss'
   ...:     
dfsssssssssssss

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

SyntaxError不是运行时错误,您无法在代码中捕获它。但是,py_compile不会引发SyntaxError;如the documentation所示,它会引发py_compile.PyCompileError

修改因此,您的代码存在一些问题。首先,再次如文档所示,您需要将doraise=True传递给编译才能使其产生错误。

另一个例外正在发生,因为如果成功,你就不会从_check_code_for_errors返回任何内容。你可能应该返回一个空字典。