code_check.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import json
  2. import os
  3. import tempfile
  4. from typing import Optional
  5. from fastapi import APIRouter
  6. from fastapi import Depends
  7. from app import schemas
  8. from app.common.security.auth import verify_users
  9. from utils.sx_time import sxtimeit
  10. from utils.sx_web import web_try
  11. from pylint import epylint
  12. import sqlfluff
  13. router = APIRouter(
  14. prefix="/jpt/code_check",
  15. tags=["code_check-代码校验"],
  16. )
  17. @router.post("/")
  18. @web_try()
  19. @sxtimeit
  20. def code_check(code: str, code_type: str, token_data: schemas.TokenData = Depends(verify_users)):
  21. res = []
  22. if code_type == "python":
  23. file = tempfile.NamedTemporaryFile(delete=False, mode='w')
  24. file.write(code)
  25. file.close()
  26. options = ' '.join([
  27. file.name,
  28. '--output-format', 'json',
  29. ])
  30. (lint_stdout, lint_stderr) = epylint.py_run(return_std=True, command_options=options)
  31. os.remove(file.name)
  32. res = json.loads(lint_stdout.getvalue())
  33. else:
  34. lint_out = sqlfluff.lint(code,'ansi')
  35. res = [l for l in lint_out if l['code'] == 'PRS']
  36. return res