Skip to content
This repository was archived by the owner on Jun 7, 2023. It is now read-only.

Commit 89d760e

Browse files
Add python_check endpoint to routers/books
1 parent 5f4c400 commit 89d760e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

bookserver/routers/books.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
import random
1818
import socket
1919
from typing import Optional
20+
import ast
21+
import io
2022

2123
# Third-party imports
2224
# -------------------
@@ -25,6 +27,7 @@
2527
from fastapi.templating import Jinja2Templates
2628
from jinja2.exceptions import TemplateNotFound
2729
from pydantic import constr
30+
from pyflakes import (reporter, checker)
2831

2932
# Local application imports
3033
# -------------------------
@@ -55,6 +58,35 @@
5558
tags=["books"],
5659
)
5760

61+
62+
@router.post("/python_check")
63+
async def python_check(request: Request):
64+
"""
65+
Takes a chunk of Python code and runs a syntax checker (currently
66+
Pyflakes) on it to provide more detailed advice than is available
67+
via Skulpt.
68+
69+
Caller must provide:
70+
* ``code`` -- the Python code to check
71+
"""
72+
code_bytes = await request.body()
73+
code = code_bytes.decode("utf-8")
74+
75+
filename = "program.py"
76+
77+
resultMessage = ""
78+
try:
79+
tree = ast.parse(code, filename=filename)
80+
w = checker.Checker(tree, filename=filename)
81+
except SyntaxError as e:
82+
textOut = io.StringIO()
83+
reporter = reporter.Reporter(textOut, textOut)
84+
reporter.syntaxError(filename, e.args[0], e.lineno, e.offset, e.text)
85+
textOut.seek(0)
86+
resultMessage = textOut.read()
87+
88+
return resultMessage
89+
5890

5991
# Options for static asset renderers:
6092
#

0 commit comments

Comments
 (0)