Skip to content

Commit

Permalink
use exec() instead of importlib
Browse files Browse the repository at this point in the history
  • Loading branch information
w3ichen committed Jun 2, 2023
1 parent 900325c commit 508f09c
Show file tree
Hide file tree
Showing 4 changed files with 2,787 additions and 2,768 deletions.
38 changes: 15 additions & 23 deletions back-end/server.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import importlib
import io
import json
import os
import tempfile
import traceback
from contextlib import redirect_stdout

Expand Down Expand Up @@ -57,27 +55,21 @@ def run_code(code):
response = {}
# (1) Get user inputs as json
inputs = request.get_json(force=True)
with tempfile.NamedTemporaryFile(mode="w", suffix=".py") as code_file:
# (2) Write code to a temp file
code_file.write(code)
code_file.flush()
# (3) Capture stdout
stdout = io.StringIO()
with redirect_stdout(stdout):
# (4) Compile and run the app code
try:
# https://stackoverflow.com/a/67692
# Compile the functions
spec = importlib.util.spec_from_file_location(
"app_code", code_file.name
)
script = importlib.util.module_from_spec(spec)
spec.loader.exec_module(script)
# Execute the main() function
response["outputs"] = clean_json(script.main(inputs))
except Exception as e:
response["error"] = traceback.format_exc()
response["stdout"] = stdout.getvalue()
# (3) Capture stdout
stdout = io.StringIO()
with redirect_stdout(stdout):
# (4) Compile and run the app code
try:
g = {}
exec(code, g)

assert "main" in g, "'def main(inputs):' is not defined"
outputs = g["main"](inputs)

response["outputs"] = clean_json(outputs)
except Exception as e:
response["error"] = traceback.format_exc()
response["stdout"] = stdout.getvalue()
return response


Expand Down
177 changes: 97 additions & 80 deletions front-end/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions front-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@
"@mui/icons-material": "^5.6.0",
"@mui/lab": "^5.0.0-alpha.77",
"@mui/material": "^5.6.0",
"@types/katex": "^0.14.0",
"@types/lodash": "^4.14.181",
"@types/nunjucks": "^3.2.1",
"@types/react-grid-layout": "^1.3.2",
"axios": "^0.26.1",
"date-fns": "^2.28.0",
"formik": "^2.2.9",
Expand All @@ -32,13 +28,17 @@
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-dropzone": "^12.0.5",
"react-grid-layout": "^1.3.4",
"react-grid-layout": "^1.2.3",
"react-quill": "^2.0.0-beta.4"
},
"devDependencies": {
"@types/katex": "^0.16.0",
"@types/lodash": "^4.14.195",
"@types/node": "17.0.23",
"@types/nunjucks": "^3.2.2",
"@types/react": "18.0.1",
"@types/react-dom": "18.0.0",
"@types/react-grid-layout": "^1.3.2",
"eslint": "8.13.0",
"eslint-config-next": "12.1.4",
"typescript": "4.6.3"
Expand Down

0 comments on commit 508f09c

Please sign in to comment.