1
- from collections . abc import Callable
2
- from typing import Any , Type , Union
1
+ from contextlib import contextmanager
2
+ from typing import Generator
3
3
4
4
from fastapi .exceptions import RequestValidationError
5
5
from pydantic import ValidationError
6
6
7
7
8
- class ensure_request_validation_errors ():
8
+ @contextmanager
9
+ def ensure_request_validation_errors () -> Generator [None , None , None ]:
9
10
"""
10
11
Converter for `ValidationError` to `RequestValidationError`.
11
12
@@ -17,43 +18,14 @@ class ensure_request_validation_errors():
17
18
18
19
Usage examples:
19
20
20
- ```python
21
- # Use as a decorator
22
- @ensure_request_validation_errors
23
- def some_func():
24
- some_code_doing_extra_validation() # for example async validation
25
- ```
26
-
27
21
```python
28
22
# Use as a context manager
29
23
with ensure_request_validation_errors():
30
24
some_code_doing_extra_validation() # for example async validation
31
25
```
32
26
"""
33
27
34
- func : Union [Callable , None ]
35
-
36
- def __init__ (self , func : Union [Callable , None ] = None ) -> None :
37
- self .func = func
38
-
39
- def __call__ (self , * args : Any , ** kwargs : Any ) -> Any :
40
- if self .func is None :
41
- raise RuntimeError ("No func given" )
42
-
43
- with self :
44
- return self .func (* args , ** kwargs )
45
-
46
- def __enter__ (self ) -> None :
47
- pass
48
-
49
- def __exit__ (
50
- self ,
51
- exc_type : Union [Type [Exception ], None ],
52
- exc_value : Union [Exception , None ],
53
- traceback : Any ,
54
- ) -> None :
55
- if exc_value is None :
56
- return
57
-
58
- if isinstance (exc_value , ValidationError ):
59
- raise RequestValidationError (errors = exc_value .errors ())
28
+ try :
29
+ yield
30
+ except ValidationError as O_o :
31
+ raise RequestValidationError (errors = O_o .errors ())
0 commit comments