Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix(api): serialize rejected inputs in validation responses

Rudy Celekli3e818bc35ca0
diff --git a/app/asgi.py b/app/asgi.py
index a3f222dd..c46d552a 100644
--- a/app/asgi.py
+++ b/app/asgi.py
@@ -1,11 +1,13 @@
"""Application implementation - ASGI."""
+import math
import os
from contextlib import asynccontextmanager
from urllib.parse import urlsplit
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
+from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
@@ -63,10 +65,19 @@ def exception_handler(request: Request, e: HttpException):
def validation_exception_handler(request: Request, e: RequestValidationError):
+ # Rejected inputs can contain NaN/Infinity, and custom validators attach
+ # exception objects to ctx. Neither can be emitted by JSONResponse directly.
+ errors = jsonable_encoder(
+ e.errors(),
+ custom_encoder={
+ float: lambda value: value if math.isfinite(value) else str(value),
+ Exception: str,
+ },
+ )
return JSONResponse(
status_code=400,
content=utils.get_response(
- status=400, data=e.errors(), message="field required"
+ status=400, data=errors, message="field required"
),
)
diff --git a/test/services/test_api_validation_json.py b/test/services/test_api_validation_json.py
new file mode 100644
index 00000000..f60277e3
--- /dev/null
+++ b/test/services/test_api_validation_json.py
@@ -0,0 +1,66 @@
+import json
+from unittest.mock import patch
+
+import pytest
+from fastapi import FastAPI
+from fastapi.exceptions import RequestValidationError
+from fastapi.testclient import TestClient
+from pydantic import BaseModel, field_validator
+
+from app import asgi
+from app.config import config
+
+
[email protected]('number', ['NaN', 'Infinity', '-Infinity'])
[email protected]('path,field', [('/api/v1/videos', 'n_threads'), ('/api/v1/terms', 'amount')])
+def test_rejected_nonfinite_json_numbers_return_validation_response(number, path, field):
+ with (
+ patch.dict(config.app, {'api_key': ''}),
+ patch('app.controllers.v1.video.task_manager.add_task') as schedule,
+ patch('app.controllers.v1.llm.llm.generate_terms') as generate,
+ TestClient(asgi.get_application(), raise_server_exceptions=False) as client,
+ ):
+ response = client.post(
+ path,
+ content='{"video_subject":"test","' + field + '":' + number + '}',
+ headers={'content-type': 'application/json'},
+ )
+ assert response.status_code == 400
+ body = response.json()
+ assert body['status'] == 400
+ assert body['data'][0]['loc'] == ['body', field]
+ json.dumps(body, allow_nan=False)
+ schedule.assert_not_called()
+ generate.assert_not_called()
+
+
+def test_validator_exception_context_is_serializable():
+ class Parameters(BaseModel):
+ value: str
+
+ @field_validator('value')
+ @classmethod
+ def reject_value(cls, value):
+ raise ValueError('invalid custom value')
+
+ instance = FastAPI()
+ instance.add_exception_handler(RequestValidationError, asgi.validation_exception_handler)
+
+ @instance.post('/validate')
+ def validate(params: Parameters):
+ return params.model_dump()
+
+ response = TestClient(instance, raise_server_exceptions=False).post('/validate', json={'value': 'x'})
+ assert response.status_code == 400
+ assert response.json()['data'][0]['ctx']['error'] == 'invalid custom value'
+
+
+def test_normal_error_details_remain_available():
+ instance = asgi.get_application()
+ with patch.dict(config.app, {'api_key': ''}):
+ response = TestClient(instance).post('/api/v1/terms', json={'amount': 0})
+ assert response.status_code == 400
+ error = response.json()['data'][0]
+ assert error['type'] == 'greater_than_equal'
+ assert error['input'] == 0
+ assert error['ctx'] == {'ge': 1}