Browse Source

make compatible with Python <3.10 and Pydantic v1

Signed-off-by: merlinz01 <na@notaccessible.xyz>
pull/12135/head
merlinz01 8 months ago
parent
commit
d57cd4f379
  1. 21
      fastapi/dependencies/utils.py
  2. 4
      tests/test_none_passed_when_null_received.py

21
fastapi/dependencies/utils.py

@ -1,4 +1,5 @@
import inspect import inspect
import sys
import types import types
from contextlib import AsyncExitStack, contextmanager from contextlib import AsyncExitStack, contextmanager
from copy import copy, deepcopy from copy import copy, deepcopy
@ -669,12 +670,20 @@ async def solve_dependencies(
dependency_cache=dependency_cache, dependency_cache=dependency_cache,
) )
if PYDANTIC_V2:
def _allows_none(field: ModelField) -> bool: if sys.hexversion >= 0x30a00000:
origin = get_origin(field.type_) def _allows_none(field: ModelField) -> bool:
return (origin is Union or origin is types.UnionType) and type(None) in get_args( origin = get_origin(field.type_)
field.type_ return (origin is Union or origin is types.UnionType) and type(None) in get_args(
) field.type_
)
else:
def _allows_none(field: ModelField) -> bool:
origin = get_origin(field.type_)
return origin is Union and type(None) in get_args(field.type_)
else:
def _allows_none(field: ModelField) -> bool:
return field.allow_none
def _validate_value_with_model_field( def _validate_value_with_model_field(

4
tests/test_none_passed_when_null_received.py

@ -10,7 +10,7 @@ DEFAULT = 1234567890
endpoints = [] endpoints = []
if sys.hexversion >= 0x31000000: if sys.hexversion >= 0x30a0000:
from typing import Annotated from typing import Annotated
@app.post("/api1") @app.post("/api1")
@ -22,7 +22,7 @@ if sys.hexversion >= 0x31000000:
endpoints.append("/api1") endpoints.append("/api1")
if sys.hexversion >= 0x30900000: if sys.hexversion >= 0x3090000:
from typing import Annotated from typing import Annotated
@app.post("/api2") @app.post("/api2")

Loading…
Cancel
Save