feat: add POST /format endpoint
This commit is contained in:
19
main.py
19
main.py
@@ -5,9 +5,16 @@ from fastapi.responses import StreamingResponse
|
|||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
from openai import OpenAI
|
from openai import OpenAI
|
||||||
from schemas import PresetCodeCreate, AIAnalysisRequest, DebugRequest
|
from schemas import (
|
||||||
|
PresetCodeCreate,
|
||||||
|
AIAnalysisRequest,
|
||||||
|
DebugRequest,
|
||||||
|
FormatRequest,
|
||||||
|
FormatResponse,
|
||||||
|
)
|
||||||
from database import DatabaseService
|
from database import DatabaseService
|
||||||
from pg_logger import exec_script_str_local
|
from pg_logger import exec_script_str_local
|
||||||
|
from formatter import format_code, FormatError
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
|
||||||
@@ -139,6 +146,16 @@ async def debug(request: DebugRequest):
|
|||||||
return {"data": data}
|
return {"data": data}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/format", response_model=FormatResponse)
|
||||||
|
async def format_code_endpoint(request: FormatRequest) -> FormatResponse:
|
||||||
|
"""格式化代码"""
|
||||||
|
try:
|
||||||
|
formatted = format_code(request.code, request.language)
|
||||||
|
except FormatError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
return FormatResponse(code=formatted)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|
||||||
|
|||||||
13
schemas.py
13
schemas.py
@@ -32,3 +32,16 @@ class DebugRequest(BaseModel):
|
|||||||
"""调试请求模式,用于调试 Python 代码"""
|
"""调试请求模式,用于调试 Python 代码"""
|
||||||
code: str
|
code: str
|
||||||
inputs: List[str]
|
inputs: List[str]
|
||||||
|
|
||||||
|
|
||||||
|
class FormatRequest(BaseModel):
|
||||||
|
"""格式化代码的请求模式"""
|
||||||
|
|
||||||
|
code: str
|
||||||
|
language: str
|
||||||
|
|
||||||
|
|
||||||
|
class FormatResponse(BaseModel):
|
||||||
|
"""格式化代码的响应模式"""
|
||||||
|
|
||||||
|
code: str
|
||||||
|
|||||||
18
test_main.py
Normal file
18
test_main.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from main import app
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_format_endpoint_formats_python_code():
|
||||||
|
response = client.post("/format", json={"code": "x=1\n", "language": "python"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"code": "x = 1\n"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_format_endpoint_returns_400_on_syntax_error():
|
||||||
|
response = client.post(
|
||||||
|
"/format", json={"code": "def foo(:\n", "language": "python"}
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
Reference in New Issue
Block a user