Browse Source

Remove code examples for Python 3.8 in `dependencies`

pull/14510/head
Yurii Motov 7 months ago
parent
commit
78e5794ef6
  1. 10
      docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
  2. 2
      docs/en/docs/tutorial/dependencies/global-dependencies.md
  3. 25
      docs_src/dependencies/tutorial001_02_an.py
  4. 22
      docs_src/dependencies/tutorial001_an.py
  5. 0
      docs_src/dependencies/tutorial001_py39.py
  6. 26
      docs_src/dependencies/tutorial002_an.py
  7. 0
      docs_src/dependencies/tutorial002_py39.py
  8. 26
      docs_src/dependencies/tutorial003_an.py
  9. 0
      docs_src/dependencies/tutorial003_py39.py
  10. 26
      docs_src/dependencies/tutorial004_an.py
  11. 0
      docs_src/dependencies/tutorial004_py39.py
  12. 26
      docs_src/dependencies/tutorial005_an.py
  13. 0
      docs_src/dependencies/tutorial005_py39.py
  14. 20
      docs_src/dependencies/tutorial006_an.py
  15. 0
      docs_src/dependencies/tutorial006_py39.py
  16. 0
      docs_src/dependencies/tutorial007_py39.py
  17. 26
      docs_src/dependencies/tutorial008_an.py
  18. 0
      docs_src/dependencies/tutorial008_py39.py
  19. 31
      docs_src/dependencies/tutorial008b_an.py
  20. 0
      docs_src/dependencies/tutorial008b_py39.py
  21. 28
      docs_src/dependencies/tutorial008c_an.py
  22. 0
      docs_src/dependencies/tutorial008c_py39.py
  23. 29
      docs_src/dependencies/tutorial008d_an.py
  24. 0
      docs_src/dependencies/tutorial008d_py39.py
  25. 16
      docs_src/dependencies/tutorial008e_an.py
  26. 0
      docs_src/dependencies/tutorial008e_py39.py
  27. 25
      docs_src/dependencies/tutorial009.py
  28. 0
      docs_src/dependencies/tutorial010_py39.py
  29. 22
      docs_src/dependencies/tutorial011_an.py
  30. 0
      docs_src/dependencies/tutorial011_py39.py
  31. 26
      docs_src/dependencies/tutorial012_an.py
  32. 3
      docs_src/dependencies/tutorial012_an_py39.py
  33. 0
      docs_src/dependencies/tutorial012_py39.py
  34. 7
      tests/test_tutorial/test_dependencies/test_tutorial001.py
  35. 7
      tests/test_tutorial/test_dependencies/test_tutorial004.py
  36. 7
      tests/test_tutorial/test_dependencies/test_tutorial006.py
  37. 7
      tests/test_tutorial/test_dependencies/test_tutorial008b.py
  38. 7
      tests/test_tutorial/test_dependencies/test_tutorial008c.py
  39. 7
      tests/test_tutorial/test_dependencies/test_tutorial008d.py
  40. 7
      tests/test_tutorial/test_dependencies/test_tutorial008e.py
  41. 7
      tests/test_tutorial/test_dependencies/test_tutorial012.py

10
docs/en/docs/tutorial/dependencies/dependencies-with-yield.md

@ -29,15 +29,15 @@ For example, you could use this to create a database session and close it after
Only the code prior to and including the `yield` statement is executed before creating a response: Only the code prior to and including the `yield` statement is executed before creating a response:
{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} {* ../../docs_src/dependencies/tutorial007_py39.py hl[2:4] *}
The yielded value is what is injected into *path operations* and other dependencies: The yielded value is what is injected into *path operations* and other dependencies:
{* ../../docs_src/dependencies/tutorial007.py hl[4] *} {* ../../docs_src/dependencies/tutorial007_py39.py hl[4] *}
The code following the `yield` statement is executed after the response: The code following the `yield` statement is executed after the response:
{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} {* ../../docs_src/dependencies/tutorial007_py39.py hl[5:6] *}
/// tip /// tip
@ -57,7 +57,7 @@ So, you can look for that specific exception inside the dependency with `except
In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not. In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not.
{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} {* ../../docs_src/dependencies/tutorial007_py39.py hl[3,5] *}
## Sub-dependencies with `yield` { #sub-dependencies-with-yield } ## Sub-dependencies with `yield` { #sub-dependencies-with-yield }
@ -269,7 +269,7 @@ In Python, you can create Context Managers by <a href="https://docs.python.org/3
You can also use them inside of **FastAPI** dependencies with `yield` by using You can also use them inside of **FastAPI** dependencies with `yield` by using
`with` or `async with` statements inside of the dependency function: `with` or `async with` statements inside of the dependency function:
{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} {* ../../docs_src/dependencies/tutorial010_py39.py hl[1:9,13] *}
/// tip /// tip

2
docs/en/docs/tutorial/dependencies/global-dependencies.md

@ -6,7 +6,7 @@ Similar to the way you can [add `dependencies` to the *path operation decorators
In that case, they will be applied to all the *path operations* in the application: In that case, they will be applied to all the *path operations* in the application:
{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} {* ../../docs_src/dependencies/tutorial012_an_py39.py hl[17] *}
And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app. And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app.

25
docs_src/dependencies/tutorial001_02_an.py

@ -1,25 +0,0 @@
from typing import Union
from fastapi import Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
CommonsDep = Annotated[dict, Depends(common_parameters)]
@app.get("/items/")
async def read_items(commons: CommonsDep):
return commons
@app.get("/users/")
async def read_users(commons: CommonsDep):
return commons

22
docs_src/dependencies/tutorial001_an.py

@ -1,22 +0,0 @@
from typing import Union
from fastapi import Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return commons
@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return commons

0
docs_src/dependencies/tutorial001.py → docs_src/dependencies/tutorial001_py39.py

26
docs_src/dependencies/tutorial002_an.py

@ -1,26 +0,0 @@
from typing import Union
from fastapi import Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
class CommonQueryParams:
def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip : commons.skip + commons.limit]
response.update({"items": items})
return response

0
docs_src/dependencies/tutorial002.py → docs_src/dependencies/tutorial002_py39.py

26
docs_src/dependencies/tutorial003_an.py

@ -1,26 +0,0 @@
from typing import Any, Union
from fastapi import Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
class CommonQueryParams:
def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: Annotated[Any, Depends(CommonQueryParams)]):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip : commons.skip + commons.limit]
response.update({"items": items})
return response

0
docs_src/dependencies/tutorial003.py → docs_src/dependencies/tutorial003_py39.py

26
docs_src/dependencies/tutorial004_an.py

@ -1,26 +0,0 @@
from typing import Union
from fastapi import Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
class CommonQueryParams:
def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: Annotated[CommonQueryParams, Depends()]):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip : commons.skip + commons.limit]
response.update({"items": items})
return response

0
docs_src/dependencies/tutorial004.py → docs_src/dependencies/tutorial004_py39.py

26
docs_src/dependencies/tutorial005_an.py

@ -1,26 +0,0 @@
from typing import Union
from fastapi import Cookie, Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
def query_extractor(q: Union[str, None] = None):
return q
def query_or_cookie_extractor(
q: Annotated[str, Depends(query_extractor)],
last_query: Annotated[Union[str, None], Cookie()] = None,
):
if not q:
return last_query
return q
@app.get("/items/")
async def read_query(
query_or_default: Annotated[str, Depends(query_or_cookie_extractor)],
):
return {"q_or_cookie": query_or_default}

0
docs_src/dependencies/tutorial005.py → docs_src/dependencies/tutorial005_py39.py

20
docs_src/dependencies/tutorial006_an.py

@ -1,20 +0,0 @@
from fastapi import Depends, FastAPI, Header, HTTPException
from typing_extensions import Annotated
app = FastAPI()
async def verify_token(x_token: Annotated[str, Header()]):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
async def verify_key(x_key: Annotated[str, Header()]):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")
return x_key
@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
return [{"item": "Foo"}, {"item": "Bar"}]

0
docs_src/dependencies/tutorial006.py → docs_src/dependencies/tutorial006_py39.py

0
docs_src/dependencies/tutorial007.py → docs_src/dependencies/tutorial007_py39.py

26
docs_src/dependencies/tutorial008_an.py

@ -1,26 +0,0 @@
from fastapi import Depends
from typing_extensions import Annotated
async def dependency_a():
dep_a = generate_dep_a()
try:
yield dep_a
finally:
dep_a.close()
async def dependency_b(dep_a: Annotated[DepA, Depends(dependency_a)]):
dep_b = generate_dep_b()
try:
yield dep_b
finally:
dep_b.close(dep_a)
async def dependency_c(dep_b: Annotated[DepB, Depends(dependency_b)]):
dep_c = generate_dep_c()
try:
yield dep_c
finally:
dep_c.close(dep_b)

0
docs_src/dependencies/tutorial008.py → docs_src/dependencies/tutorial008_py39.py

31
docs_src/dependencies/tutorial008b_an.py

@ -1,31 +0,0 @@
from fastapi import Depends, FastAPI, HTTPException
from typing_extensions import Annotated
app = FastAPI()
data = {
"plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
"portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
}
class OwnerError(Exception):
pass
def get_username():
try:
yield "Rick"
except OwnerError as e:
raise HTTPException(status_code=400, detail=f"Owner error: {e}")
@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
if item_id not in data:
raise HTTPException(status_code=404, detail="Item not found")
item = data[item_id]
if item["owner"] != username:
raise OwnerError(username)
return item

0
docs_src/dependencies/tutorial008b.py → docs_src/dependencies/tutorial008b_py39.py

28
docs_src/dependencies/tutorial008c_an.py

@ -1,28 +0,0 @@
from fastapi import Depends, FastAPI, HTTPException
from typing_extensions import Annotated
app = FastAPI()
class InternalError(Exception):
pass
def get_username():
try:
yield "Rick"
except InternalError:
print("Oops, we didn't raise again, Britney 😱")
@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
if item_id == "portal-gun":
raise InternalError(
f"The portal gun is too dangerous to be owned by {username}"
)
if item_id != "plumbus":
raise HTTPException(
status_code=404, detail="Item not found, there's only a plumbus here"
)
return item_id

0
docs_src/dependencies/tutorial008c.py → docs_src/dependencies/tutorial008c_py39.py

29
docs_src/dependencies/tutorial008d_an.py

@ -1,29 +0,0 @@
from fastapi import Depends, FastAPI, HTTPException
from typing_extensions import Annotated
app = FastAPI()
class InternalError(Exception):
pass
def get_username():
try:
yield "Rick"
except InternalError:
print("We don't swallow the internal error here, we raise again 😎")
raise
@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
if item_id == "portal-gun":
raise InternalError(
f"The portal gun is too dangerous to be owned by {username}"
)
if item_id != "plumbus":
raise HTTPException(
status_code=404, detail="Item not found, there's only a plumbus here"
)
return item_id

0
docs_src/dependencies/tutorial008d.py → docs_src/dependencies/tutorial008d_py39.py

16
docs_src/dependencies/tutorial008e_an.py

@ -1,16 +0,0 @@
from fastapi import Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
def get_username():
try:
yield "Rick"
finally:
print("Cleanup up before response is sent")
@app.get("/users/me")
def get_user_me(username: Annotated[str, Depends(get_username, scope="function")]):
return username

0
docs_src/dependencies/tutorial008e.py → docs_src/dependencies/tutorial008e_py39.py

25
docs_src/dependencies/tutorial009.py

@ -1,25 +0,0 @@
from fastapi import Depends
async def dependency_a():
dep_a = generate_dep_a()
try:
yield dep_a
finally:
dep_a.close()
async def dependency_b(dep_a=Depends(dependency_a)):
dep_b = generate_dep_b()
try:
yield dep_b
finally:
dep_b.close(dep_a)
async def dependency_c(dep_b=Depends(dependency_b)):
dep_c = generate_dep_c()
try:
yield dep_c
finally:
dep_c.close(dep_b)

0
docs_src/dependencies/tutorial010.py → docs_src/dependencies/tutorial010_py39.py

22
docs_src/dependencies/tutorial011_an.py

@ -1,22 +0,0 @@
from fastapi import Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
class FixedContentQueryChecker:
def __init__(self, fixed_content: str):
self.fixed_content = fixed_content
def __call__(self, q: str = ""):
if q:
return self.fixed_content in q
return False
checker = FixedContentQueryChecker("bar")
@app.get("/query-checker/")
async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
return {"fixed_content_in_query": fixed_content_included}

0
docs_src/dependencies/tutorial011.py → docs_src/dependencies/tutorial011_py39.py

26
docs_src/dependencies/tutorial012_an.py

@ -1,26 +0,0 @@
from fastapi import Depends, FastAPI, Header, HTTPException
from typing_extensions import Annotated
async def verify_token(x_token: Annotated[str, Header()]):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
async def verify_key(x_key: Annotated[str, Header()]):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")
return x_key
app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
@app.get("/items/")
async def read_items():
return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
@app.get("/users/")
async def read_users():
return [{"username": "Rick"}, {"username": "Morty"}]

3
docs_src/dependencies/tutorial012_an_py39.py

@ -1,5 +1,6 @@
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException from fastapi import Depends, FastAPI, Header, HTTPException
from typing_extensions import Annotated
async def verify_token(x_token: Annotated[str, Header()]): async def verify_token(x_token: Annotated[str, Header()]):

0
docs_src/dependencies/tutorial012.py → docs_src/dependencies/tutorial012_py39.py

7
tests/test_tutorial/test_dependencies/test_tutorial001.py

@ -4,16 +4,15 @@ import pytest
from dirty_equals import IsDict from dirty_equals import IsDict
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310 from ...utils import needs_py310
@pytest.fixture( @pytest.fixture(
name="client", name="client",
params=[ params=[
"tutorial001", pytest.param("tutorial001_py39"),
pytest.param("tutorial001_py310", marks=needs_py310), pytest.param("tutorial001_py310", marks=needs_py310),
"tutorial001_an", pytest.param("tutorial001_an_py39"),
pytest.param("tutorial001_an_py39", marks=needs_py39),
pytest.param("tutorial001_an_py310", marks=needs_py310), pytest.param("tutorial001_an_py310", marks=needs_py310),
], ],
) )

7
tests/test_tutorial/test_dependencies/test_tutorial004.py

@ -4,16 +4,15 @@ import pytest
from dirty_equals import IsDict from dirty_equals import IsDict
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39, needs_py310 from ...utils import needs_py310
@pytest.fixture( @pytest.fixture(
name="client", name="client",
params=[ params=[
"tutorial004", pytest.param("tutorial004_py39"),
pytest.param("tutorial004_py310", marks=needs_py310), pytest.param("tutorial004_py310", marks=needs_py310),
"tutorial004_an", pytest.param("tutorial004_an_py39"),
pytest.param("tutorial004_an_py39", marks=needs_py39),
pytest.param("tutorial004_an_py310", marks=needs_py310), pytest.param("tutorial004_an_py310", marks=needs_py310),
], ],
) )

7
tests/test_tutorial/test_dependencies/test_tutorial006.py

@ -4,15 +4,12 @@ import pytest
from dirty_equals import IsDict from dirty_equals import IsDict
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture( @pytest.fixture(
name="client", name="client",
params=[ params=[
"tutorial006", pytest.param("tutorial006_py39"),
"tutorial006_an", pytest.param("tutorial006_an_py39"),
pytest.param("tutorial006_an_py39", marks=needs_py39),
], ],
) )
def get_client(request: pytest.FixtureRequest): def get_client(request: pytest.FixtureRequest):

7
tests/test_tutorial/test_dependencies/test_tutorial008b.py

@ -3,15 +3,12 @@ import importlib
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture( @pytest.fixture(
name="client", name="client",
params=[ params=[
"tutorial008b", pytest.param("tutorial008b_py39"),
"tutorial008b_an", pytest.param("tutorial008b_an_py39"),
pytest.param("tutorial008b_an_py39", marks=needs_py39),
], ],
) )
def get_client(request: pytest.FixtureRequest): def get_client(request: pytest.FixtureRequest):

7
tests/test_tutorial/test_dependencies/test_tutorial008c.py

@ -5,15 +5,12 @@ import pytest
from fastapi.exceptions import FastAPIError from fastapi.exceptions import FastAPIError
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture( @pytest.fixture(
name="mod", name="mod",
params=[ params=[
"tutorial008c", pytest.param("tutorial008c_py39"),
"tutorial008c_an", pytest.param("tutorial008c_an_py39"),
pytest.param("tutorial008c_an_py39", marks=needs_py39),
], ],
) )
def get_mod(request: pytest.FixtureRequest): def get_mod(request: pytest.FixtureRequest):

7
tests/test_tutorial/test_dependencies/test_tutorial008d.py

@ -4,15 +4,12 @@ from types import ModuleType
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture( @pytest.fixture(
name="mod", name="mod",
params=[ params=[
"tutorial008d", pytest.param("tutorial008d_py39"),
"tutorial008d_an", pytest.param("tutorial008d_an_py39"),
pytest.param("tutorial008d_an_py39", marks=needs_py39),
], ],
) )
def get_mod(request: pytest.FixtureRequest): def get_mod(request: pytest.FixtureRequest):

7
tests/test_tutorial/test_dependencies/test_tutorial008e.py

@ -3,15 +3,12 @@ import importlib
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture( @pytest.fixture(
name="client", name="client",
params=[ params=[
"tutorial008e", pytest.param("tutorial008e_py39"),
"tutorial008e_an", pytest.param("tutorial008e_an_py39"),
pytest.param("tutorial008e_an_py39", marks=needs_py39),
], ],
) )
def get_client(request: pytest.FixtureRequest): def get_client(request: pytest.FixtureRequest):

7
tests/test_tutorial/test_dependencies/test_tutorial012.py

@ -4,15 +4,12 @@ import pytest
from dirty_equals import IsDict from dirty_equals import IsDict
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from ...utils import needs_py39
@pytest.fixture( @pytest.fixture(
name="client", name="client",
params=[ params=[
"tutorial012", pytest.param("tutorial012_py39"),
"tutorial012_an", pytest.param("tutorial012_an_py39"),
pytest.param("tutorial012_an_py39", marks=needs_py39),
], ],
) )
def get_client(request: pytest.FixtureRequest): def get_client(request: pytest.FixtureRequest):

Loading…
Cancel
Save