From 838e9c964eaef85f47ec8b22b4d1feb124a3a039 Mon Sep 17 00:00:00 2001 From: malicious <38064672+malicious@users.noreply.github.com> Date: Thu, 11 Jan 2024 16:31:18 +0000 Subject: [PATCH 001/104] =?UTF-8?q?=F0=9F=93=9D=20Reword=20in=20docs,=20fr?= =?UTF-8?q?om=20"have=20in=20mind"=20to=20"keep=20in=20mind"=20(#10376)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/advanced/additional-responses.md | 2 +- docs/en/docs/advanced/behind-a-proxy.md | 4 ++-- docs/en/docs/advanced/custom-response.md | 2 +- docs/en/docs/advanced/dataclasses.md | 2 +- docs/en/docs/advanced/events.md | 2 +- docs/en/docs/advanced/response-change-status-code.md | 2 +- docs/en/docs/advanced/response-cookies.md | 2 +- docs/en/docs/advanced/response-headers.md | 2 +- docs/en/docs/advanced/websockets.md | 2 +- docs/en/docs/benchmarks.md | 2 +- docs/en/docs/deployment/concepts.md | 4 ++-- docs/en/docs/deployment/https.md | 2 +- docs/en/docs/deployment/index.md | 4 ++-- docs/en/docs/deployment/manually.md | 4 ++-- docs/en/docs/help-fastapi.md | 6 +++--- docs/en/docs/how-to/sql-databases-peewee.md | 4 ++-- docs/en/docs/release-notes.md | 2 +- docs/en/docs/tutorial/body-nested-models.md | 2 +- docs/en/docs/tutorial/middleware.md | 2 +- docs/en/docs/tutorial/path-params-numeric-validations.md | 4 ++-- docs/en/docs/tutorial/query-params-str-validations.md | 8 ++++---- docs/en/docs/tutorial/request-files.md | 2 +- docs/en/docs/tutorial/security/get-current-user.md | 2 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 2 +- docs/en/docs/tutorial/sql-databases.md | 2 +- 25 files changed, 36 insertions(+), 36 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 624036ce9..41b39c18e 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -28,7 +28,7 @@ For example, to declare another response with a status code `404` and a Pydantic ``` !!! note - Have in mind that you have to return the `JSONResponse` directly. + Keep in mind that you have to return the `JSONResponse` directly. !!! info The `model` key is not part of OpenAPI. diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index e7af77f3d..01998cc91 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -125,7 +125,7 @@ Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--r ### About `root_path` -Have in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. +Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. But if you go with your browser to http://127.0.0.1:8000/app you will see the normal response: @@ -142,7 +142,7 @@ Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, ## About proxies with a stripped path prefix -Have in mind that a proxy with stripped path prefix is only one of the ways to configure it. +Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it. Probably in many cases the default will be that the proxy doesn't have a stripped path prefix. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index ce2619e8d..827776f5e 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -101,7 +101,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi Here are some of the available responses. -Have in mind that you can use `Response` to return anything else, or even create a custom sub-class. +Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. !!! note "Technical Details" You could also use `from starlette.responses import HTMLResponse`. diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 72daca06a..ed1d5610f 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -21,7 +21,7 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. !!! info - Have in mind that dataclasses can't do everything Pydantic models can do. + Keep in mind that dataclasses can't do everything Pydantic models can do. So, you might still need to use Pydantic models. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 6b7de4130..6df1411d1 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -159,4 +159,4 @@ Underneath, in the ASGI technical specification, this is part of the using the 'X-' prefix. +Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 49b8fba89..b8dfab1d1 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -212,7 +212,7 @@ Client #1596980209979 left the chat !!! tip The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. - But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. + But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md index e05fec840..d746b6d7c 100644 --- a/docs/en/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -2,7 +2,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) -But when checking benchmarks and comparisons you should have the following in mind. +But when checking benchmarks and comparisons you should keep the following in mind. ## Benchmarks and speed diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index 77419f8b0..cc01fb24e 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -258,7 +258,7 @@ And you will have to make sure that it's a single process running those previous Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. !!! tip - Also, have in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. In that case, you wouldn't have to worry about any of this. 🀷 @@ -297,7 +297,7 @@ You can use simple tools like `htop` to see the CPU and RAM used in your server ## Recap -You have been reading here some of the main concepts that you would probably need to have in mind when deciding how to deploy your application: +You have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application: * Security - HTTPS * Running on startup diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 790976a71..5cf76c111 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -9,7 +9,7 @@ But it is way more complex than that. To **learn the basics of HTTPS**, from a consumer perspective, check https://howhttps.works/. -Now, from a **developer's perspective**, here are several things to have in mind while thinking about HTTPS: +Now, from a **developer's perspective**, here are several things to keep in mind while thinking about HTTPS: * For HTTPS, **the server** needs to **have "certificates"** generated by a **third party**. * Those certificates are actually **acquired** from the third party, not "generated". diff --git a/docs/en/docs/deployment/index.md b/docs/en/docs/deployment/index.md index 6c43d8abb..b43bd050a 100644 --- a/docs/en/docs/deployment/index.md +++ b/docs/en/docs/deployment/index.md @@ -16,6 +16,6 @@ There are several ways to do it depending on your specific use case and the tool You could **deploy a server** yourself using a combination of tools, you could use a **cloud service** that does part of the work for you, or other possible options. -I will show you some of the main concepts you should probably have in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). +I will show you some of the main concepts you should probably keep in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). -You will see more details to have in mind and some of the techniques to do it in the next sections. ✹ +You will see more details to keep in mind and some of the techniques to do it in the next sections. ✹ diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index d6892b2c1..b10a3686d 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -10,11 +10,11 @@ There are 3 main alternatives: ## Server Machine and Server Program -There's a small detail about names to have in mind. 💡 +There's a small detail about names to keep in mind. 💡 The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). -Just have that in mind when you read "server" in general, it could refer to one of those two things. +Just keep in mind that when you read "server" in general, it could refer to one of those two things. When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 8199c9b9a..71c580409 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -106,7 +106,7 @@ In many cases they will only copy a fragment of the code, but that's not enough * You can ask them to provide a minimal, reproducible, example, that you can **copy-paste** and run locally to see the same error or behavior they are seeing, or to understand their use case better. -* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just have in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. +* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just keep in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. ### Suggest solutions @@ -148,7 +148,7 @@ Again, please try your best to be kind. 🀗 --- -Here's what to have in mind and how to review a pull request: +Here's what to keep in mind and how to review a pull request: ### Understand the problem @@ -233,7 +233,7 @@ Join the 👥 `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. -There are several things to have in mind. +There are several things to keep in mind. The `ContextVar` has to be created at the top of the module, like: diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 692890d73..6431ed2c3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -3379,7 +3379,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * Add OAuth2 redirect page for Swagger UI. This allows having delegated authentication in the Swagger UI docs. For this to work, you need to add `{your_origin}/docs/oauth2-redirect` to the allowed callbacks in your OAuth2 provider (in Auth0, Facebook, Google, etc). * For example, during development, it could be `http://localhost:8000/docs/oauth2-redirect`. - * Have in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. + * Keep in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. * This is only to allow delegated authentication in the API docs with Swagger UI. * PR [#198](https://github.com/tiangolo/fastapi/pull/198) by [@steinitzu](https://github.com/steinitzu). diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 387f0de9a..7058d4ad0 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -361,7 +361,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo ``` !!! tip - Have in mind that JSON only supports `str` as keys. + Keep in mind that JSON only supports `str` as keys. But Pydantic has automatic data conversion. diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 3c6868fe4..492a1b065 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -33,7 +33,7 @@ The middleware function receives: ``` !!! tip - Have in mind that custom proprietary headers can be added using the 'X-' prefix. + Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index 57ad20b13..b5b13cfbe 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -126,7 +126,7 @@ So, you can declare your function as: {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` -But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. +But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. === "Python 3.9+" @@ -166,7 +166,7 @@ Python won't do anything with that `*`, but it will know that all the following ### Better with `Annotated` -Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. +Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. === "Python 3.9+" diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 91ae615ff..7a9bc4875 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -173,7 +173,7 @@ q: str | None = None But it declares it explicitly as being a query parameter. !!! info - Have in mind that the most important part to make a parameter optional is the part: + Keep in mind that the most important part to make a parameter optional is the part: ```Python = None @@ -199,7 +199,7 @@ This will validate the data, show a clear error when the data is not valid, and ### `Query` as the default value or in `Annotated` -Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. +Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent. @@ -659,7 +659,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho ``` !!! note - Have in mind that in this case, FastAPI won't check the contents of the list. + Keep in mind that in this case, FastAPI won't check the contents of the list. For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. @@ -670,7 +670,7 @@ You can add more information about the parameter. That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools. !!! note - Have in mind that different tools might have different levels of OpenAPI support. + Keep in mind that different tools might have different levels of OpenAPI support. Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index c85a68ed6..8eb8ace64 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -71,7 +71,7 @@ The files will be uploaded as "form data". If you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`. -Have in mind that this means that the whole contents will be stored in memory. This will work well for small files. +Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files. But there are several cases in which you might benefit from using `UploadFile`. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index e99a800c6..dc6d87c9c 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -227,7 +227,7 @@ Just use any kind of model, any kind of class, any kind of database that you nee ## Code size -This example might seem verbose. Have in mind that we are mixing security, data models, utility functions and *path operations* in the same file. +This example might seem verbose. Keep in mind that we are mixing security, data models, utility functions and *path operations* in the same file. But here's the key point. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 0a347fed3..4159b3659 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -318,7 +318,7 @@ In those cases, several of those entities could have the same ID, let's say `foo So, to avoid ID collisions, when creating the JWT token for the user, you could prefix the value of the `sub` key, e.g. with `username:`. So, in this example, the value of `sub` could have been: `username:johndoe`. -The important thing to have in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. +The important thing to keep in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. ## Check it diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 1bc87a702..161d5491d 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -301,7 +301,7 @@ while Pydantic *models* declare the types using `:`, the new type annotation syn name: str ``` -Have it in mind, so you don't get confused when using `=` and `:` with them. +Keep these in mind, so you don't get confused when using `=` and `:` with them. ### Create Pydantic *models* / schemas for reading / returning From 6761fc1fa4ffce2cc0c73117aeadce81fa3a659c Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 16:31:38 +0000 Subject: [PATCH 002/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6431ed2c3..9cdb82e19 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). * 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). From abe7db6b2489052e73b2386d6c5372922f9a7cee Mon Sep 17 00:00:00 2001 From: Mikhail Rozhkov Date: Thu, 11 Jan 2024 18:29:24 +0100 Subject: [PATCH 003/104] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20ML=20serving=20and=20monitoring=20with=20FastAPI=20and=20Evi?= =?UTF-8?q?dently=20(#9701)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index ed512b733..aea400dfc 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Mikhail Rozhkov, Elena Samuylova + author_link: https://www.linkedin.com/in/mnrozhkov/ + link: https://www.evidentlyai.com/blog/fastapi-tutorial + title: ML serving and monitoring with FastAPI and Evidently - author: Visual Studio Code Team author_link: https://code.visualstudio.com/ link: https://code.visualstudio.com/docs/python/tutorial-fastapi From 3325635eed6ab45e81de31766863e63ab3a7662a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 17:29:48 +0000 Subject: [PATCH 004/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9cdb82e19..ccb2d1593 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). * 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). * 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). From 0380ca3e69efe642149bda481d05906f99f4da69 Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Thu, 11 Jan 2024 18:42:43 +0100 Subject: [PATCH 005/104] =?UTF-8?q?=F0=9F=93=9D=20Review=20and=20rewording?= =?UTF-8?q?=20of=20`en/docs/contributing.md`=20(#10480)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/contributing.md | 71 ++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 35bc1c501..2d308a9db 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -4,11 +4,11 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- ## Developing -If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment. +If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. ### Virtual environment with `venv` -You can create a virtual environment in a directory using Python's `venv` module: +You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
@@ -18,7 +18,7 @@ $ python -m venv env
-That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment. +That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. ### Activate the environment @@ -84,7 +84,7 @@ To check it worked, use: If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 -Make sure you have the latest pip version on your virtual environment to avoid errors on the next steps: +Make sure you have the latest pip version on your local environment to avoid errors on the next steps:
@@ -101,7 +101,7 @@ $ python -m pip install --upgrade pip This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. -### pip +### Install requirements using pip After activating the environment as described above: @@ -117,20 +117,20 @@ $ pip install -r requirements.txt It will install all the dependencies and your local FastAPI in your local environment. -#### Using your local FastAPI +### Using your local FastAPI -If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code. +If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your cloned local FastAPI source code. And if you update that local FastAPI source code when you run that Python file again, it will use the fresh version of FastAPI you just edited. That way, you don't have to "install" your local version to be able to test every change. !!! note "Technical Details" - This only happens when you install using this included `requirements.txt` instead of installing `pip install fastapi` directly. + This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside of the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. -### Format +### Format the code There is a script that you can run that will format and clean all your code: @@ -227,15 +227,13 @@ And those Python files are included/injected in the documentation when generatin Most of the tests actually run against the example source files in the documentation. -This helps making sure that: +This helps to make sure that: -* The documentation is up to date. +* The documentation is up-to-date. * The documentation examples can be run as is. * Most of the features are covered by the documentation, ensured by test coverage. - - -### Apps and docs at the same time +#### Apps and docs at the same time If you run the examples with, e.g.: @@ -259,7 +257,9 @@ Here are the steps to help with translations. #### Tips and guidelines -* Check the currently existing pull requests for your language and add reviews requesting changes or approving them. +* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. + +* Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. !!! tip You can add comments with change suggestions to existing pull requests. @@ -268,19 +268,9 @@ Here are the steps to help with translations. * Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. -* Add a single pull request per page translated. That will make it much easier for others to review it. - -For the languages I don't speak, I'll wait for several others to review the translation before merging. +* If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it. -* You can also check if there are translations for your language and add a review to them, that will help me know that the translation is correct and I can merge it. - * You could check in the GitHub Discussions for your language. - * Or you can filter the existing PRs by the ones with the label for your language, for example, for Spanish, the label is `lang-es`. - -* Use the same Python examples and only translate the text in the docs. You don't have to change anything for this to work. - -* Use the same images, file names, and links. You don't have to change anything for it to work. - -* To check the 2-letter code for the language you want to translate you can use the table List of ISO 639-1 codes. +* To check the 2-letter code for the language you want to translate, you can use the table List of ISO 639-1 codes. #### Existing language @@ -323,7 +313,7 @@ $ python ./scripts/docs.py live es Now you can go to http://127.0.0.1:8008 and see your changes live. -You will see that every language has all the pages. But some pages are not translated and have a notification about the missing translation. +You will see that every language has all the pages. But some pages are not translated and have an info box at the top, about the missing translation. Now let's say that you want to add a translation for the section [Features](features.md){.internal-link target=_blank}. @@ -342,7 +332,7 @@ docs/es/docs/features.md !!! tip Notice that the only change in the path and file name is the language code, from `en` to `es`. -If you go to your browser you will see that now the docs show your new section. 🎉 +If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 Now you can translate it all and see how it looks as you save the file. @@ -386,7 +376,7 @@ You can make the first pull request with those two files, `docs/ht/mkdocs.yml` a #### Preview the result -You can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). +As already mentioned above, you can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). Once you are done, you can also test it all as it would look online, including all the other languages. @@ -423,6 +413,25 @@ Serving at: http://127.0.0.1:8008
+#### Translation specific tips and guidelines + +* Translate only the Markdown documents (`.md`). Do not translate the code examples at `./docs_src`. + +* In code blocks within the Markdown document, translate comments (`# a comment`), but leave the rest unchanged. + +* Do not change anything enclosed in "``" (inline code). + +* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. + +* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. + +* Do not change the paths in links to images, code files, Markdown documents. + +* However, when a Markdown document is translated, the `#hash-parts` in links to its headings may change. Update these links if possible. + * Search for such links in the translated document using the regex `#[^# ]`. + * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". + * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. + ## Tests There is a script that you can run locally to test all the code and generate coverage reports in HTML: From 0be64abac748116f12d68ca766915ec46ff879df Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 17:43:08 +0000 Subject: [PATCH 006/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ccb2d1593..65a81f7d3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). * 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). From e6759aa6044929d1aaaea8280dd2e576a2339dc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B3=20Lino?= Date: Thu, 11 Jan 2024 20:52:15 +0100 Subject: [PATCH 007/104] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Instrument=20a=20FastAPI=20service=20adding=20tracing=20with?= =?UTF-8?q?=20OpenTelemetry=20and=20send/show=20traces=20in=20Grafana=20Te?= =?UTF-8?q?mpo=20(#9440)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Carol Willing Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index aea400dfc..412156442 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Nicoló Lino + author_link: https://www.nlino.com + link: https://github.com/softwarebloat/python-tracing-demo + title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo - author: Mikhail Rozhkov, Elena Samuylova author_link: https://www.linkedin.com/in/mnrozhkov/ link: https://www.evidentlyai.com/blog/fastapi-tutorial From 4dde172a969644e4e4f88b5d6c29b1d4d2e95303 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 19:52:37 +0000 Subject: [PATCH 008/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 65a81f7d3..23dbeb5b3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). * 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). * 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). From f74aeb00674d35d10e4f9f0ecd34a8e36a0df131 Mon Sep 17 00:00:00 2001 From: Hungtsetse <33526088+hungtsetse@users.noreply.github.com> Date: Fri, 12 Jan 2024 03:56:09 +0800 Subject: [PATCH 009/104] =?UTF-8?q?=F0=9F=93=9D=20Add=20hyperlink=20to=20`?= =?UTF-8?q?docs/en/docs/tutorial/static-files.md`=20(#10243)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/static-files.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 7a0c36af3..311d2b1c8 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -22,7 +22,7 @@ You can serve static files automatically from a directory using `StaticFiles`. This is different from using an `APIRouter` as a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application, etc. -You can read more about this in the **Advanced User Guide**. +You can read more about this in the [Advanced User Guide](../advanced/index.md){.internal-link target=_blank}. ## Details From 99769b966975b85321a8213b48a57828fac9453c Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 19:57:48 +0000 Subject: [PATCH 010/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 23dbeb5b3..66b7f260e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). * 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). * 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). From b62e379a55488d523c42718616f0ad7eea526850 Mon Sep 17 00:00:00 2001 From: Ankit Anchlia Date: Thu, 11 Jan 2024 13:59:29 -0600 Subject: [PATCH 011/104] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Explore=20How=20to=20Effectively=20Use=20JWT=20With=20FastAP?= =?UTF-8?q?I=20(#10212)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ankit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 412156442..b4b8687c4 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Ankit Anchlia + author_link: https://linkedin.com/in/aanchlia21 + link: https://hackernoon.com/explore-how-to-effectively-use-jwt-with-fastapi + title: Explore How to Effectively Use JWT With FastAPI - author: Nicoló Lino author_link: https://www.nlino.com link: https://github.com/softwarebloat/python-tracing-demo From cbcd3fe863a4ee537facb65acf0e8ef9e2b6da23 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 20:01:57 +0000 Subject: [PATCH 012/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 66b7f260e..b4b137a30 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). * 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). * 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). * 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). From d192ddacec3ffc2d0ff5ec43bc7f816358ab769c Mon Sep 17 00:00:00 2001 From: Pedro Augusto de Paula Barbosa Date: Thu, 11 Jan 2024 17:18:07 -0300 Subject: [PATCH 013/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Update=20highlight?= =?UTF-8?q?ed=20line=20in=20`docs/en/docs/tutorial/bigger-applications.md`?= =?UTF-8?q?=20(#5490)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/tutorial/bigger-applications.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 9ec3720c8..b2d928405 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -315,7 +315,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m Now we import the other submodules that have `APIRouter`s: -```Python hl_lines="5" title="app/main.py" +```Python hl_lines="4-5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` From 53a3dd740826362dd874c92d5c08fb5f607e2bc0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 20:18:31 +0000 Subject: [PATCH 014/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b4b137a30..80a581865 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). * 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). * 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). * 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). From fd97e8efe43baced1c040cac3627904b37f2380b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Szaci=C5=82owski?= <44623605+piotrszacilowski@users.noreply.github.com> Date: Thu, 11 Jan 2024 22:21:35 +0100 Subject: [PATCH 015/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20usage=20of=20To?= =?UTF-8?q?ken=20model=20in=20security=20docs=20(#9313)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra Sánchez Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../em/docs/advanced/security/oauth2-scopes.md | 6 +++--- docs/em/docs/tutorial/security/oauth2-jwt.md | 4 ++-- .../en/docs/advanced/security/oauth2-scopes.md | 18 +++++++++--------- docs/en/docs/tutorial/security/oauth2-jwt.md | 4 ++-- docs/ja/docs/tutorial/security/oauth2-jwt.md | 2 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 2 +- docs_src/security/tutorial004.py | 8 +++++--- docs_src/security/tutorial004_an.py | 6 +++--- docs_src/security/tutorial004_an_py310.py | 6 +++--- docs_src/security/tutorial004_an_py39.py | 6 +++--- docs_src/security/tutorial004_py310.py | 8 +++++--- docs_src/security/tutorial005.py | 8 +++++--- docs_src/security/tutorial005_an.py | 6 +++--- docs_src/security/tutorial005_an_py310.py | 6 +++--- docs_src/security/tutorial005_an_py39.py | 6 +++--- docs_src/security/tutorial005_py310.py | 8 +++++--- docs_src/security/tutorial005_py39.py | 8 +++++--- 17 files changed, 61 insertions(+), 51 deletions(-) diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index a4684352c..d82fe152b 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -56,7 +56,7 @@ Oauth2⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 🥇, ➡ 🔜 👀 🍕 👈 🔀 ⚪➡ 🖌 👑 **🔰 - 👩‍💻 🊮** [Oauth2⃣ ⏮ 🔐 (& 🔁), 📚 ⏮ 🥙 🀝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙ Oauth2⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -93,7 +93,7 @@ Oauth2⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. ✋ 👆 🈞, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕎 🚮 ↔ 👈 👩‍💻 🀙 💪 ✔, ⚖ 🕐 👆 ✔ 🔁. -```Python hl_lines="153" +```Python hl_lines="155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -118,7 +118,7 @@ Oauth2⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👥 🔚 ⚫ 📥 🎊 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. -```Python hl_lines="4 139 166" +```Python hl_lines="4 139 168" {!../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc207c566..bc3c943f8 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -192,13 +192,13 @@ $ openssl rand -hex 32 === "🐍 3⃣.6⃣ & 🔛" - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` === "🐍 3⃣.1⃣0⃣ & 🔛" - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 304a46090..b93d2991c 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152" + ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -88,7 +88,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -97,7 +97,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="152" + ```Python hl_lines="154" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -208,7 +208,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="153" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -217,7 +217,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="153" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 138 165" + ```Python hl_lines="3 138 167" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -274,7 +274,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 166" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -283,7 +283,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 166" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 4159b3659..1c792e3d9 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -285,7 +285,7 @@ Create a real JWT access token and return it !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -294,7 +294,7 @@ Create a real JWT access token and return it !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 348ffda01..d5b179aa0 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -167,7 +167,7 @@ JWTトヌクンの眲名に䜿甚するアルゎリズム`"HS256"`を指定し JWTアクセストヌクンを䜜成し、それを返したす。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 054198545..33a4d7fc7 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -170,7 +170,7 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问什牌。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 134c15c5a..044eec700 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -112,8 +112,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -125,7 +127,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index 204151a56..c78e8496c 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -115,10 +115,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -130,7 +130,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 64dfa15c6..36dbc677e 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -114,10 +114,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,7 +129,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index 631a8366e..23fc04a72 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -114,10 +114,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,7 +129,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 470f22e29..8363d45ab 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -111,8 +111,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -124,7 +126,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index ece461bc8..b16bf440a 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -143,8 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index c5b5609e5..95e406b32 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -144,10 +144,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -156,7 +156,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 5e81a50e1..c6116a5ed 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -143,10 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,7 +155,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index ae9811c68..af51c08b5 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -143,10 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,7 +155,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index 0fcdda4c0..37a22c709 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -142,8 +142,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -152,7 +154,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index d756c0b6b..c27580763 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -143,8 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) From 22e68b151d92aff6d6e0cdf001b08a792e20020d Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 21:21:57 +0000 Subject: [PATCH 016/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 80a581865..945d342d9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). * ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). * 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). * 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). From 0c796747a3d652f7d5d7fc59c5fbb68512b64ccf Mon Sep 17 00:00:00 2001 From: Ezzeddin Abdullah Date: Fri, 12 Jan 2024 00:25:37 +0200 Subject: [PATCH 017/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20template=20docs?= =?UTF-8?q?=20with=20more=20info=20about=20`url=5Ffor`=20(#5937)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/advanced/templates.md | 48 +++++++++++++++++-- docs_src/templates/templates/item.html | 2 +- .../test_templates/test_tutorial001.py | 5 +- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 583abda7f..6055b3017 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -46,21 +46,61 @@ $ pip install jinja2 ## Writing templates -Then you can write a template at `templates/item.html` with: +Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" {!../../../docs_src/templates/templates/item.html!} ``` -It will show the `id` taken from the "context" `dict` you passed: +### Template Context Values + +In the HTML that contains: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...it will show the `id` taken from the "context" `dict` you passed: ```Python -{"request": request, "id": id} +{"id": id} +``` + +For example, with an ID of `42`, this would render: + +```html +Item ID: 42 +``` + +### Template `url_for` Arguments + +You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*. + +So, the section with: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`. + +For example, with an ID of `42`, this would render: + +```html + ``` ## Templates and static files -You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. +You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} diff --git a/docs_src/templates/templates/item.html b/docs_src/templates/templates/item.html index a70287e77..27994ca99 100644 --- a/docs_src/templates/templates/item.html +++ b/docs_src/templates/templates/item.html @@ -4,6 +4,6 @@ -

Item ID: {{ id }}

+

Item ID: {{ id }}

diff --git a/tests/test_tutorial/test_templates/test_tutorial001.py b/tests/test_tutorial/test_templates/test_tutorial001.py index bfee5c090..4d4729425 100644 --- a/tests/test_tutorial/test_templates/test_tutorial001.py +++ b/tests/test_tutorial/test_templates/test_tutorial001.py @@ -16,7 +16,10 @@ def test_main(): client = TestClient(app) response = client.get("/items/foo") assert response.status_code == 200, response.text - assert b"

Item ID: foo

" in response.content + assert ( + b'

Item ID: foo

' + in response.content + ) response = client.get("/static/styles.css") assert response.status_code == 200, response.text assert b"color: green;" in response.content From 5f37d3870bd101bdda65e6dbda06ca969f6ef510 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 22:25:58 +0000 Subject: [PATCH 018/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 945d342d9..af3d2e2b2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). * 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). * ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). * 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). From ea84587a2f0431a7fad42395fd1dadee3dae3fed Mon Sep 17 00:00:00 2001 From: Turabek Gaybullaev <43612265+Torabek@users.noreply.github.com> Date: Fri, 12 Jan 2024 20:10:55 +0900 Subject: [PATCH 019/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Remove=20broken=20?= =?UTF-8?q?links=20from=20`external=5Flinks.yml`=20(#10943)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index b4b8687c4..00d6f696d 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -40,10 +40,6 @@ Articles: author_link: https://dev.to/ link: https://dev.to/teresafds/authorization-on-fastapi-with-casbin-41og title: Authorization on FastAPI with Casbin - - author: WayScript - author_link: https://www.wayscript.com - link: https://blog.wayscript.com/fast-api-quickstart/ - title: Quickstart Guide to Build and Host Responsive APIs with Fast API and WayScript - author: New Relic author_link: https://newrelic.com link: https://newrelic.com/instant-observability/fastapi/e559ec64-f765-4470-a15f-1901fcebb468 @@ -96,10 +92,6 @@ Articles: author_link: https://dev.to/factorlive link: https://dev.to/factorlive/python-facebook-messenger-webhook-with-fastapi-on-glitch-4n90 title: Python Facebook messenger webhook with FastAPI on Glitch - - author: Dom Patmore - author_link: https://twitter.com/dompatmore - link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0 - title: Authenticate Your FastAPI App with auth0 - author: Valon Januzaj author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/ link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b @@ -112,10 +104,6 @@ Articles: author_link: https://twitter.com/louis_guitton link: https://guitton.co/posts/fastapi-monitoring/ title: How to monitor your FastAPI service - - author: Julien Harbulot - author_link: https://julienharbulot.com/ - link: https://julienharbulot.com/notification-server.html - title: HTTP server to display desktop notifications - author: Precious Ndubueze author_link: https://medium.com/@gabbyprecious2000 link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37 @@ -164,18 +152,10 @@ Articles: author_link: https://wuilly.com/ link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/ title: Real-time Notifications with Python and Postgres - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream - title: Apache Kafka producer and consumer with FastAPI and aiokafka - author: Navule Pavan Kumar Rao author_link: https://www.linkedin.com/in/navule/ link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/ title: Create and Deploy FastAPI app to Heroku without using Docker - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda - title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM - author: Arthur Henrique author_link: https://twitter.com/arthurheinrique link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb @@ -200,10 +180,6 @@ Articles: author_link: https://dev.to/dbanty link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6 title: Why I'm Leaving Flask - - author: Rob Wagner - author_link: https://robwagner.dev/ - link: https://robwagner.dev/tortoise-fastapi-setup/ - title: Setting up Tortoise ORM with FastAPI - author: Mike Moritz author_link: https://medium.com/@mike.p.moritz link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b From e0eaaee7496e3f95cd0e1c47c5473c989f390ed6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 11:11:15 +0000 Subject: [PATCH 020/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index af3d2e2b2..671e63216 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). * 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). * 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). * ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). From 3ca38568c1a31628c3f5863fb67a99b6b44cec9d Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Fri, 12 Jan 2024 14:12:19 +0300 Subject: [PATCH 021/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/dependencies/classes-as-depe?= =?UTF-8?q?ndencies.md`=20(#10410)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Vladislav Kramorenko <85196001+Xewus@users.noreply.github.com> --- .../dependencies/classes-as-dependencies.md | 478 ++++++++++++++++++ 1 file changed, 478 insertions(+) create mode 100644 docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..b6ad25daf --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,478 @@ +# Классы как завОсОЌПстО + +ПрежЎе чеЌ углубОться в сОстеЌу **ВМеЎреМОя ЗавОсОЌПстей**, Ўавайте ПбМПвОЌ преЎыЎущОй прОЌер. + +## `СлПварь` Оз преЎыЎущегП прОЌера + +В преЎыЎущеЌ прОЌере Ќы вПзвращалО `слПварь` Оз Машей завОсОЌПстО: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +НП затеЌ Ќы пПлучаеЌ `слПварь` в параЌетре `commons` *фуМкцОО ПперацОО путО*. И Ќы зМаеЌ, чтП реЎактПры Ме ЌПгут ПбеспечОть ЎПстатПчМую пПЎЎержку Ўля `слПваря`, пПскПльку ПМО Ме ЌПгут зМать Ох ключО О тОпы зМачеМОй. + +Мы ЌПжеЌ сЎелать лучше... + +## ЧтП Ўелает завОсОЌПсть + +ДП сОх пПр вы вОЎелО завОсОЌПстО, ПбъявлеММые как фуМкцОО. + +НП этП Ме еЎОМствеММый спПсПб ПбъявлеМОя завОсОЌПстей (хПтя, верПятМП, бПлее распрПстраМеММый). + +КлючевыЌ фактПрПЌ является тП, чтП завОсОЌПсть ЎПлжМа быть "вызываеЌПй". + +В Python "**вызываеЌый**" - этП все, чтП Python ЌПжет "вызвать", как фуМкцОю. + +Так, еслО у вас есть Пбъект `something` (кПтПрый ЌПжет _Ме_ быть фуМкцОей) О вы ЌПжете "вызвать" егП (выпПлМОть) как: + +```Python +something() +``` + +ОлО + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +в такПЌ случае ПМ является "вызываеЌыЌ". + +## Классы как завОсОЌПстО + +Вы ЌПжете заЌетОть, чтП Ўля сПзЎаМОя экзеЌпляра класса в Python ОспПльзуется тПт же сОМтаксОс. + +НапрОЌер: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +В ЎаММПЌ случае `fluffy` является экзеЌплярПЌ класса `Cat`. + +А чтПбы сПзЎать `fluffy`, вы "вызываете" `Cat`. + +ТакОЌ ПбразПЌ, класс в Python также является **вызываеЌыЌ**. + +ТПгЎа в **FastAPI** в качестве завОсОЌПстО ЌПжМП ОспПльзПвать класс Python. + +На саЌПЌ Ўеле FastAPI прПверяет, чтП переЎаММый Пбъект является "вызываеЌыЌ" (фуМкцОя, класс ОлО чтП-лОбП еще) О указаМы МеПбхПЎОЌые Ўля егП вызПва параЌетры. + +ЕслО вы переЎаёте чтП-тП, чтП ЌПжМП "вызывать" в качестве завОсОЌПстО в **FastAPI**, тП ПМ буЎет аМалОзОрПвать параЌетры, МеПбхПЎОЌые Ўля "вызПва" этПгП Пбъекта О Пбрабатывать Ох так же, как параЌетры *фуМкцОО ПперацОО путО*. Включая пПЎзавОсОЌПстО. + +ЭтП ПтМПсОтся О к вызываеЌыЌ ПбъектаЌ без параЌетрПв. РабПта с МОЌО прПОсхПЎОт тПчМП так же, как О Ўля *фуМкцОй ПперацОО путО* без параЌетрПв. + +Теперь Ќы ЌПжеЌ ОзЌеМОть завОсОЌПсть `common_parameters`, указаММую выше, Ма класс `CommonQueryParams`: + +=== "Python 3.10+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="9-13" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +ОбратОте вМОЌаМОе Ма ЌетПЎ `__init__`, ОспПльзуеЌый Ўля сПзЎаМОя экзеЌпляра класса: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +...ОЌеет те же параЌетры, чтП О раМее ОспПльзуеЌая фуМкцОя `common_parameters`: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="6" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +ЭтО параЌетры О буЎут ОспПльзПваться **FastAPI** Ўля "решеМОя" завОсОЌПстО. + +В ПбПОх случаях ПМа буЎет ОЌеть: + +* НеПбязательМый параЌетр запрПса `q`, преЎставляющОй сПбПй `str`. +* ПараЌетр запрПса `skip`, преЎставляющОй сПбПй `int`, пП уЌПлчаМОю `0`. +* ПараЌетр запрПса `limit`, преЎставляющОй сПбПй `int`, пП уЌПлчаМОю равМый `100`. + +В ПбПОх случаях ЎаММые буЎут кПМвертОрПваМы, валОЎОрПваМы, ЎПкуЌеМтОрПваМы пП схеЌе OpenAPI О т.ÐŽ. + +## Как этП ОспПльзПвать + +Теперь вы ЌПжете ПбъявОть свПю завОсОЌПсть, ОспПльзуя этПт класс. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +**FastAPI** вызывает класс `CommonQueryParams`. ПрО этПЌ сПзЎается "экзеЌпляр" этПгП класса, кПтПрый буЎет переЎаМ в качестве параЌетра `commons` в вашу фуМкцОю. + +## АММПтацОя тОпа ОлО `Depends` + +ОбратОте вМОЌаМОе, чтП в прОвеЎеММПЌ выше кПЎе Ќы Ўва раза пОшеЌ `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +ППслеЎМОй параЌетр `CommonQueryParams`, в: + +```Python +... Depends(CommonQueryParams) +``` + +...этП тП, чтП **FastAPI** буЎет ОспПльзПвать, чтПбы узМать, чтП является завОсОЌПстью. + +Из МегП FastAPI Озвлечёт ПбъявлеММые параЌетры О ОЌеММП Ох буЎет вызывать. + +--- + +В этПЌ случае первый `CommonQueryParams`, в: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams ... + ``` + +...Ме ОЌеет МОкакПгП спецОальМПгП зМачеМОя Ўля **FastAPI**. FastAPI Ме буЎет ОспПльзПвать егП Ўля преПбразПваМОя ЎаММых, валОЎацОО О т.ÐŽ. (пПскПльку Ўля этПгП ОспПльзуется `Depends(CommonQueryParams)`). + +На саЌПЌ Ўеле ЌПжМП МапОсать прПстП: + +=== "Python 3.6+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons = Depends(CommonQueryParams) + ``` + +...как тут: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial003_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003.py!} + ``` + +НП ПбъявлеМОе тОпа прОветствуется, так как в этПЌ случае ваш реЎактПр буЎет зМать, чтП буЎет переЎаМП в качестве параЌетра `commons`, О тПгЎа ПМ сЌПжет пПЌПчь ваЌ с автПЎПпПлМеМОеЌ, прПверкПй тОпПв О т.ÐŽ: + + + +## СПкращеМОе + +НП вы вОЎОте, чтП зЎесь Ќы ОЌееЌ МекПтПрПе пПвтПреМОе кПЎа, ЎважЎы МапОсав `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +Для случаев, кПгЎа завОсОЌПстью является *кПМкретМый* класс, кПтПрый **FastAPI** "вызПвет" Ўля сПзЎаМОя экзеЌпляра этПгП класса, ЌПжМП ОспПльзПвать укПрПчеММую запОсь. + + +ВЌестП тПгП чтПбы пОсать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +...слеЎует МапОсать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "Python 3.6 без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends() + ``` + +Вы Пбъявляете завОсОЌПсть как тОп параЌетра О ОспПльзуете `Depends()` без какПгП-лОбП параЌетра, вЌестП тПгП чтПбы *сМПва* пОсать пПлМый класс вМутрО `Depends(CommonQueryParams)`. + +АМалПгОчМый прОЌер буЎет выгляЎеть слеЎующОЌ ПбразПЌ: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial004_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004.py!} + ``` + +...О **FastAPI** буЎет зМать, чтП Ўелать. + +!!! tip "ППЎсказка" + ЕслО этП пПкажется ваЌ бПлее запутаММыЌ, чеЌ пПлезМыЌ, Ме Пбращайте вМОЌаМОя, этП ваЌ Ме *МужМП*. + + ЭтП прПстП сПкращеМОе. ППтПЌу чтП **FastAPI** забПтОтся П тПЌ, чтПбы пПЌПчь ваЌ свестО к ЌОМОЌуЌу пПвтПреМОе кПЎа. From 4c231854dc2dc7336f8ad3ed399b806f6dc7d498 Mon Sep 17 00:00:00 2001 From: HiemalBeryl <63165207+HiemalBeryl@users.noreply.github.com> Date: Fri, 12 Jan 2024 19:13:04 +0800 Subject: [PATCH 022/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20in?= =?UTF-8?q?=20`docs/zh/docs/tutorial/extra-data-types.md`=20(#10727)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/extra-data-types.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index a74efa61b..f4a77050c 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -44,11 +44,11 @@ * 产生的暡匏将指定那些 `set` 的倌是唯䞀的 (䜿甚 JSON 暡匏的 `uniqueItems`)。 * `bytes`: * 标准的 Python `bytes`。 - * 圚请求和盞应䞭被圓䜜 `str` 倄理。 + * 圚请求和响应䞭被圓䜜 `str` 倄理。 * 生成的暡匏将指定这䞪 `str` 是 `binary` "栌匏"。 * `Decimal`: * 标准的 Python `Decimal`。 - * 圚请求和盞应䞭被圓做 `float` 䞀样倄理。 + * 圚请求和响应䞭被圓做 `float` 䞀样倄理。 * 悚可以圚这里检查所有有效的pydantic数据类型: Pydantic data types. ## 䟋子 From 6a4aed45f05c7e0c9db635e74b29e76ecae6ca5c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 11:13:22 +0000 Subject: [PATCH 023/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 671e63216..457bc5e98 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,10 @@ hide: * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). * 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). + ## 0.109.0 ### Features From 753c8136d8b5ecffe27f7b2ac18e02687f2c269b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 11:15:04 +0000 Subject: [PATCH 024/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 457bc5e98..628e18b10 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -24,6 +24,7 @@ hide: ### Translations +* ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). ## 0.109.0 From f1329abf9930165f4c53cb760fd9f809b4ed6266 Mon Sep 17 00:00:00 2001 From: theoohoho <31537466+theoohoho@users.noreply.github.com> Date: Fri, 12 Jan 2024 21:39:54 +0800 Subject: [PATCH 025/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20broken=20lin?= =?UTF-8?q?k=20in=20`docs/tutorial/sql-databases.md`=20in=20several=20lang?= =?UTF-8?q?uages=20(#10716)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/tutorial/sql-databases.md | 2 +- docs/en/docs/tutorial/sql-databases.md | 2 +- docs/zh/docs/tutorial/sql-databases.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 9d46c2460..e3ced7ef4 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -501,7 +501,7 @@ current_user.items "🛠" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇞🇲 🏷, 🚮 🆕 🔢, ♒. 🔁 👈 🔀 💜, 🚮 🆕 🏓, 🆕 🏓, ♒. -👆 💪 🔎 🖌 ⚗ FastAPI 🏗 📄 ⚪➡ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. +👆 💪 🔎 🖌 ⚗ FastAPI 🏗 📄 ⚪➡ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. ### ✍ 🔗 diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 161d5491d..70d9482df 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -513,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job). A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc. -You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. +You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. ### Create a dependency diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index a936eb27b..c49374971 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -499,7 +499,7 @@ current_user.items “迁移”是每圓悚曎改 SQLAlchemy 暡型的结构、添加新属性等以圚数据库䞭倍制这些曎改、添加新列、新衚等时所需的䞀组步骀。 -悚可以圚[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的暡板䞭扟到䞀䞪 FastAPI 项目䞭的 Alembic 瀺䟋。具䜓圚[`alembic`代码目圕䞭](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/)。 +悚可以圚[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的暡板䞭扟到䞀䞪 FastAPI 项目䞭的 Alembic 瀺䟋。具䜓圚[`alembic`代码目圕䞭](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/)。 ### 创建䟝赖项 From dc704036a2dd646c30fb9d58ec8a707236135f84 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 13:40:15 +0000 Subject: [PATCH 026/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 628e18b10..55b6a6894 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). * ✏ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). * 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). * 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). From 7e0e16fa3669d83a9992ff5aee669135ebb41fc1 Mon Sep 17 00:00:00 2001 From: Jacob McDonald <48448372+jacob-indigo@users.noreply.github.com> Date: Fri, 12 Jan 2024 09:03:25 -0500 Subject: [PATCH 027/104] =?UTF-8?q?=F0=9F=93=9D=20Add=20warning=20about=20?= =?UTF-8?q?lifespan=20functions=20and=20backwards=20compatibility=20with?= =?UTF-8?q?=20events=20(#10734)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/advanced/events.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 6df1411d1..ca9d86ae4 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -92,7 +92,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager** ## Alternative Events (deprecated) !!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. + The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. You can probably skip this part. From 38915783fc355a4eb49310182f353778982c70e1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:03:51 +0000 Subject: [PATCH 028/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 55b6a6894..01eefb052 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). * ✏ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). * ✏ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). * 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). From 58e2f8b1d9265a90aa0aecd7e7eb1ca8c19bf1de Mon Sep 17 00:00:00 2001 From: Delitel-WEB <57365921+Delitel-WEB@users.noreply.github.com> Date: Fri, 12 Jan 2024 17:10:31 +0300 Subject: [PATCH 029/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`docs/ru/docs/index.md`=20(#10672)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 97a3947bd..6c99f623d 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -321,7 +321,7 @@ def update_item(item_id: int, item: Item): ТакОЌ ПбразПЌ, вы Пбъявляете **ПЎОМ раз** тОпы параЌетрПв, телП О т. ÐŽ. в качестве параЌетрПв фуМкцОО. -Вы Ўелаете этП Оспльзуя стаМЎартМую сПвреЌеММую тОпОзацОю Python. +Вы Ўелаете этП ОспПльзуя стаМЎартМую сПвреЌеММую тОпОзацОю Python. ВаЌ Ме МужМП Озучать МПвый сОМтаксОс, ЌетПЎы ОлО классы кПМкретМПй бОблОПтекО О т. ÐŽ. From ca33b6edac847e27a9543c0a8dad95c1fcfc65fc Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:10:54 +0000 Subject: [PATCH 030/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 01eefb052..4e795b8cc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). From c81ab17a594e140e66424addfe8374d72550728a Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Fri, 12 Jan 2024 15:15:29 +0100 Subject: [PATCH 031/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/background-tasks.md`=20(#1056?= =?UTF-8?q?6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/background-tasks.md | 126 ++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 docs/de/docs/tutorial/background-tasks.md diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..a7bfd55a7 --- /dev/null +++ b/docs/de/docs/tutorial/background-tasks.md @@ -0,0 +1,126 @@ +# Hintergrundtasks + +Sie können Hintergrundtasks (Hintergrund-Aufgaben) definieren, die *nach* der RÃŒckgabe einer Response ausgefÃŒhrt werden sollen. + +Das ist nÃŒtzlich fÃŒr VorgÀnge, die nach einem Request ausgefÃŒhrt werden mÃŒssen, bei denen der Client jedoch nicht unbedingt auf den Abschluss des Vorgangs warten muss, bevor er die Response erhÀlt. + +Hierzu zÀhlen beispielsweise: + +* E-Mail-Benachrichtigungen, die nach dem AusfÃŒhren einer Aktion gesendet werden: + * Da die Verbindung zu einem E-Mail-Server und das Senden einer E-Mail in der Regel „langsam“ ist (einige Sekunden), können Sie die Response sofort zurÃŒcksenden und die E-Mail-Benachrichtigung im Hintergrund senden. +* Daten verarbeiten: + * Angenommen, Sie erhalten eine Datei, die einen langsamen Prozess durchlaufen muss. Sie können als Response „Accepted“ (HTTP 202) zurÃŒckgeben und die Datei im Hintergrund verarbeiten. + +## `BackgroundTasks` verwenden + +Importieren Sie zunÀchst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** erstellt fÃŒr Sie das Objekt vom Typ `BackgroundTasks` und ÃŒbergibt es als diesen Parameter. + +## Eine Taskfunktion erstellen + +Erstellen Sie eine Funktion, die als Hintergrundtask ausgefÃŒhrt werden soll. + +Es handelt sich schlicht um eine Standard-Funktion, die Parameter empfangen kann. + +Es kann sich um eine `async def`- oder normale `def`-Funktion handeln. **FastAPI** weiß, wie damit zu verfahren ist. + +In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail simulierend). + +Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## Den Hintergrundtask hinzufÃŒgen + +Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` erhÀlt als Argumente: + +* Eine Taskfunktion, die im Hintergrund ausgefÃŒhrt wird (`write_notification`). +* Eine beliebige Folge von Argumenten, die der Reihe nach an die Taskfunktion ÃŒbergeben werden sollen (`email`). +* Alle SchlÃŒsselwort-Argumente, die an die Taskfunktion ÃŒbergeben werden sollen (`message="some notification"`). + +## Dependency Injection + +Die Verwendung von `BackgroundTasks` funktioniert auch mit dem Dependency Injection System. Sie können einen Parameter vom Typ `BackgroundTasks` auf mehreren Ebenen deklarieren: in einer *Pfadoperation-Funktion*, in einer AbhÀngigkeit (Dependable), in einer UnterabhÀngigkeit usw. + +**FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengefÃŒhrt und anschließend im Hintergrund ausgefÃŒhrt werden: + +=== "Python 3.10+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14 16 23 26" + {!> ../../../docs_src/background_tasks/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11 13 20 23" + {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002.py!} + ``` + +In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. + +Wenn im Request ein Query-Parameter enthalten war, wird dieser in einem Hintergrundtask in das Log geschrieben. + +Und dann schreibt ein weiterer Hintergrundtask, der in der *Pfadoperation-Funktion* erstellt wird, eine Nachricht unter Verwendung des Pfad-Parameters `email`. + +## Technische Details + +Die Klasse `BackgroundTasks` stammt direkt von `starlette.background`. + +Sie wird direkt in FastAPI importiert/inkludiert, sodass Sie sie von `fastapi` importieren können und vermeiden, versehentlich das alternative `BackgroundTask` (ohne das `s` am Ende) von `starlette.background` zu importieren. + +Indem Sie nur `BackgroundTasks` (und nicht `BackgroundTask`) verwenden, ist es dann möglich, es als *Pfadoperation-Funktion*-Parameter zu verwenden und **FastAPI** den Rest fÃŒr Sie erledigen zu lassen, genau wie bei der direkten Verwendung des `Request`-Objekts. + +Es ist immer noch möglich, `BackgroundTask` allein in FastAPI zu verwenden, aber Sie mÃŒssen das Objekt in Ihrem Code erstellen und eine Starlette-`Response` zurÃŒckgeben, die es enthÀlt. + +Weitere Details finden Sie in der offiziellen Starlette-Dokumentation fÃŒr Hintergrundtasks. + +## Vorbehalt + +Wenn Sie umfangreiche Hintergrundberechnungen durchfÃŒhren mÃŒssen und diese nicht unbedingt vom selben Prozess ausgefÃŒhrt werden mÃŒssen (z. B. mÃŒssen Sie Speicher, Variablen, usw. nicht gemeinsam nutzen), könnte die Verwendung anderer größerer Tools wie z. B. Celery von Vorteil sein. + +Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die AusfÃŒhrung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern. + +Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert. + +Wenn Sie jedoch ÃŒber dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausfÃŒhren mÃŒssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden. + +## Zusammenfassung + +Importieren und verwenden Sie `BackgroundTasks` mit Parametern in *Pfadoperation-Funktionen* und AbhÀngigkeiten, um Hintergrundtasks hinzuzufÃŒgen. From 4f9ad80f5d48377dae978130692dc4965fa19a2a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:15:52 +0000 Subject: [PATCH 032/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4e795b8cc..b69ad9e78 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). From 0aee526de9fa908027c100237a692407a5e49818 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 12 Jan 2024 15:38:17 +0100 Subject: [PATCH 033/104] =?UTF-8?q?=F0=9F=94=A7=20=20Add=20support=20for?= =?UTF-8?q?=20translations=20to=20languages=20with=20a=20longer=20code=20n?= =?UTF-8?q?ame,=20like=20`zh-hant`=20(#10950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/language_names.yml | 1 + scripts/docs.py | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/language_names.yml b/docs/language_names.yml index fbbbde303..7c37ff2b1 100644 --- a/docs/language_names.yml +++ b/docs/language_names.yml @@ -179,4 +179,5 @@ yi: יי֎דיש yo: Yorùbá za: Saɯ cueŋƅ zh: 汉语 +zh-hant: 繁體䞭文 zu: isiZulu diff --git a/scripts/docs.py b/scripts/docs.py index a6710d7a5..37a7a3477 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -53,9 +53,6 @@ def get_lang_paths() -> List[Path]: def lang_callback(lang: Optional[str]) -> Union[str, None]: if lang is None: return None - if not lang.isalpha() or len(lang) != 2: - typer.echo("Use a 2 letter language code, like: es") - raise typer.Abort() lang = lang.lower() return lang @@ -289,6 +286,12 @@ def update_config() -> None: for lang_dict in languages: code = list(lang_dict.keys())[0] url = lang_dict[code] + if code not in local_language_names: + print( + f"Missing language name for: {code}, " + "update it in docs/language_names.yml" + ) + raise typer.Abort() use_name = f"{code} - {local_language_names[code]}" new_alternate.append({"link": url, "name": use_name}) new_alternate.append({"link": "/em/", "name": "😉"}) From 44f3ebce6edc3926876ac0c0370fa8b69e2dea19 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:38:40 +0000 Subject: [PATCH 034/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b69ad9e78..eb78fe8cf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,10 @@ hide: * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). +### Internal + +* 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). + ## 0.109.0 ### Features From be0bd344463c04ce095051a1fd6bf209165b3e94 Mon Sep 17 00:00:00 2001 From: ooknimm <68068775+ooknimm@users.noreply.github.com> Date: Fri, 12 Jan 2024 23:52:00 +0900 Subject: [PATCH 035/104] =?UTF-8?q?=E2=9C=85=20Re-enable=20test=20in=20`te?= =?UTF-8?q?sts/test=5Ftutorial/test=5Fheader=5Fparams/test=5Ftutorial003.p?= =?UTF-8?q?y`=20after=20fix=20in=20Starlette=20(#10904)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial/test_header_params/test_tutorial003.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py index 268df7a3e..6f7de8ed4 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003.py @@ -12,8 +12,12 @@ client = TestClient(app) [ ("/items", None, 200, {"X-Token values": None}), ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), + ( + "/items", + [("x-token", "foo"), ("x-token", "bar")], + 200, + {"X-Token values": ["foo", "bar"]}, + ), ], ) def test(path, headers, expected_status, expected_response): From 22e5d9e27fd3079e693cda8ae5c5a44c53b61ca2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:52:20 +0000 Subject: [PATCH 036/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index eb78fe8cf..2f82b70d6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). + ### Docs * 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). From 91666b3556aedbaae2c84112ac272d23f312e5cb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Jan 2024 10:00:18 -0500 Subject: [PATCH 037/104] =?UTF-8?q?=E2=AC=86=20Bump=20dawidd6/action-downl?= =?UTF-8?q?oad-artifact=20from=202.28.0=20to=203.0.0=20(#10777)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 2.28.0 to 3.0.0. - [Release notes](https://github.com/dawidd6/action-download-artifact/releases) - [Commits](https://github.com/dawidd6/action-download-artifact/compare/v2.28.0...v3.0.0) --- updated-dependencies: - dependency-name: dawidd6/action-download-artifact dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 2 +- .github/workflows/smokeshow.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 155ebd0a8..2bec6682c 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -21,7 +21,7 @@ jobs: mkdir ./site - name: Download Artifact Docs id: download - uses: dawidd6/action-download-artifact@v2.28.0 + uses: dawidd6/action-download-artifact@v3.0.0 with: if_no_artifact_found: ignore github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 38b44c413..229f56a9f 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -24,7 +24,7 @@ jobs: - run: pip install smokeshow - - uses: dawidd6/action-download-artifact@v2.28.0 + - uses: dawidd6/action-download-artifact@v3.0.0 with: github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} workflow: test.yml From 0ce4f80ac9aea70af3425bd337c875a85b2d4625 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:00:39 +0000 Subject: [PATCH 038/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f82b70d6..156c48bbe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -37,6 +37,7 @@ hide: ### Internal +* ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). ## 0.109.0 From 25646a5070064053309259f1e69c98015c5ec633 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jiri=20Dan=C4=9Bk?= Date: Fri, 12 Jan 2024 16:01:06 +0100 Subject: [PATCH 039/104] =?UTF-8?q?=F0=9F=94=A7=20Fix=20Ruff=20configurati?= =?UTF-8?q?on=20unintentionally=20enabling=20and=20re-disabling=20mccabe?= =?UTF-8?q?=20complexity=20check=20(#10893)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix mistake in Ruff configuration unintentionally enabling mccabe complexity check Enabling "C" turns on complexity checks (C90, mccabe), which is unintended Instead, enable "C4" to get flake8-comprehensions checks See docs at https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4 Co-authored-by: Sebastián Ramírez --- pyproject.toml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 8e7f8bbbe..3e43f35e1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -145,15 +145,14 @@ select = [ "W", # pycodestyle warnings "F", # pyflakes "I", # isort - "C", # flake8-comprehensions "B", # flake8-bugbear + "C4", # flake8-comprehensions "UP", # pyupgrade ] ignore = [ "E501", # line too long, handled by black "B008", # do not perform function calls in argument defaults - "C901", # too complex - "W191", # indentation contains tabs + "W191", # indentation contains tabs ] [tool.ruff.per-file-ignores] From a2937099982b7da564279619f0cb257df33521f6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Jan 2024 10:01:52 -0500 Subject: [PATCH 040/104] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.8.10=20to=201.8.11=20(#10731)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.10 to 1.8.11. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.10...v1.8.11) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8cbd01b92..d053be0a0 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -32,7 +32,7 @@ jobs: - name: Build distribution run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.10 + uses: pypa/gh-action-pypi-publish@v1.8.11 with: password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context From c9e46ae12cfe5e32a25a78dca7499db1fae55059 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:02:38 +0000 Subject: [PATCH 041/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 156c48bbe..558bd10b1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). * ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). ### Docs From bc7d026b6ca487598a758b20c5935ccde1eace11 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:04:40 +0000 Subject: [PATCH 042/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 558bd10b1..65128b29a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). From b0cd4f915bce79575e890e4ae0cccd5b15f2e38f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Jan 2024 16:13:58 +0100 Subject: [PATCH 043/104] =?UTF-8?q?=E2=AC=86=20Bump=20actions/setup-python?= =?UTF-8?q?=20from=204=20to=205=20(#10764)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4 to 5. - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/setup-python dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build-docs.yml | 4 ++-- .github/workflows/publish.yml | 2 +- .github/workflows/smokeshow.yml | 2 +- .github/workflows/test.yml | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 51c069d9e..abf2b90f6 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -39,7 +39,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 @@ -80,7 +80,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d053be0a0..8ebb28a80 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -15,7 +15,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.10" # Issue ref: https://github.com/actions/setup-python/issues/436 diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 229f56a9f..10bff67ae 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -18,7 +18,7 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.9' diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 032db9c9c..b6b173685 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -19,7 +19,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -57,7 +57,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -98,7 +98,7 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.8' # Issue ref: https://github.com/actions/setup-python/issues/436 From 26e57903d134742ba0ee8e65ce7985cd398afdea Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:14:18 +0000 Subject: [PATCH 044/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 65128b29a..19b4d8a35 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). From fad1a464e73003feb8d5ae47f5d676faf353dd3e Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Sat, 13 Jan 2024 02:00:31 +0100 Subject: [PATCH 045/104] =?UTF-8?q?=F0=9F=94=A7=20=20Group=20dependencies?= =?UTF-8?q?=20on=20dependabot=20updates=20(#10952)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/dependabot.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index cd972a0ba..0a59adbd6 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,6 +11,10 @@ updates: - package-ecosystem: "pip" directory: "/" schedule: - interval: "daily" + interval: "monthly" + groups: + python-packages: + patterns: + - "*" commit-message: prefix: ⬆ From 1ce27fd743cf95901ca44fcf24805b596615581a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 01:00:55 +0000 Subject: [PATCH 046/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 19b4d8a35..13efb84e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex). * ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). From 1caee0f105d64f475e369a82f9cac90472e54d61 Mon Sep 17 00:00:00 2001 From: Ahmed Ashraf <104530599+ahmedabdou14@users.noreply.github.com> Date: Sat, 13 Jan 2024 14:49:05 +0300 Subject: [PATCH 047/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20Pydantic=20m?= =?UTF-8?q?ethod=20name=20in=20`docs/en/docs/advanced/path-operation-advan?= =?UTF-8?q?ced-configuration.md`=20(#10826)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ahmed Ashraf --- docs/en/docs/advanced/path-operation-advanced-configuration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 7ca88d43e..8b79bfe22 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -163,7 +163,7 @@ For example, in this application we don't use FastAPI's integrated functionality ``` !!! info - In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_schema_json()`. + In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. From cc5711e6f105251f8e1952c0a10c660a258a0ed3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 11:49:51 +0000 Subject: [PATCH 048/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 13efb84e9..973073205 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +* ✏ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14). + ### Refactors * 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). From c3e2aa9dc2b1fbdb48009ed532410e1e75c2f231 Mon Sep 17 00:00:00 2001 From: fhabers21 <58401847+fhabers21@users.noreply.github.com> Date: Sat, 13 Jan 2024 12:50:36 +0100 Subject: [PATCH 049/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/index.md`=20(#9502)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/de/docs/tutorial/index.md | 80 ++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 docs/de/docs/tutorial/index.md diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md new file mode 100644 index 000000000..dd7ed43bd --- /dev/null +++ b/docs/de/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Tutorial - Benutzerhandbuch - Intro + +Diese Anleitung zeigt Ihnen Schritt fÃŒr Schritt, wie Sie **FastAPI** mit den meisten Funktionen nutzen können. + +Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema ÃŒbergehen können, um Ihre speziellen API-Anforderungen zu lösen. + +Außerdem dienen diese als zukÃŒnftige Referenz. + +Dadurch können Sie jederzeit zurÃŒckkommen und sehen genau das, was Sie benötigen. + +## Den Code ausfÃŒhren + +Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt). + +Um eines der Beispiele auszufÃŒhren, kopieren Sie den Code in die Datei `main.py`, und starten Sie `uvicorn` mit: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +Es wird **ausdrÌcklich empfohlen**, dass Sie den Code schreiben oder kopieren, ihn bearbeiten und lokal ausfÌhren. + +Die Verwendung in Ihrem eigenen Editor zeigt Ihnen die Vorteile von FastAPI am besten, wenn Sie sehen, wie wenig Code Sie schreiben mÌssen, all die TypprÌfungen, die automatische VervollstÀndigung usw. + +--- + +## FastAPI installieren + +Der erste Schritt besteht aus der Installation von FastAPI. + +FÌr dieses Tutorial empfiehlt es sich, FastAPI mit allen optionalen AbhÀngigkeiten und Funktionen zu installieren: + +
+ +```console +$ pip install "fastapi[all]" + +---> 100% +``` + +
+ +...dies beinhaltet auch `uvicorn`, das Sie als Server verwenden können, auf dem Ihr Code lÀuft. + +!!! Hinweis + Sie können die Installation auch in einzelnen Schritten ausfÃŒhren. + + Dies werden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung produktiv einsetzen möchten: + + ``` + pip install fastapi + ``` + + Installieren Sie auch `uvicorn`, dies arbeitet als Server: + + ``` + pip install "uvicorn[standard]" + ``` + + Dasselbe gilt fÃŒr jede der optionalen AbhÀngigkeiten, die Sie verwenden möchten. + +## Erweitertes Benutzerhandbuch + +ZusÀtzlich gibt es ein **Erweitertes Benutzerhandbuch**, dies können Sie spÀter nach diesem **Tutorial - Benutzerhandbuch** lesen. + +Das **Erweiterte Benutzerhandbuch** baut auf dieses Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen zusÀtzliche Funktionen bei. + +Allerdings sollten Sie zuerst das **Tutorial - Benutzerhandbuch** lesen (was Sie gerade lesen). + +Es ist so konzipiert, dass Sie nur mit dem **Tutorial - Benutzerhandbuch** eine vollstÀndige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusÀtzlichen Ideen aus dem **Erweiterten Benutzerhandbuch** erweitern können. From 4299e712fb600b6460f85f551a2dd1d75ca7be05 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 11:51:55 +0000 Subject: [PATCH 050/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 973073205..66f14ef1e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). * 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). From a37ac3819ee9b8d19d045d53d742779109d2f711 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Jos=C3=A9=20L=C3=B3pez=20Lira?= Date: Sat, 13 Jan 2024 06:57:27 -0500 Subject: [PATCH 051/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20for?= =?UTF-8?q?=20Spanish=20documentation=20(#10957)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/advanced/additional-status-codes.md | 2 +- docs/es/docs/advanced/response-directly.md | 2 +- docs/es/docs/features.md | 14 +++++++------- docs/es/docs/index.md | 8 ++++---- docs/es/docs/python-types.md | 16 ++++++++-------- docs/es/docs/tutorial/first-steps.md | 2 +- docs/es/docs/tutorial/index.md | 2 +- docs/es/docs/tutorial/path-params.md | 6 +++--- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 1f28ea85b..eaa3369eb 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -23,7 +23,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte No será serializado con el modelo, etc. - Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). + Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). !!! note "Detalles Técnicos" También podrías utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 54dadf576..dee44ac08 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -21,7 +21,7 @@ Y cuando devuelves una `Response`, **FastAPI** la pasará directamente. No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc. -Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc. +Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquier declaración de datos o validación, etc. ## Usando el `jsonable_encoder` en una `Response` diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index d05c4f73e..d68791d63 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -13,7 +13,7 @@ ### Documentación automática -Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluídas por defecto, porque el framework está basado en OpenAPI. +Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluidas por defecto, porque el framework está basado en OpenAPI. * Swagger UI, con exploración interactiva, llama y prueba tu API directamente desde tu navegador. @@ -25,7 +25,7 @@ Documentación interactiva de la API e interfaces web de exploración. Hay múlt ### Simplemente Python moderno -Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintáxis nueva, solo Python moderno. +Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintaxis nueva, solo Python moderno. Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}. @@ -72,9 +72,9 @@ my_second_user: User = User(**second_user_data) El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo. -En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "autocompletado". +En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "auto-completado". -El framework **FastAPI** está creado para satisfacer eso. El autocompletado funciona en todas partes. +El framework **FastAPI** está creado para satisfacer eso. El auto-completado funciona en todas partes. No vas a tener que volver a la documentación seguido. @@ -140,13 +140,13 @@ FastAPI incluye un sistema de https://github.com/florimondmanca/asgi-lifespan#usage. + If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. ## Other Asynchronous Function Calls From b24c4870d8f8f0547d956ac8c1d2c751f1f66b69 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 12:10:29 +0000 Subject: [PATCH 054/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c632cc0b0..2234624f0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Docs +* ✏ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). * 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). * ✏ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). From 83e386519d30d8c732249983ffdf7200e8af5a5d Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Sat, 13 Jan 2024 13:16:22 +0100 Subject: [PATCH 055/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20A=20few=20tweaks?= =?UTF-8?q?=20in=20`docs/de/docs/tutorial/first-steps.md`=20(#10959)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/first-steps.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index 5997f138f..27ba3ec16 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -43,7 +43,7 @@ Diese Zeile zeigt die URL, unter der Ihre Anwendung auf Ihrem lokalen Computer b Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. -Sie werden folgende JSON-Antwort sehen: +Sie werden folgende JSON-Response sehen: ```JSON {"message": "Hello World"} @@ -81,7 +81,7 @@ Diese Schemadefinition enthÀlt Ihre API-Pfade, die möglichen Parameter, welche #### Daten-„Schema“ -Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z.B. einen JSON-Inhalt. +Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z. B. einen JSON-Inhalt. In diesem Fall sind die JSON-Attribute und deren Datentypen, usw. gemeint. @@ -328,6 +328,6 @@ Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert we * Importieren Sie `FastAPI`. * Erstellen Sie eine `app` Instanz. -* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z.B. `@app.get("/")`). -* Schreiben Sie eine **Pfadoperation-Funktion** (wie z.B. oben `def root(): ...`). -* Starten Sie den Entwicklungsserver (z.B. `uvicorn main:app --reload`). +* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z. B. `@app.get("/")`). +* Schreiben Sie eine **Pfadoperation-Funktion** (wie z. B. oben `def root(): ...`). +* Starten Sie den Entwicklungsserver (z. B. `uvicorn main:app --reload`). From cca6203c18552aa95c7ad0f7fd972fd6e86d0d77 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 12:19:28 +0000 Subject: [PATCH 056/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2234624f0..510b842ba 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Docs +* ✏ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). * 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). From de0126d145c920c992c605538e63fe0e46b508d5 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Sat, 13 Jan 2024 17:31:38 +0300 Subject: [PATCH 057/104] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Simplify=20string?= =?UTF-8?q?=20format=20with=20f-strings=20in=20`fastapi/utils.py`=20(#1057?= =?UTF-8?q?6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/utils.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index f8463dda2..0019c2153 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -173,17 +173,17 @@ def generate_operation_id_for_path( DeprecationWarning, stacklevel=2, ) - operation_id = name + path + operation_id = f"{name}{path}" operation_id = re.sub(r"\W", "_", operation_id) - operation_id = operation_id + "_" + method.lower() + operation_id = f"{operation_id}_{method.lower()}" return operation_id def generate_unique_id(route: "APIRoute") -> str: - operation_id = route.name + route.path_format + operation_id = f"{route.name}{route.path_format}" operation_id = re.sub(r"\W", "_", operation_id) assert route.methods - operation_id = operation_id + "_" + list(route.methods)[0].lower() + operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" return operation_id From 61a08d0c60cbe29784bb64cdbdea5d613a38b2e5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 14:31:58 +0000 Subject: [PATCH 058/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 510b842ba..1fc1a1695 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Refactors +* ♻ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub). * 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). * ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). From f18eadb7de142d6bf37eff900731329a541758f5 Mon Sep 17 00:00:00 2001 From: Emmett Butler <723615+emmettbutler@users.noreply.github.com> Date: Sat, 13 Jan 2024 07:10:26 -0800 Subject: [PATCH 059/104] =?UTF-8?q?=E2=9C=85=20Refactor=20tests=20for=20du?= =?UTF-8?q?plicate=20operation=20ID=20generation=20for=20compatibility=20w?= =?UTF-8?q?ith=20other=20tools=20running=20the=20FastAPI=20test=20suite=20?= =?UTF-8?q?(#10876)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- tests/test_generate_unique_id_function.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test_generate_unique_id_function.py b/tests/test_generate_unique_id_function.py index c5ef5182b..5aeec6636 100644 --- a/tests/test_generate_unique_id_function.py +++ b/tests/test_generate_unique_id_function.py @@ -1626,6 +1626,9 @@ def test_warn_duplicate_operation_id(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") client.get("/openapi.json") - assert len(w) == 2 - assert issubclass(w[-1].category, UserWarning) - assert "Duplicate Operation ID" in str(w[-1].message) + assert len(w) >= 2 + duplicate_warnings = [ + warning for warning in w if issubclass(warning.category, UserWarning) + ] + assert len(duplicate_warnings) > 0 + assert "Duplicate Operation ID" in str(duplicate_warnings[0].message) From e90fc7bed4213fbf42195830a1a8f54288be4fb8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 15:10:47 +0000 Subject: [PATCH 060/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1fc1a1695..5e02e2352 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Refactors +* ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler). * ♻ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub). * 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). * ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). From dcc952d6990c507956669e6fc5cddba0530c79d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 15 Jan 2024 11:32:16 +0100 Subject: [PATCH 061/104] =?UTF-8?q?=E2=9C=A8=20=20Include=20HTTP=20205=20i?= =?UTF-8?q?n=20status=20codes=20with=20no=20body=20(#10969)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index 0019c2153..53b2fa0c3 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -53,7 +53,7 @@ def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: }: return True current_status_code = int(status_code) - return not (current_status_code < 200 or current_status_code in {204, 304}) + return not (current_status_code < 200 or current_status_code in {204, 205, 304}) def get_path_param_names(path: str) -> Set[str]: From 69dc735fc2339f8b39a9f1b01ced7974df9c4a65 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 10:32:42 +0000 Subject: [PATCH 062/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5e02e2352..7b09977e7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,10 @@ hide: * ✏ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14). +### Features + +* ✹ Include HTTP 205 in status codes with no body. PR [#10969](https://github.com/tiangolo/fastapi/pull/10969) by [@tiangolo](https://github.com/tiangolo). + ### Refactors * ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler). From 63e5396a78a470c39558a37d1fefbbe1bcbf4db7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 15 Jan 2024 16:13:48 +0100 Subject: [PATCH 063/104] =?UTF-8?q?=F0=9F=91=B7=20Add=20changes-requested?= =?UTF-8?q?=20handling=20in=20GitHub=20Action=20issue=20manager=20(#10971)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue-manager.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index bb967fa11..d1aad28fd 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -31,5 +31,9 @@ jobs: "answered": { "delay": 864000, "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs." + }, + "changes-requested": { + "delay": 2628000, + "message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." } } From 2b6f12a5d00717f40b1fa0fa5e882fe021862559 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:14:34 +0000 Subject: [PATCH 064/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7b09977e7..c7ef17d65 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -50,6 +50,7 @@ hide: ### Internal +* 👷 Add changes-requested handling in GitHub Action issue manager. PR [#10971](https://github.com/tiangolo/fastapi/pull/10971) by [@tiangolo](https://github.com/tiangolo). * 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex). * ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). From cf01195555ea0111a9540bccc1444b9d802587da Mon Sep 17 00:00:00 2001 From: Pedro Augusto de Paula Barbosa Date: Mon, 15 Jan 2024 12:17:34 -0300 Subject: [PATCH 065/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20`HTTPException`?= =?UTF-8?q?=20details=20in=20`docs/en/docs/tutorial/handling-errors.md`=20?= =?UTF-8?q?(#5418)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/handling-errors.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index a03029e81..7d521696d 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -234,9 +234,7 @@ You will receive a response telling you that the data is invalid containing the And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class. -The only difference, is that **FastAPI**'s `HTTPException` allows you to add headers to be included in the response. - -This is needed/used internally for OAuth 2.0 and some security utilities. +The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it. So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code. From 32ae9497233a9dc859a17f642c6b9bca0260f9ca Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:17:54 +0000 Subject: [PATCH 066/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c7ef17d65..771d286a1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Docs +* 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb). * ✏ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). From 15429a9c395df0378aa58fdee00c9b63a7a40358 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:33:28 +0900 Subject: [PATCH 067/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/body-fields.md`=20(#1923)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/body-fields.md | 48 ++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs/ja/docs/tutorial/body-fields.md diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md new file mode 100644 index 000000000..8f01e8216 --- /dev/null +++ b/docs/ja/docs/tutorial/body-fields.md @@ -0,0 +1,48 @@ +# ボディ - フィヌルド + +`Query`や`Path`、`Body`を䜿っお *path operation関数* のパラメヌタに远加のバリデヌションやメタデヌタを宣蚀するのず同じように、Pydanticの`Field`を䜿っおPydanticモデルの内郚でバリデヌションやメタデヌタを宣蚀するこずができたす。 + +## `Field`のむンポヌト + +たず、以䞋のようにむンポヌトしたす: + +```Python hl_lines="4" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +!!! warning "泚意" + `Field`は他の党おのもの`Query`、`Path`、`Body`などずは違い、`fastapi`からではなく、`pydantic`から盎接むンポヌトされおいるこずに泚意しおください。 + +## モデルの属性の宣蚀 + +以䞋のように`Field`をモデルの属性ずしお䜿甚するこずができたす: + +```Python hl_lines="11 12 13 14" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +`Field`は`Query`や`Path`、`Body`ず同じように動䜜し、党く同様のパラメヌタなどを持ちたす。 + +!!! note "技術詳现" + 実際には次に芋る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブゞェクトを䜜成したすが、それ自䜓はPydanticの`FieldInfo`クラスのサブクラスです。 + + たた、Pydanticの`Field`は`FieldInfo`のむンスタンスも返したす。 + + `Body`は`FieldInfo`のサブクラスのオブゞェクトを盎接返すこずもできたす。そしお、他にも`Body`クラスのサブクラスであるものがありたす。 + + `fastapi`から`Query`や`Path`などをむンポヌトする堎合、これらは実際には特殊なクラスを返す関数であるこずに泚意しおください。 + +!!! tip "豆知識" + 型、デフォルト倀、`Field`を持぀各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持぀、*path operation 関数の*パラメヌタず同じ構造になっおいるこずに泚目しおください。 + +## 远加情報の远加 + +远加情報は`Field`や`Query`、`Body`などで宣蚀するこずができたす。そしおそれは生成されたJSONスキヌマに含たれたす。 + +埌に䟋を甚いお宣蚀を孊ぶ際に、远加情報を句悪方法を孊べたす。 + +## たずめ + +Pydanticの`Field`を䜿甚しお、モデルの属性に远加のバリデヌションやメタデヌタを宣蚀するこずができたす。 + +远加のキヌワヌド匕数を䜿甚しお、远加のJSONスキヌマのメタデヌタを枡すこずもできたす。 From 467ab2a5756245cc53a8c0ec4fd467ffbef7d347 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:33:51 +0000 Subject: [PATCH 068/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 771d286a1..2d73401ef 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). * 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). From 88f19be7c38b1c904d453dff3f0f1f97ebdcaec7 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:34:57 +0900 Subject: [PATCH 069/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/body-nested-models.md`=20(#?= =?UTF-8?q?1930)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/body-nested-models.md | 244 ++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 docs/ja/docs/tutorial/body-nested-models.md diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..7f916c47a --- /dev/null +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -0,0 +1,244 @@ +# ボディ - ネストされたモデル + +**FastAPI** を䜿甚するず、深くネストされた任意のモデルを定矩、怜蚌、文曞化、䜿甚するこずができたすPydanticのおかげです。 + +## リストのフィヌルド + +属性をサブタむプずしお定矩するこずができたす。䟋えば、Pythonの`list`は以䞋のように定矩できたす: + +```Python hl_lines="12" +{!../../../docs_src/body_nested_models/tutorial001.py!} +``` + +これにより、各項目の型は宣蚀されおいたせんが、`tags`はある項目のリストになりたす。 + +## タむプパラメヌタを持぀リストのフィヌルド + +しかし、Pythonには型や「タむプパラメヌタ」を䜿っおリストを宣蚀する方法がありたす: + +### typingの`List`をむンポヌト + +たず、Pythonの暙準の`typing`モゞュヌルから`List`をむンポヌトしたす: + +```Python hl_lines="1" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +### タむプパラメヌタを持぀`List`の宣蚀 + +`list`や`dict`、`tuple`のようなタむプパラメヌタ内郚の型を持぀型を宣蚀するには: + +* `typing`モゞュヌルからそれらをむンストヌルしたす。 +* 角括匧`[`ず`]`を䜿っお「タむプパラメヌタ」ずしお内郚の型を枡したす: + +```Python +from typing import List + +my_list: List[str] +``` + +型宣蚀の暙準的なPythonの構文はこれだけです。 + +内郚の型を持぀モデルの属性にも同じ暙準の構文を䜿甚しおください。 + +そのため、以䞋の䟋では`tags`を具䜓的な「文字列のリスト」にするこずができたす: + +```Python hl_lines="14" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +## セット型 + +しかし、よく考えおみるず、タグは繰り返すべきではなく、おそらくナニヌクな文字列になるのではないかず気付いたずしたす。 + +そしお、Pythonにはナニヌクな項目のセットのための特別なデヌタ型`set`がありたす。 + +そのため、以䞋のように、`Set`をむンポヌトしお`str`の`set`ずしお`tags`を宣蚀するこずができたす: + +```Python hl_lines="1 14" +{!../../../docs_src/body_nested_models/tutorial003.py!} +``` + +これを䜿えば、デヌタが重耇しおいるリク゚ストを受けた堎合でも、ナニヌクな項目のセットに倉換されたす。 + +そしお、そのデヌタを出力するず、たずえ゜ヌスに重耇があったずしおも、固有の項目のセットずしお出力されたす。 + +たた、それに応じお泚釈を぀けたり、文曞化したりしたす。 + +## ネストされたモデル + +Pydanticモデルの各属性には型がありたす。 + +しかし、その型はそれ自䜓が別のPydanticモデルである可胜性がありたす。 + +そのため、特定の属性名、型、バリデヌションを指定しお、深くネストしたJSON`object`を宣蚀するこずができたす。 + +すべおは、任意のネストにされおいたす。 + +### サブモデルの定矩 + +䟋えば、`Image`モデルを定矩するこずができたす: + +```Python hl_lines="9 10 11" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +### サブモデルを型ずしお䜿甚 + +そしお、それを属性の型ずしお䜿甚するこずができたす: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +これは **FastAPI** が以䞋のようなボディを期埅するこずを意味したす: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +繰り返しになりたすが、**FastAPI** を䜿甚しお、その宣蚀を行うだけで以䞋のような恩恵を受けられたす: + +* ネストされたモデルでも察応可胜な゚ディタのサポヌト補完など +* デヌタ倉換 +* デヌタの怜蚌 +* 自動文曞化 + +## 特殊な型ずバリデヌション + +`str`や`int`、`float`のような通垞の単数型の他にも、`str`を継承したより耇雑な単数型を䜿うこずもできたす。 + +すべおのオプションをみるには、Pydanticの゚キゟチック な型のドキュメントを確認しおください。次の章でいく぀かの䟋をみるこずができたす。 + +䟋えば、`Image`モデルのように`url`フィヌルドがある堎合、`str`の代わりにPydanticの`HttpUrl`を指定するこずができたす: + +```Python hl_lines="4 10" +{!../../../docs_src/body_nested_models/tutorial005.py!} +``` + +文字列は有効なURLであるこずが確認され、そのようにJSONスキヌマ・OpenAPIで文曞化されたす。 + +## サブモデルのリストを持぀属性 + +Pydanticモデルを`list`や`set`などのサブタむプずしお䜿甚するこずもできたす: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial006.py!} +``` + +これは、次のようなJSONボディを期埅したす倉換、怜蚌、ドキュメントなど: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +!!! info "情報" + `images`キヌが画像オブゞェクトのリストを持぀ようになったこずに泚目しおください。 + +## 深くネストされたモデル + +深くネストされた任意のモデルを定矩するこずができたす: + +```Python hl_lines="9 14 20 23 27" +{!../../../docs_src/body_nested_models/tutorial007.py!} +``` + +!!! info "情報" + `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っおいるこずに泚目しおください。 + +## 玔粋なリストのボディ + +期埅するJSONボディのトップレベルの倀がJSON`array`Pythonの`list`であれば、Pydanticモデルず同じように、関数のパラメヌタで型を宣蚀するこずができたす: + +```Python +images: List[Image] +``` + +以䞋のように: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial008.py!} +``` + +## あらゆる堎所での゚ディタサポヌト + +゚ディタのサポヌトもどこでも受けるこずができたす。 + +以䞋のようにリストの䞭の項目でも: + + + +Pydanticモデルではなく、`dict`を盎接䜿甚しおいる堎合はこのような゚ディタのサポヌトは埗られたせん。 + +しかし、それらに぀いお心配する必芁はありたせん。入力された蟞曞は自動的に倉換され、出力も自動的にJSONに倉換されたす。 + +## 任意の`dict`のボディ + +たた、ある型のキヌず別の型の倀を持぀`dict`ずしおボディを宣蚀するこずもできたす。 + +有効なフィヌルド・属性名を事前に知る必芁がありたせんPydanticモデルの堎合のように。 + +これは、ただ知らないキヌを受け取りたいずきに䟿利だず思いたす。 + +--- + +他にも、`int`のように他の型のキヌを持ちたい堎合などに䟿利です。 + +それをここで芋おいきたしょう。 + +この堎合、`int`のキヌず`float`の倀を持぀ものであれば、どんな`dict`でも受け入れるこずができたす: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial009.py!} +``` + +!!! tip "豆知識" + JSONはキヌずしお`str`しかサポヌトしおいないこずに泚意しおください。 + + しかしPydanticには自動デヌタ倉換機胜がありたす。 + + これは、APIクラむアントがキヌずしお文字列しか送信できなくおも、それらの文字列に玔粋な敎数が含たれおいる限り、Pydanticが倉換しお怜蚌するこずを意味したす。 + + そしお、`weights`ずしお受け取る`dict`は、実際には`int`のキヌず`float`の倀を持぀こずになりたす。 + +## たずめ + +**FastAPI** を䜿甚するず、Pydanticモデルが提䟛する最倧限の柔軟性を持ちながら、コヌドをシンプルに短く、゚レガントに保぀こずができたす。 + +以䞋のような利点がありたす: + +* ゚ディタのサポヌトどこでも補完 +* デヌタ倉換別名構文解析・シリアラむズ +* デヌタの怜蚌 +* スキヌマ文曞 +* 自動文曞化 From 2619bbd7cde8251e955512f560dc632a96f72fe8 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:35:25 +0900 Subject: [PATCH 070/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20tranlsa?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/schema-extra-example.md`=20?= =?UTF-8?q?(#1931)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/schema-extra-example.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/ja/docs/tutorial/schema-extra-example.md diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..3102a4936 --- /dev/null +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -0,0 +1,58 @@ +# スキヌマの远加 - 䟋 + +JSON Schemaに远加する情報を定矩するこずができたす。 + +䞀般的なナヌスケヌスはこのドキュメントで瀺されおいるように`example`を远加するこずです。 + +JSON Schemaの远加情報を宣蚀する方法はいく぀かありたす。 + +## Pydanticの`schema_extra` + +Pydanticのドキュメント: スキヌマのカスタマむズで説明されおいるように、`Config`ず`schema_extra`を䜿っおPydanticモデルの䟋を宣蚀するこずができたす: + +```Python hl_lines="15 16 17 18 19 20 21 22 23" +{!../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +その远加情報はそのたた出力され、JSON Schemaに远加されたす。 + +## `Field`の远加匕数 + +埌述する`Field`、`Path`、`Query`、`Body`などでは、任意の匕数を関数に枡すこずでJSON Schemaの远加情報を宣蚀するこずもできたす: + +```Python hl_lines="4 10 11 12 13" +{!../../../docs_src/schema_extra_example/tutorial002.py!} +``` + +!!! warning "泚意" + これらの远加匕数が枡されおも、文曞化のためのバリデヌションは远加されず、泚釈だけが远加されるこずを芚えおおいおください。 + +## `Body`の远加匕数 + +远加情報を`Field`に枡すのず同じように、`Path`、`Query`、`Body`などでも同じこずができたす。 + +䟋えば、`Body`にボディリク゚ストの`example`を枡すこずができたす: + +```Python hl_lines="21 22 23 24 25 26" +{!../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +## ドキュメントのUIの䟋 + +䞊蚘のいずれの方法でも、`/docs`の䞭では以䞋のようになりたす: + + + +## 技術詳现 + +`example` ず `examples`に぀いお... + +JSON Schemaの最新バヌゞョンでは`examples`ずいうフィヌルドを定矩しおいたすが、OpenAPIは`examples`を持たない叀いバヌゞョンのJSON Schemaをベヌスにしおいたす。 + +そのため、OpenAPIでは同じ目的のために`example`を独自に定矩しおおり`examples`ではなく`example`ずしお、それがdocs UISwagger UIを䜿甚で䜿甚されおいたす。 + +぀たり、`example`はJSON Schemaの䞀郚ではありたせんが、OpenAPIの䞀郚であり、それがdocs UIで䜿甚されるこずになりたす。 + +## その他の情報 + +同じように、フロント゚ンドのナヌザヌむンタヌフェヌスなどをカスタマむズするために、各モデルのJSON Schemaに远加される独自の远加情報を远加するこずができたす。 From 79dbb11867f5217e090d3b498d91d9566be2fd95 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:35:41 +0000 Subject: [PATCH 071/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2d73401ef..0b820dce1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). * 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). From c238292b44340f55df15ea48eb324288b922e85a Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:36:32 +0900 Subject: [PATCH 072/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/extra-models.md`=20(#1941)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/extra-models.md | 195 ++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 docs/ja/docs/tutorial/extra-models.md diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md new file mode 100644 index 000000000..aa2e5ffdc --- /dev/null +++ b/docs/ja/docs/tutorial/extra-models.md @@ -0,0 +1,195 @@ +# モデル - より詳しく + +先ほどの䟋に続き、耇数の関連モデルを持぀こずが䞀般的です。 + +これはナヌザヌモデルの堎合は特にそうです。なぜなら: + +* **入力モデル** にはパスワヌドが必芁です。 +* **出力モデル**はパスワヌドをも぀べきではありたせん。 +* **デヌタベヌスモデル**はおそらくハッシュ化されたパスワヌドが必芁になるでしょう。 + +!!! danger "危険" + ナヌザヌの平文のパスワヌドは絶察に保存しないでください。垞に認蚌に利甚可胜な「安党なハッシュ」を保存しおください。 + + 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワヌドハッシュ」ずは䜕かを孊ぶこずができたす。 + +## 耇数のモデル + +ここでは、パスワヌドフィヌルドをも぀モデルがどのように芋えるのか、たた、どこで䜿われるのか、倧たかなむメヌゞを玹介したす: + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!../../../docs_src/extra_models/tutorial001.py!} +``` + +### `**user_in.dict()`に぀いお + +#### Pydanticの`.dict()` + +`user_in`は`UserIn`クラスのPydanticモデルです。 + +Pydanticモデルには、モデルのデヌタを含む`dict`を返す`.dict()`メ゜ッドがありたす。 + +そこで、以䞋のようなPydanticオブゞェクト`user_in`を䜜成するず: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +そしお呌び出すず: + +```Python +user_dict = user_in.dict() +``` + +これで倉数`user_dict`のデヌタを持぀`dict`ができたした。これはPydanticモデルのオブゞェクトの代わりに`dict`です。 + +そしお呌び出すず: + +```Python +print(user_dict) +``` + +以䞋のようなPythonの`dict`を埗るこずができたす: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### `dict`の展開 + +`user_dict`のような`dict`を受け取り、それを`**user_dict`を持぀関数たたはクラスに枡すず、Pythonはそれを「展開」したす。これは`user_dict`のキヌず倀を盎接キヌ・バリュヌの匕数ずしお枡したす。 + +そこで䞊述の`user_dict`の続きを以䞋のように曞くず: + +```Python +UserInDB(**user_dict) +``` + +以䞋ず同等の結果になりたす: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +もっず正確に蚀えば、`user_dict`を将来的にどんな内容であっおも盎接䜿甚するこずになりたす: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### 別のモデルから぀くるPydanticモデル + +䞊述の䟋では`user_in.dict()`から`user_dict`をこのコヌドのように取埗しおいたすが: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +これは以䞋ず同等です: + +```Python +UserInDB(**user_in.dict()) +``` + +...なぜなら`user_in.dict()`は`dict`であり、`**`を付䞎しお`UserInDB`を枡しおPythonに「展開」させおいるからです。 + +そこで、別のPydanticモデルのデヌタからPydanticモデルを取埗したす。 + +#### `dict`の展開ず远加匕数 + +そしお、远加のキヌワヌド匕数`hashed_password=hashed_password`を以䞋のように远加するず: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +...以䞋のようになりたす: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +!!! warning "泚意" + サポヌトしおいる远加機胜は、デヌタの可胜な流れをデモするだけであり、もちろん本圓のセキュリティを提䟛しおいるわけではありたせん。 + +## 重耇の削枛 + +コヌドの重耇を枛らすこずは、**FastAPI**の䞭栞的なアむデアの぀です。 + +コヌドの重耇が増えるず、バグやセキュリティの問題、コヌドの非同期化問題ある堎所では曎新しおも他の堎所では曎新されない堎合などが発生する可胜性が高くなりたす。 + +そしお、これらのモデルは党おのデヌタを共有し、属性名や型を重耇させおいたす。 + +もっず良い方法がありたす。 + +他のモデルのベヌスずなる`UserBase`モデルを宣蚀するこずができたす。そしお、そのモデルの属性型宣蚀、怜蚌などを継承するサブクラスを䜜るこずができたす。 + +デヌタの倉換、怜蚌、文曞化などはすべお通垞通りに動䜜したす。 + +このようにしお、モデル間の違いだけを宣蚀するこずができたす: + +```Python hl_lines="9 15 16 19 20 23 24" +{!../../../docs_src/extra_models/tutorial002.py!} +``` + +## `Union`たたは`anyOf` + +レスポンスを぀の型の`Union`ずしお宣蚀するこずができたす。 + +OpenAPIでは`anyOf`で定矩されたす。 + +そのためには、暙準的なPythonの型ヒント`typing.Union`を䜿甚したす: + +```Python hl_lines="1 14 15 18 19 20 33" +{!../../../docs_src/extra_models/tutorial003.py!} +``` + +## モデルのリスト + +同じように、オブゞェクトのリストのレスポンスを宣蚀するこずができたす。 + +そのためには、暙準のPythonの`typing.List`を䜿甚する: + +```Python hl_lines="1 20" +{!../../../docs_src/extra_models/tutorial004.py!} +``` + +## 任意の`dict`を持぀レスポンス + +たた、Pydanticモデルを䜿甚せずに、キヌず倀の型だけを定矩した任意の`dict`を䜿っおレスポンスを宣蚀するこずもできたす。 + +これは、有効なフィヌルド・属性名Pydanticモデルに必芁なものを事前に知らない堎合に䟿利です。 + +この堎合、`typing.Dict`を䜿甚するこずができたす: + +```Python hl_lines="1 8" +{!../../../docs_src/extra_models/tutorial005.py!} +``` + +## たずめ + +耇数のPydanticモデルを䜿甚し、ケヌスごずに自由に継承したす。 + +゚ンティティが異なる「状態」を持たなければならない堎合は、゚ンティティごずに単䞀のデヌタモデルを持぀必芁はありたせん。`password` や `password_hash` やパスワヌドなしなどのいく぀かの「状態」をも぀ナヌザヌ「゚ンティティ」の堎合の様にすれば良いです。 From f386011d64e68c63f397834eda1c937b660f0d75 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:38:18 +0000 Subject: [PATCH 073/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0b820dce1..bca167cd1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). From 17511f776891d6bbdaac2a6ba7157b24259210a4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:38:58 +0000 Subject: [PATCH 074/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bca167cd1..33caa2ac7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). From 88225ae231731ff266f964f3bf5818a4397db223 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:42:08 +0900 Subject: [PATCH 075/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/response-status-code.md`=20?= =?UTF-8?q?(#1942)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/response-status-code.md | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 docs/ja/docs/tutorial/response-status-code.md diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..ead2addda --- /dev/null +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -0,0 +1,89 @@ +# レスポンスステヌタスコヌド + +レスポンスモデルを指定するのず同じ方法で、レスポンスに䜿甚されるHTTPステヌタスコヌドを以䞋の*path operations*のいずれかの`status_code`パラメヌタで宣蚀するこずもできたす。 + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +!!! note "備考" + `status_code`は「デコレヌタ」メ゜ッド`get`、`post`などのパラメヌタであるこずに泚意しおください。すべおのパラメヌタやボディのように、*path operation関数*のものではありたせん。 + +`status_code`パラメヌタはHTTPステヌタスコヌドを含む数倀を受け取りたす。 + +!!! info "情報" + `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取るこずもできたす。 + +これは: + +* レスポンスでステヌタスコヌドを返したす。 +* OpenAPIスキヌマおよびナヌザヌむンタヌフェヌスに以䞋のように文曞化したす: + + + +!!! note "備考" + いく぀かのレスポンスコヌド次のセクションを参照は、レスポンスにボディがないこずを瀺しおいたす。 + + FastAPIはこれを知っおいお、レスポンスボディがないずいうOpenAPIドキュメントを生成したす。 + +## HTTPステヌタスコヌドに぀いお + +!!! note "備考" + すでにHTTPステヌタスコヌドが䜕であるかを知っおいる堎合は、次のセクションにスキップしおください。 + +HTTPでは、レスポンスの䞀郚ずしお桁の数字のステヌタスコヌドを送信したす。 + +これらのステヌタスコヌドは、それらを認識するために関連付けられた名前を持っおいたすが、重芁な郚分は番号です。 + +぀たり: + +* `100`以䞊は「情報」のためのものです。。盎接䜿うこずはほずんどありたせん。これらのステヌタスコヌドを持぀レスポンスはボディを持぀こずができたせん。 +* **`200`** 以䞊は「成功」のレスポンスのためのものです。これらは最も利甚するであろうものです。 + * `200`はデフォルトのステヌタスコヌドで、すべおが「OK」であったこずを意味したす。 + * 別の䟋ずしおは、`201`Createdがありたす。これはデヌタベヌスに新しいレコヌドを䜜成した埌によく䜿甚されたす。 + * 特殊なケヌスずしお、`204`No Contentがありたす。このレスポンスはクラむアントに返すコンテンツがない堎合に䜿甚されたす。そしおこのレスポンスはボディを持぀こずはできたせん。 +* **`300`** 以䞊は「リダむレクト」のためのものです。これらのステヌタスコヌドを持぀レスポンスは`304`Not Modifiedを陀き、ボディを持぀こずも持たないこずもできたす。 +* **`400`** 以䞊は「クラむアント゚ラヌ」のレスポンスのためのものです。これらは、おそらく最も倚甚するであろう番目のタむプです。 + * 䟋えば、`404`は「Not Found」レスポンスです。 + * クラむアントからの䞀般的な゚ラヌに぀いおは、`400`を䜿甚するこずができたす。 +* `500`以䞊はサヌバヌ゚ラヌのためのものです。これらを盎接䜿うこずはほずんどありたせん。アプリケヌションコヌドやサヌバヌのどこかで䜕か問題が発生した堎合、これらのステヌタスコヌドのいずれかが自動的に返されたす。 + +!!! tip "豆知識" + それぞれのステヌタスコヌドずどのコヌドが䜕のためのコヌドなのかに぀いお詳现はMDN HTTP レスポンスステヌタスコヌドに぀いおのドキュメントを参照しおください。 + +## 名前を芚えるための近道 + +先ほどの䟋をもう䞀床芋おみたしょう: + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +`201`は「䜜成完了」のためのステヌタスコヌドです。 + +しかし、それぞれのコヌドの意味を暗蚘する必芁はありたせん。 + +`fastapi.status`の䟿利な倉数を利甚するこずができたす。 + +```Python hl_lines="1 6" +{!../../../docs_src/response_status_code/tutorial002.py!} +``` + +それらは䟿利です。それらは同じ番号を保持しおおり、その方法でぱディタの自動補完を䜿甚しおそれらを芋぀けるこずができたす。 + + + +!!! note "技術詳现" + たた、`from starlette import status`を䜿うこずもできたす。 + + **FastAPI** は、`開発者の利䟿性を考慮しお、fastapi.status`ず同じ`starlette.status`を提䟛しおいたす。しかし、これはStarletteから盎接提䟛されおいたす。 + +## デフォルトの倉曎 + +埌に、[高床なナヌザヌガむド](../advanced/response-change-status-code.md){.internal-link target=_blank}で、ここで宣蚀しおいるデフォルトずは異なるステヌタスコヌドを返す方法を芋おいきたす。 From 217bff20cabbd47dfef43394bae72f807a44e9a7 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:43:45 +0900 Subject: [PATCH 076/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/handling-errors.md`=20(#195?= =?UTF-8?q?3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/handling-errors.md | 265 +++++++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 docs/ja/docs/tutorial/handling-errors.md diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..ec36e9880 --- /dev/null +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -0,0 +1,265 @@ +# ゚ラヌハンドリング + +APIを䜿甚しおいるクラむアントに゚ラヌを通知する必芁がある状況はたくさんありたす。 + +このクラむアントは、フロント゚ンドを持぀ブラりザ、誰かのコヌド、IoTデバむスなどが考えられたす。 + +クラむアントに以䞋のようなこずを䌝える必芁があるかもしれたせん: + +* クラむアントにはその操䜜のための十分な暩限がありたせん。 +* クラむアントはそのリ゜ヌスにアクセスできたせん。 +* クラむアントがアクセスしようずしおいた項目が存圚したせん。 +* など + +これらの堎合、通垞は **400**400から499の範囲内の **HTTPステヌタスコヌド** を返すこずになりたす。 + +これは200のHTTPステヌタスコヌド200から299に䌌おいたす。これらの「200」ステヌタスコヌドは、䜕らかの圢でリク゚スト「成功」であったこずを意味したす。 + +400の範囲にあるステヌタスコヌドは、クラむアントからの゚ラヌがあったこずを意味したす。 + +**"404 Not Found"** の゚ラヌおよびゞョヌクを芚えおいたすか + +## `HTTPException`の䜿甚 + +HTTPレスポンスを゚ラヌでクラむアントに返すには、`HTTPException`を䜿甚したす。 + +### `HTTPException`のむンポヌト + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### コヌド内での`HTTPException`の発生 + +`HTTPException`は通垞のPythonの䟋倖であり、APIに関連するデヌタを远加したものです。 + +Pythonの䟋倖なので、`return`ではなく、`raise`です。 + +これはたた、*path operation関数*の内郚で呌び出しおいるナヌティリティ関数の内郚から`HTTPException`を発生させた堎合、*path operation関数*の残りのコヌドは実行されず、そのリク゚ストを盎ちに終了させ、`HTTPException`からのHTTP゚ラヌをクラむアントに送信するこずを意味したす。 + +倀を返す`return`よりも䟋倖を発生させるこずの利点は、「䟝存関係ずセキュリティ」のセクションでより明確になりたす。 + +この䟋では、クラむアントが存圚しないIDでアむテムを芁求した堎合、`404`のステヌタスコヌドを持぀䟋倖を発生させたす: + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### レスポンス結果 + +クラむアントが`http://example.com/items/foo``item_id` `"foo"`をリク゚ストするず、HTTPステヌタスコヌドが200で、以䞋のJSONレスポンスが返されたす: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +しかし、クラむアントが`http://example.com/items/bar`存圚しない`item_id` `"bar"`をリク゚ストした堎合、HTTPステヌタスコヌド404"not found"゚ラヌず以䞋のJSONレスポンスが返されたす: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! tip "豆知識" + `HTTPException`を発生させる際には、`str`だけでなく、JSONに倉換できる任意の倀を`detail`パラメヌタずしお枡すこずができたす。 + + `dist`や`list`などを枡すこずができたす。 + + これらは **FastAPI** によっお自動的に凊理され、JSONに倉換されたす。 + +## カスタムヘッダヌの远加 + +䟋えば、いく぀かのタむプのセキュリティのために、HTTP゚ラヌにカスタムヘッダを远加できるず䟿利な状況がいく぀かありたす。 + +おそらくコヌドの䞭で盎接䜿甚する必芁はないでしょう。 + +しかし、高床なシナリオのために必芁な堎合には、カスタムヘッダヌを远加するこずができたす: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## カスタム䟋倖ハンドラのむンストヌル + +カスタム䟋倖ハンドラはStarletteず同じ䟋倖ナヌティリティを䜿甚しお远加するこずができたす。 + +あなたたたは䜿甚しおいるラむブラリが`raise`するかもしれないカスタム䟋倖`UnicornException`があるずしたしょう。 + +そしお、この䟋倖をFastAPIでグロヌバルに凊理したいず思いたす。 + +カスタム䟋倖ハンドラを`@app.exception_handler()`で远加するこずができたす: + +```Python hl_lines="5 6 7 13 14 15 16 17 18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +ここで、`/unicorns/yolo`をリク゚ストするず、*path operation*は`UnicornException`を`raise`したす。 + +しかし、これは`unicorn_exception_handler`で凊理されたす。 + +そのため、HTTPステヌタスコヌドが`418`で、JSONの内容が以䞋のような明確な゚ラヌを受け取るこずになりたす: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "技術詳现" + たた、`from starlette.requests import Request`ず`from starlette.responses import JSONResponse`を䜿甚するこずもできたす。 + + **FastAPI** は開発者の利䟿性を考慮しお、`fastapi.responses`ず同じ`starlette.responses`を提䟛しおいたす。しかし、利甚可胜なレスポンスのほずんどはStarletteから盎接提䟛されたす。これは`Request`ず同じです。 + +## デフォルトの䟋倖ハンドラのオヌバヌラむド + +**FastAPI** にはいく぀かのデフォルトの䟋倖ハンドラがありたす。 + +これらのハンドラは、`HTTPException`を`raise`させた堎合や、リク゚ストに無効なデヌタが含たれおいる堎合にデフォルトのJSONレスポンスを返す圹割を担っおいたす。 + +これらの䟋倖ハンドラを独自のものでオヌバヌラむドするこずができたす。 + +### リク゚スト怜蚌の䟋倖のオヌバヌラむド + +リク゚ストに無効なデヌタが含たれおいる堎合、**FastAPI** は内郚的に`RequestValidationError`を発生させたす。 + +たた、そのためのデフォルトの䟋倖ハンドラも含たれおいたす。 + +これをオヌバヌラむドするには`RequestValidationError`をむンポヌトしお`@app.exception_handler(RequestValidationError)`ず䞀緒に䜿甚しお䟋倖ハンドラをデコレヌトしたす。 + +この䟋倖ハンドラは`Requset`ず䟋倖を受け取りたす。 + +```Python hl_lines="2 14 15 16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +これで、`/items/foo`にアクセスするず、デフォルトのJSON゚ラヌの代わりに以䞋が返されたす: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +以䞋のようなテキスト版を取埗したす: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError`ず`ValidationError` + +!!! warning "泚意" + これらは今のあなたにずっお重芁でない堎合は省略しおも良い技術的な詳现です。 + +`RequestValidationError`はPydanticの`ValidationError`のサブクラスです。 + +**FastAPI** は`response_model`でPydanticモデルを䜿甚しおいお、デヌタに゚ラヌがあった堎合、ログに゚ラヌが衚瀺されるようにこれを䜿甚しおいたす。 + +しかし、クラむアントやナヌザヌはそれを芋るこずはありたせん。その代わりに、クラむアントはHTTPステヌタスコヌド`500`の「Internal Server Error」を受け取りたす。 + +*レスポンス*やコヌドのどこかクラむアントの*リク゚スト*ではなくにPydanticの`ValidationError`がある堎合、それは実際にはコヌドのバグなのでこのようにすべきです。 + +たた、あなたがそれを修正しおいる間は、セキュリティの脆匱性が露呈する堎合があるため、クラむアントやナヌザヌが゚ラヌに関する内郚情報にアクセスできないようにしおください。 + +### ゚ラヌハンドラ`HTTPException`のオヌバヌラむド + +同様に、`HTTPException`ハンドラをオヌバヌラむドするこずもできたす。 + +䟋えば、これらの゚ラヌに察しおは、JSONではなくプレヌンテキストを返すようにするこずができたす: + +```Python hl_lines="3 4 9 10 11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "技術詳现" + たた、`from starlette.responses import PlainTextResponse`を䜿甚するこずもできたす。 + + **FastAPI** は開発者の利䟿性を考慮しお、`fastapi.responses`ず同じ`starlette.responses`を提䟛しおいたす。しかし、利甚可胜なレスポンスのほずんどはStarletteから盎接提䟛されたす。 + +### `RequestValidationError`のボディの䜿甚 + +`RequestValidationError`には無効なデヌタを含む`body`が含たれおいたす。 + +アプリ開発䞭に本䜓のログを取っおデバッグしたり、ナヌザヌに返したりなどに䜿甚するこずができたす。 + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial005.py!} +``` + +ここで、以䞋のような無効な項目を送信しおみおください: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +受信したボディを含むデヌタが無効であるこずを瀺すレスポンスが衚瀺されたす: + +```JSON hl_lines="12 13 14 15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIの`HTTPException`ずStarletteの`HTTPException` + +**FastAPI**は独自の`HTTPException`を持っおいたす。 + +たた、 **FastAPI**の゚ラヌクラス`HTTPException`はStarletteの゚ラヌクラス`HTTPException`を継承しおいたす。 + +唯䞀の違いは、**FastAPI** の`HTTPException`はレスポンスに含たれるヘッダを远加できるこずです。 + +これはOAuth 2.0ずいく぀かのセキュリティナヌティリティのために内郚的に必芁ずされ、䜿甚されおいたす。 + +そのため、コヌド内では通垞通り **FastAPI** の`HTTPException`を発生させ続けるこずができたす。 + +しかし、䟋倖ハンドラを登録する際には、Starletteの`HTTPException`を登録しおおく必芁がありたす。 + +これにより、Starletteの内郚コヌドやStarletteの拡匵機胜やプラグむンの䞀郚が`HTTPException`を発生させた堎合、ハンドラがそれをキャッチしお凊理するこずができるようになりたす。 + +以䞋の䟋では、同じコヌド内で䞡方の`HTTPException`を䜿甚できるようにするために、Starletteの䟋倖の名前を`StarletteHTTPException`に倉曎しおいたす: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI** の䟋倖ハンドラの再利甚 + +たた、䜕らかの方法で䟋倖を䜿甚するこずもできたすが、**FastAPI** から同じデフォルトの䟋倖ハンドラを䜿甚するこずもできたす。 + +デフォルトの䟋倖ハンドラを`fastapi.exception_handlers`からむンポヌトしお再利甚するこずができたす: + +```Python hl_lines="2 3 4 5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +この䟋では、非垞に衚珟力のあるメッセヌゞで゚ラヌを`print`しおいたす。 + +しかし、䟋倖を䜿甚しお、デフォルトの䟋倖ハンドラを再利甚するこずができるずいうこずが理解できたす。 From efac3a293fecc06a4cbb933f829877cc914a95f1 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:45:27 +0900 Subject: [PATCH 077/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/python-types.md`=20(#1899)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/python-types.md | 315 +++++++++++++++++++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 docs/ja/docs/python-types.md diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md new file mode 100644 index 000000000..bbfef2adf --- /dev/null +++ b/docs/ja/docs/python-types.md @@ -0,0 +1,315 @@ +# Pythonの型の玹介 + +**Python 3.6以降** では「型ヒント」オプションがサポヌトされおいたす。 + +これらの **"型ヒント"** は倉数の型を宣蚀するこずができる新しい構文です。Python 3.6以降 + +倉数に型を宣蚀するこずで゚ディタヌやツヌルがより良いサポヌトを提䟛するこずができたす。 + +ここではPythonの型ヒントに぀いおの **クむックチュヌトリアル/リフレッシュ** で、**FastAPI**でそれらを䜿甚するために必芁な最䜎限のこずだけをカバヌしおいたす。...実際には本圓に少ないです。 + +**FastAPI** はすべおこれらの型ヒントに基づいおおり、倚くの匷みず利点を䞎えおくれたす。 + +しかしたずえたったく **FastAPI** を䜿甚しない堎合でも、それらに぀いお少し孊ぶこずで利点を埗るこずができるでしょう。 + +!!! note "備考" + もしあなたがPythonの専門家で、すでに型ヒントに぀いおすべお知っおいるのであれば、次の章たで読み飛ばしおください。 + +## 動機 + +簡単な䟋から始めおみたしょう: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +このプログラムを実行するず以䞋が出力されたす: + +``` +John Doe +``` + +この関数は以䞋のようなこずを行いたす: + +* `first_name`ず`last_name`を取埗したす。 +* `title()`を甚いお、それぞれの最初の文字を倧文字に倉換したす。 +* 真ん䞭にスペヌスを入れお連結したす。 + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### 線集 + +これはずおも簡単なプログラムです。 + +しかし、今、あなたがそれを䞀から曞いおいたず想像しおみおください。 + +パラメヌタの準備ができおいたら、そのずき、関数の定矩を始めおいたこずでしょう... + +しかし、そうするず「最初の文字を倧文字に倉換するあのメ゜ッド」を呌び出す必芁がありたす。 + +それは`upper`でしたか`uppercase`でしたかそれずも`first_uppercase`たたは`capitalize` + +そしお、叀くからプログラマヌの友人である゚ディタで自動補完を詊しおみたす。 + +関数の最初のパラメヌタ`first_name`を入力し、ドット(`.`)を入力しおから、`Ctrl+Space`を抌すず補完が実行されたす。 + +しかし、悲しいこずに、これはなんの圹にも立ちたせん: + + + +### 型の远加 + +先ほどのコヌドから䞀行倉曎しおみたしょう。 + +以䞋の関数のパラメヌタ郚分を: + +```Python + first_name, last_name +``` + +以䞋ぞ倉曎したす: + +```Python + first_name: str, last_name: str +``` + +これだけです。 + +それが「型ヒント」です: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +これは、以䞋のようにデフォルト倀を宣蚀するのず同じではありたせん: + +```Python + first_name="john", last_name="doe" +``` + +それずは別物です。 + +むコヌル`=`ではなく、コロン`:`を䜿甚したす。 + +そしお、通垞、型ヒントを远加しおも、それらがない状態ず起こるこずは䜕も倉わりたせん。 + +しかし今、あなたが再びその関数を䜜成しおいる最䞭に、型ヒントを䜿っおいるず想像しおみお䞋さい。 + +同じタむミングで`Ctrl+Space`で自動補完を実行するず、以䞋のようになりたす: + + + +これであれば、あなたは「ベルを鳎らす」䞀぀を芋぀けるたで、オプションを芋お、スクロヌルするこずができたす: + + + +## より匷い動機 + +この関数を芋おください。すでに型ヒントを持っおいたす: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +゚ディタは倉数の型を知っおいるので、補完だけでなく、゚ラヌチェックをするこずもできたす。 + + + +これで`age`を`str(age)`で文字列に倉換しお修正する必芁があるこずがわかりたす: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## 型の宣蚀 + +関数のパラメヌタずしお、型ヒントを宣蚀しおいる䞻な堎所を確認したした。 + +これは **FastAPI** で䜿甚する䞻な堎所でもありたす。 + +### 単玔な型 + +`str`だけでなく、Pythonの暙準的な型すべおを宣蚀するこずができたす。 + +䟋えば、以䞋を䜿甚可胜です: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### 型パラメヌタを持぀ゞェネリック型 + +デヌタ構造の䞭には、`dict`、`list`、`set`、そしお`tuple`のように他の倀を含むこずができるものがありたす。たた内郚の倀も独自の型を持぀こずができたす。 + +これらの型や内郚の型を宣蚀するには、Pythonの暙準モゞュヌル`typing`を䜿甚したす。 + +これらの型ヒントをサポヌトするために特別に存圚しおいたす。 + +#### `List` + +䟋えば、`str`の`list`の倉数を定矩しおみたしょう。 + +`typing`から`List`をむンポヌトしたす倧文字の`L`を含む: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +同じようにコロン`:`の構文で倉数を宣蚀したす。 + +型ずしお、`List`を入力したす。 + +リストはいく぀かの内郚の型を含む型なので、それらを角括匧で囲んでいたす。 + +```Python hl_lines="4" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +!!! tip "豆知識" + 角括匧内の内郚の型は「型パラメヌタ」ず呌ばれおいたす。 + + この堎合、`str`は`List`に枡される型パラメヌタです。 + +぀たり: 倉数`items`は`list`であり、このリストの各項目は`str`です。 + +そうするこずで、゚ディタはリストの項目を凊理しおいる間にもサポヌトを提䟛できたす。 + + + +タむプがなければ、それはほが䞍可胜です。 + +倉数`item`はリスト`items`の芁玠の䞀぀であるこずに泚意しおください。 + +それでも、゚ディタはそれが`str`であるこずを知っおいお、そのためのサポヌトを提䟛しおいたす。 + +#### `Tuple` ず `Set` + +`tuple`ず`set`の宣蚀も同様です: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial007.py!} +``` + +぀たり: + +* 倉数`items_t`は`int`、`int`、`str`の3぀の項目を持぀`tuple`です + +* 倉数`items_s`はそれぞれの項目が`bytes`型である`set`です。 + +#### `Dict` + +`dict`を宣蚀するためには、カンマ区切りで2぀の型パラメヌタを枡したす。 + +最初の型パラメヌタは`dict`のキヌです。 + +番目の型パラメヌタは`dict`の倀です。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial008.py!} +``` + +぀たり: + +* 倉数`prices`は`dict`であり: + * この`dict`のキヌは`str`型です。぀たり、各項目の名前 + * この`dict`の倀は`float`型です。぀たり、各項目の䟡栌 + +#### `Optional` + +たた、`Optional`を䜿甚しお、倉数が`str`のような型を持぀こずを宣蚀するこずもできたすが、それは「オプション」であり、`None`にするこずもできたす。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +ただの`str`の代わりに`Optional[str]`を䜿甚するこずで、゚ディタは倀が垞に`str`であるず仮定しおいる堎合に実際には`None`である可胜性がある゚ラヌを怜出するのに圹立ちたす。 + +#### ゞェネリック型 + +以䞋のように角括匧で型パラメヌタを取る型を: + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Optional` +* ...など + +**ゞェネリック型** たたは **ゞェネリクス** ず呌びたす。 + +### 型ずしおのクラス + +倉数の型ずしおクラスを宣蚀するこずもできたす。 + +䟋えば、`Person`クラスずいう名前のクラスがあるずしたしょう: + +```Python hl_lines="1 2 3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +倉数の型を`Person`ずしお宣蚀するこずができたす: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +そしお、再び、すべおの゚ディタのサポヌトを埗るこずができたす: + + + +## Pydanticのモデル + +Pydantic はデヌタ怜蚌を行うためのPythonラむブラリです。 + +デヌタの「圢」を属性付きのクラスずしお宣蚀したす。 + +そしお、それぞれの属性は型を持ちたす。 + +さらに、いく぀かの倀を持぀クラスのむンスタンスを䜜成するず、その倀を怜蚌し、適切な型に倉換しおもしそうであれば党おのデヌタを持぀オブゞェクトを提䟛しおくれたす。 + +たた、その結果のオブゞェクトですべおの゚ディタのサポヌトを受けるこずができたす。 + +Pydanticの公匏ドキュメントから匕甚: + +```Python +{!../../../docs_src/python_types/tutorial011.py!} +``` + +!!! info "情報" + Pydanticに぀いおより孊びたい方はドキュメントを参照しおください. + +**FastAPI** はすべおPydanticをベヌスにしおいたす。 + +すべおのこずは[チュヌトリアル - ナヌザヌガむド](tutorial/index.md){.internal-link target=_blank}で実際に芋るこずができたす。 + +## **FastAPI**での型ヒント + +**FastAPI** はこれらの型ヒントを利甚しおいく぀かのこずを行いたす。 + +**FastAPI** では型ヒントを䜿っお型パラメヌタを宣蚀するず以䞋のものが埗られたす: + +* **゚ディタサポヌト**. +* **型チェック**. + +...そしお **FastAPI** は同じように宣蚀をするず、以䞋のこずを行いたす: + +* **芁件の定矩**: リク゚ストパスパラメヌタ、ク゚リパラメヌタ、ヘッダヌ、ボディ、䟝存関係などから芁件を定矩したす。 +* **デヌタの倉換**: リク゚ストのデヌタを必芁な型に倉換したす。 +* **デヌタの怜蚌**: リク゚ストごずに: + * デヌタが無効な堎合にクラむアントに返される **自動゚ラヌ** を生成したす。 +* **ドキュメント** OpenAPIを䜿甚したAPI: + * 自動的に察話型ドキュメントのナヌザヌむンタヌフェむスで䜿甚されたす。 + +すべおが抜象的に聞こえるかもしれたせん。心配しないでください。 この党おの動䜜は [チュヌトリアル - ナヌザヌガむド](tutorial/index.md){.internal-link target=_blank}で芋るこずができたす。 + +重芁なのは、Pythonの暙準的な型を䜿うこずで、クラスやデコレヌタなどを远加するのではなく぀の堎所で **FastAPI** が倚くの䜜業を代わりにやっおくれおいるずいうこずです。 + +!!! info "情報" + すでにすべおのチュヌトリアルを終えお、型に぀いおの詳现を芋るためにこのペヌゞに戻っおきた堎合は、`mypy`のチヌトシヌトを参照しおください From b21599bab0a7ab38102c9e42364d1e224ad07fe3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:46:12 +0000 Subject: [PATCH 078/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 33caa2ac7..997d8b5aa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). From b73de83ca2edb35122624c4ec6db4120cf5e4496 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:46:32 +0900 Subject: [PATCH 079/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/path-params-numeric-validat?= =?UTF-8?q?ions.md`=20(#1902)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../path-params-numeric-validations.md | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 docs/ja/docs/tutorial/path-params-numeric-validations.md diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..551aeabb3 --- /dev/null +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,122 @@ +# パスパラメヌタず数倀の怜蚌 + +ク゚リパラメヌタに察しお`Query`でより倚くのバリデヌションずメタデヌタを宣蚀できるのず同じように、パスパラメヌタに察しおも`Path`で同じ皮類のバリデヌションずメタデヌタを宣蚀するこずができたす。 + +## Pathのむンポヌト + +たず初めに、`fastapi`から`Path`をむンポヌトしたす: + +```Python hl_lines="1" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +## メタデヌタの宣蚀 + +パラメヌタは`Query`ず同じものを宣蚀するこずができたす。 + +䟋えば、パスパラメヌタ`item_id`に察しお`title`のメタデヌタを宣蚀するには以䞋のようにしたす: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +!!! note "備考" + パスの䞀郚でなければならないので、パスパラメヌタは垞に必須です。 + + そのため、`...`を䜿甚しお必須ず瀺す必芁がありたす。 + + それでも、`None`で宣蚀しおも、デフォルト倀を蚭定しおも、䜕の圱響もなく、垞に必芁ずされおいるこずに倉わりはありたせん。 + +## 必芁に応じおパラメヌタを䞊び替える + +ク゚リパラメヌタ`q`を必須の`str`ずしお宣蚀したいずしたしょう。 + +たた、このパラメヌタには䜕も宣蚀する必芁がないので、`Query`を䜿う必芁はありたせん。 + +しかし、パスパラメヌタ`item_id`のために`Path`を䜿甚する必芁がありたす。 + +Pythonは「デフォルト」を持たない倀の前に「デフォルト」を持぀倀を眮くこずができたせん。 + +しかし、それらを䞊び替えるこずができ、デフォルト倀を持たない倀ク゚リパラメヌタ`q`を最初に持぀こずができたす。 + +**FastAPI**では関係ありたせん。パラメヌタは名前、型、デフォルトの宣蚀`Query`、`Path`などで怜出され、順番は気にしたせん。 + +そのため、以䞋のように関数を宣蚀するこずができたす: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` + +## 必芁に応じおパラメヌタを䞊び替えるトリック + +ク゚リパラメヌタ`q`を`Query`やデフォルト倀なしで宣蚀し、パスパラメヌタ`item_id`を`Path`を甚いお宣蚀し、それらを別の順番に䞊びたい堎合、Pythonには少し特殊な構文が甚意されおいたす。 + +関数の最初のパラメヌタずしお`*`を枡したす。 + +Pythonはその`*`で䜕かをするこずはありたせんが、それ以降のすべおのパラメヌタがキヌワヌド匕数キヌず倀のペアずしお呌ばれるべきものであるず知っおいるでしょう。それはkwargsずしおも知られおいたす。たずえデフォルト倀がなくおも。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +``` + +## 数倀の怜蚌: 以䞊 + +`Query`ず`Path`、そしお埌述する他のものを甚いお、文字列の制玄を宣蚀するこずができたすが、数倀の制玄も同様に宣蚀できたす。 + +ここで、`ge=1`の堎合、`item_id`は`1`「より倧きい`g`か、同じ`e`」敎数でなれけばなりたせん。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +## 数倀の怜蚌: より倧きいず小なりむコヌル + +以䞋も同様です: + +* `gt`: より倧きい`g`reater `t`han +* `le`: 小なりむコヌル`l`ess than or `e`qual + +```Python hl_lines="9" +{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +## 数倀の怜蚌: 浮動小数点、 倧なり小なり + +数倀のバリデヌションは`float`の倀に察しおも有効です。 + +ここで重芁になっおくるのはgtだけでなくgeも宣蚀できるこずです。これず同様に、䟋えば、倀が`1`より小さくおも`0`より倧きくなければならないこずを芁求するこずができたす。 + +したがっお、`0.5`は有効な倀ですが、`0.0`や`0`はそうではありたせん。 + +これはltも同じです。 + +```Python hl_lines="11" +{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +## たずめ + +`Query`ず`Path`そしおただ芋たこずない他のものでは、[ク゚リパラメヌタず文字列の怜蚌](query-params-str-validations.md){.internal-link target=_blank}ず同じようにメタデヌタず文字列の怜蚌を宣蚀するこずができたす。 + +たた、数倀のバリデヌションを宣蚀するこずもできたす: + +* `gt`: より倧きい`g`reater `t`han +* `ge`: 以䞊`g`reater than or `e`qual +* `lt`: より小さい`l`ess `t`han +* `le`: 以䞋`l`ess than or `e`qual + +!!! info "情報" + `Query`、`Path`などは埌に共通の`Param`クラスのサブクラスを芋るこずになりたす。䜿う必芁はありたせん + + そしお、それらすべおは、これたで芋おきた远加のバリデヌションずメタデヌタず同じパラメヌタを共有しおいたす。 + +!!! note "技術詳现" + `fastapi`から`Query`、`Path`などをむンポヌトするず、これらは実際には関数です。 + + 呌び出されるず、同じ名前のクラスのむンスタンスを返したす。 + + そのため、関数である`Query`をむンポヌトし、それを呌び出すず、`Query`ずいう名前のクラスのむンスタンスが返されたす。 + + これらの関数はクラスを盎接䜿うのではなく゚ディタが型に぀いお゚ラヌずしないようにするために存圚したす。 + + この方法によっお、これらの゚ラヌを無芖するための蚭定を远加するこずなく、通垞の゚ディタやコヌディングツヌルを䜿甚するこずができたす。 From eed57df6f685b73e3ac0a01060ed2eb81d71fa92 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:46:53 +0000 Subject: [PATCH 080/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 997d8b5aa..68b2f0a07 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). From a14907a47d723a21c46b06d73bf568a2643657e4 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:48:41 +0900 Subject: [PATCH 081/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/body-multiple-params.md`=20?= =?UTF-8?q?(#1903)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/body-multiple-params.md | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 docs/ja/docs/tutorial/body-multiple-params.md diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..2ba10c583 --- /dev/null +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -0,0 +1,169 @@ +# ボディ - 耇数のパラメヌタ + +これたで`Path`ず`Query`をどう䜿うかを芋おきたしたが、リク゚ストボディの宣蚀のより高床な䜿い方を芋おみたしょう。 + +## `Path`、`Query`ずボディパラメヌタを混ぜる + +たず、もちろん、`Path`ず`Query`ずリク゚ストボディのパラメヌタの宣蚀は自由に混ぜるこずができ、 **FastAPI** は䜕をするべきかを知っおいたす。 + +たた、デフォルトの`None`を蚭定するこずで、ボディパラメヌタをオプションずしお宣蚀するこずもできたす: + +```Python hl_lines="19 20 21" +{!../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +!!! note "備考" + この堎合、ボディから取埗する`item`はオプションであるこずに泚意しおください。デフォルト倀は`None`です。 + +## 耇数のボディパラメヌタ + +䞊述の䟋では、*path operations*は`item`の属性を持぀以䞋のようなJSONボディを期埅しおいたした: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +しかし、`item`ず`user`のように耇数のボディパラメヌタを宣蚀するこずもできたす: + +```Python hl_lines="22" +{!../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +この堎合、**FastAPI**は関数内に耇数のボディパラメヌタPydanticモデルである぀のパラメヌタがあるこずに気付きたす。 + +そのため、パラメヌタ名をボディのキヌフィヌルド名ずしお䜿甚し、以䞋のようなボディを期埅しおいたす: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note "備考" + 以前ず同じように`item`が宣蚀されおいたにもかかわらず、`item`はキヌ`item`を持぀ボディの内郚にあるこずが期埅されおいるこずに泚意しおください。 + +**FastAPI** はリク゚ストから自動で倉換を行い、パラメヌタ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取りたす。 + +耇合デヌタの怜蚌を行い、OpenAPIスキヌマや自動ドキュメントのように文曞化しおくれたす。 + +## ボディ内の単数倀 + +ク゚リずパスパラメヌタの远加デヌタを定矩するための `Query` ず `Path` があるのず同じように、 **FastAPI** は同等の `Body` を提䟛したす。 + +䟋えば、前のモデルを拡匵しお、同じボディに `item` ず `user` の他にもう䞀぀のキヌ `importance` を入れたいず決めるこずができたす。 + +単数倀なのでそのたた宣蚀するず、**FastAPI** はそれがク゚リパラメヌタであるずみなしたす。 + +しかし、`Body`を䜿甚しお、**FastAPI** に別のボディキヌずしお扱うように指瀺するこずができたす: + + +```Python hl_lines="23" +{!../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +この堎合、**FastAPI** は以䞋のようなボディを期埅したす: + + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +繰り返しになりたすが、デヌタ型の倉換、怜蚌、文曞化などを行いたす。 + +## 耇数のボディパラメヌタずク゚リ + +もちろん、ボディパラメヌタに加えお、必芁に応じお远加のク゚リパラメヌタを宣蚀するこずもできたす。 + +デフォルトでは、単数倀はク゚リパラメヌタずしお解釈されるので、明瀺的に `Query` を远加する必芁はありたせん。 + +```Python +q: str = None +``` + +以䞋においお: + +```Python hl_lines="27" +{!../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +!!! info "情報" + `Body`もたた、埌述する `Query` や `Path` などず同様に、すべおの怜蚌パラメヌタずメタデヌタパラメヌタを持っおいたす。 + + +## 単䞀のボディパラメヌタの埋め蟌み + +Pydanticモデル`Item`のボディパラメヌタ`item`を1぀だけ持っおいるずしたしょう。 + +デフォルトでは、**FastAPI**はそのボディを盎接期埅したす。 + +しかし、远加のボディパラメヌタを宣蚀したずきのように、キヌ `item` を持぀ JSON ずその䞭のモデルの内容を期埅したい堎合は、特別な `Body` パラメヌタ `embed` を䜿うこずができたす: + +```Python +item: Item = Body(..., embed=True) +``` + +以䞋においお: + +```Python hl_lines="17" +{!../../../docs_src/body_multiple_params/tutorial005.py!} +``` + +この堎合、**FastAPI** は以䞋のようなボディを期埅したす: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +以䞋の代わりに: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## たずめ + +リク゚ストが単䞀のボディしか持おない堎合でも、*path operation関数*に耇数のボディパラメヌタを远加するこずができたす。 + +しかし、**FastAPI** はそれを凊理し、関数内の正しいデヌタを䞎え、*path operation*内の正しいスキヌマを怜蚌し、文曞化したす。 + +たた、ボディの䞀郚ずしお受け取る単数倀を宣蚀するこずもできたす。 + +たた、単䞀のパラメヌタしか宣蚀されおいない堎合でも、ボディをキヌに埋め蟌むように **FastAPI** に指瀺するこずができたす。 From 1cf1ee42fe6469b9120257b8be4a9f7bcb117177 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:48:57 +0000 Subject: [PATCH 082/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 68b2f0a07..ebe8e1719 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). From 997281bf83d3a08716c044c7cf374103bd9fc575 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:51:30 +0000 Subject: [PATCH 083/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ebe8e1719..9ceee1fa0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). From bf9489c0ad54634c2ea6595d0e1cfdf97b1e1a6d Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:53:17 +0000 Subject: [PATCH 084/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9ceee1fa0..33cd064e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). From 5c71522974e9dcec378165b64364b8c1deeecb16 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 01:01:54 +0900 Subject: [PATCH 085/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/response-model.md`=20(#1938?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: atsumi Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/response-model.md | 208 ++++++++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 docs/ja/docs/tutorial/response-model.md diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md new file mode 100644 index 000000000..749b33061 --- /dev/null +++ b/docs/ja/docs/tutorial/response-model.md @@ -0,0 +1,208 @@ +# レスポンスモデル + +*path operations* のいずれにおいおも、`response_model`パラメヌタを䜿甚しお、レスポンスのモデルを宣蚀するこずができたす: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="17" +{!../../../docs_src/response_model/tutorial001.py!} +``` + +!!! note "備考" + `response_model`は「デコレヌタ」メ゜ッド`get`、`post`などのパラメヌタであるこずに泚意しおください。すべおのパラメヌタやボディのように、*path operation関数* のパラメヌタではありたせん。 + +Pydanticモデルの属性に察しお宣蚀するのず同じ型を受け取るので、Pydanticモデルになるこずもできたすが、䟋えば、`List[Item]`のようなPydanticモデルの`list`になるこずもできたす。 + +FastAPIは`response_model`を䜿っお以䞋のこずをしたす: + +* 出力デヌタを型宣蚀に倉換したす。 +* デヌタを怜蚌したす。 +* OpenAPIの *path operation* で、レスポンス甚のJSON Schemaを远加したす。 +* 自動ドキュメントシステムで䜿甚されたす。 + +しかし、最も重芁なのは: + +* 出力デヌタをモデルのデヌタに限定したす。これがどのように重芁なのか以䞋で芋おいきたしょう。 + +!!! note "技術詳现" + レスポンスモデルは、関数の戻り倀のアノテヌションではなく、このパラメヌタで宣蚀されおいたす。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデヌタベヌスオブゞェクト、あるいは他のモデルを返し、`response_model`を䜿甚しおフィヌルドの制限やシリアラむズを行うからです。 + +## 同じ入力デヌタの返华 + +ここでは`UserIn`モデルを宣蚀しおいたす。それには平文のパスワヌドが含たれおいたす: + +```Python hl_lines="9 11" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +そしお、このモデルを䜿甚しお入力を宣蚀し、同じモデルを䜿っお出力を宣蚀しおいたす: + +```Python hl_lines="17 18" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +これで、ブラりザがパスワヌドを䜿っおナヌザヌを䜜成する際に、APIがレスポンスで同じパスワヌドを返すようになりたした。 + +この堎合、ナヌザヌ自身がパスワヌドを送信しおいるので問題ないかもしれたせん。 + +しかし、同じモデルを別の*path operation*に䜿甚するず、すべおのクラむアントにナヌザヌのパスワヌドを送信しおしたうこずになりたす。 + +!!! danger "危険" + ナヌザヌの平文のパスワヌドを保存したり、レスポンスで送信したりするこずは絶察にしないでください。 + +## 出力モデルの远加 + +代わりに、平文のパスワヌドを持぀入力モデルず、パスワヌドを持たない出力モデルを䜜成するこずができたす: + +```Python hl_lines="9 11 16" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +ここでは、*path operation関数*がパスワヌドを含む同じ入力ナヌザヌを返しおいるにもかかわらず: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +...`response_model`を`UserOut`ず宣蚀したこずで、パスワヌドが含たれおいたせん: + +```Python hl_lines="22" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +そのため、**FastAPI** は出力モデルで宣蚀されおいない党おのデヌタをフィルタリングしおくれたすPydanticを䜿甚。 + +## ドキュメントを芋る + +自動ドキュメントを芋るず、入力モデルず出力モデルがそれぞれ独自のJSON Schemaを持っおいるこずが確認できたす。 + + + +そしお、䞡方のモデルは、察話型のAPIドキュメントに䜿甚されたす: + + + +## レスポンスモデルの゚ンコヌディングパラメヌタ + +レスポンスモデルにはデフォルト倀を蚭定するこずができたす: + +```Python hl_lines="11 13 14" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +* `description: str = None`は`None`がデフォルト倀です。 +* `tax: float = 10.5`は`10.5`がデフォルト倀です。 +* `tags: List[str] = []` は空のリスト`[]`がデフォルト倀です。 + +しかし、実際に保存されおいない堎合には結果からそれらを省略した方が良いかもしれたせん。 + +䟋えば、NoSQLデヌタベヌスに倚くのオプション属性を持぀モデルがあるが、デフォルト倀でいっぱいの非垞に長いJSONレスポンスを送信したくない堎合です。 + +### `response_model_exclude_unset`パラメヌタの䜿甚 + +*path operation デコレヌタ*に`response_model_exclude_unset=True`パラメヌタを蚭定するこずができたす: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +そしお、これらのデフォルト倀はレスポンスに含たれず、実際に蚭定された倀のみが含たれたす。 + +そのため、*path operation*にID`foo`が蚭定されたitemのリク゚ストを送るず、レスポンスは以䞋のようになりたすデフォルト倀を含たない: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info "情報" + FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメヌタで䜿甚しおいたす。 + +!!! info "情報" + 以䞋も䜿甚するこずができたす: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + `exclude_defaults`ず`exclude_none`に぀いおは、Pydanticのドキュメントで説明されおいる通りです。 + +#### デフォルト倀を持぀フィヌルドの倀を持぀デヌタ + +しかし、ID`bar`のitemのように、デフォルト倀が蚭定されおいるモデルのフィヌルドに倀が蚭定されおいる堎合: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +それらはレスポンスに含たれたす。 + +#### デフォルト倀ず同じ倀を持぀デヌタ + +ID`baz`のitemのようにデフォルト倀ず同じ倀を持぀デヌタの堎合: + +```Python hl_lines="3 5 6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPIは十分に賢いので実際には、Pydanticが十分に賢い`description`や`tax`、`tags`はデフォルト倀ず同じ倀を持っおいるにもかかわらず、明瀺的に蚭定されおいるこずを理解しおいたす。デフォルトから取埗するのではなく + +そのため、それらはJSONレスポンスに含たれるこずになりたす。 + +!!! tip "豆知識" + デフォルト倀は`None`だけでなく、なんでも良いこずに泚意しおください。 + 䟋えば、リスト`[]`や`10.5`の`float`などです。 + +### `response_model_include`ず`response_model_exclude` + +*path operationデコレヌタ*ずしお`response_model_include`ず`response_model_exclude`も䜿甚するこずができたす。 + +属性名を持぀`str`の`set`を受け取り、含める(残りを省略する)か、陀倖(残りを含む)したす。 + +これは、Pydanticモデルが぀しかなく、出力からいく぀かのデヌタを削陀したい堎合のクむックショヌトカットずしお䜿甚するこずができたす。 + +!!! tip "豆知識" + それでも、これらのパラメヌタではなく、耇数のクラスを䜿甚しお、䞊蚘のようなアむデアを䜿うこずをおすすめしたす。 + + これは`response_model_include`や`response_mode_exclude`を䜿甚しおいく぀かの属性を省略しおも、アプリケヌションのOpenAPIずドキュメントで生成されたJSON Schemaが完党なモデルになるからです。 + + 同様に動䜜する`response_model_by_alias`にも圓おはたりたす。 + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial005.py!} +``` + +!!! tip "豆知識" + `{"name", "description"}`の構文はこれら぀の倀をも぀`set`を䜜成したす。 + + これは`set(["name", "description"])`ず同等です。 + +#### `set`の代わりに`list`を䜿甚する + +もし`set`を䜿甚するこずを忘れお、代わりに`list`や`tuple`を䜿甚しおも、FastAPIはそれを`set`に倉換しお正しく動䜜したす: + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial006.py!} +``` + +## たずめ + +*path operationデコレヌタの*`response_model`パラメヌタを䜿甚しお、レスポンスモデルを定矩し、特にプラむベヌトデヌタがフィルタリングされおいるこずを保蚌したす。 + +明瀺的に蚭定された倀のみを返すには、`response_model_exclude_unset`を䜿甚したす。 From 39bb4bbdfc654eab57ce2bc57286c3ea2ca39c7d Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 01:08:16 +0900 Subject: [PATCH 086/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/dependencies/index.md`=20an?= =?UTF-8?q?d=20`docs/ja/docs/tutorial/dependencies/classes-as-dependencies?= =?UTF-8?q?.md`=20(#1958)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- .../dependencies/classes-as-dependencies.md | 191 ++++++++++++++++ docs/ja/docs/tutorial/dependencies/index.md | 209 ++++++++++++++++++ 2 files changed, 400 insertions(+) create mode 100644 docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md create mode 100644 docs/ja/docs/tutorial/dependencies/index.md diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..5c150d00c --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,191 @@ +# 䟝存関係ずしおのクラス + +**䟝存性泚入** システムを深く掘り䞋げる前に、先ほどの䟋をアップグレヌドしおみたしょう。 + +## 前の䟋の`dict` + +前の䟋では、䟝存関係"dependable"から`dict`を返しおいたした: + +```Python hl_lines="9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +しかし、*path operation関数*のパラメヌタ`commons`に`dict`が含たれおいたす。 + +たた、゚ディタは`dict`のキヌず倀の型を知るこずができないため、倚くのサポヌト補完のようなを提䟛するこずができたせん。 + +もっずうたくやれるはずです...。 + +## 䟝存関係を䜜るもの + +これたでは、䟝存関係が関数ずしお宣蚀されおいるのを芋おきたした。 + +しかし、䟝存関係を定矩する方法はそれだけではありたせんその方が䞀般的かもしれたせんが。 + +重芁なのは、䟝存関係が「呌び出し可胜」なものであるこずです。 + +Pythonにおける「**呌び出し可胜**」ずは、Pythonが関数のように「呌び出す」こずができるものを指したす。 + +そのため、`something`オブゞェクト関数ではないかもしれたせんがを持っおいお、それを次のように「呌び出す」実行するこずができるずしたす: + +```Python +something() +``` + +たたは + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +これを「呌び出し可胜」なものず呌びたす。 + +## 䟝存関係ずしおのクラス + +Pythonのクラスのむンスタンスを䜜成する際に、同じ構文を䜿甚しおいるこずに気づくかもしれたせん。 + +䟋えば: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +この堎合、`fluffy`は`Cat`クラスのむンスタンスです。 + +そしお`fluffy`を䜜成するために、`Cat`を「呌び出しおいる」こずになりたす。 + +そのため、Pythonのクラスもたた「呌び出し可胜」です。 + +そしお、**FastAPI** では、Pythonのクラスを䟝存関係ずしお䜿甚するこずができたす。 + +FastAPIが実際にチェックしおいるのは、それが「呌び出し可胜」関数、クラス、その他なんでもであり、パラメヌタが定矩されおいるかどうかずいうこずです。 + +**FastAPI** の䟝存関係ずしお「呌び出し可胜なもの」を枡すず、その「呌び出し可胜なもの」のパラメヌタを解析し、サブ䟝存関係も含めお、*path operation関数*のパラメヌタず同じように凊理したす。 + +それは、パラメヌタが党くない呌び出し可胜なものにも適甚されたす。パラメヌタのない*path operation関数*ず同じように。 + +そこで、䞊で玹介した䟝存関係の`common_parameters`を`CommonQueryParams`クラスに倉曎したす: + +```Python hl_lines="11 12 13 14 15" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +クラスのむンスタンスを䜜成するために䜿甚される`__init__`メ゜ッドに泚目しおください: + +```Python hl_lines="12" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +...以前の`common_parameters`ず同じパラメヌタを持っおいたす: + +```Python hl_lines="8" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これらのパラメヌタは **FastAPI** が䟝存関係を「解決」するために䜿甚するものです。 + +どちらの堎合も以䞋を持っおいたす: + +* オプショナルの`q`ク゚リパラメヌタ。 +* `skip`ク゚リパラメヌタ、デフォルトは`0`。 +* `limit`ク゚リパラメヌタ、デフォルトは`100`。 + +どちらの堎合も、デヌタは倉換され、怜蚌され、OpenAPIスキヌマなどで文曞化されたす。 + +## 䜿甚 + +これで、このクラスを䜿甚しお䟝存関係を宣蚀するこずができたす。 + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +**FastAPI** は`CommonQueryParams`クラスを呌び出したす。これにより、そのクラスの「むンスタンス」が䜜成され、むンスタンスはパラメヌタ`commons`ずしお関数に枡されたす。 + +## 型泚釈ず`Depends` + +䞊のコヌドでは`CommonQueryParams`を回曞いおいるこずに泚目しおください: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +以䞋にある最埌の`CommonQueryParams`: + +```Python +... = Depends(CommonQueryParams) +``` + +...は、**FastAPI** が䟝存関係を知るために実際に䜿甚するものです。 + +そこからFastAPIが宣蚀されたパラメヌタを抜出し、それが実際にFastAPIが呌び出すものです。 + +--- + +この堎合、以䞋にある最初の`CommonQueryParams`: + +```Python +commons: CommonQueryParams ... +``` + +...は **FastAPI** に察しお特別な意味をもちたせん。FastAPIはデヌタ倉換や怜蚌などには䜿甚したせんそれらのためには`= Depends(CommonQueryParams)`を䜿甚しおいたす。 + +実際には以䞋のように曞けばいいだけです: + +```Python +commons = Depends(CommonQueryParams) +``` + +以䞋にあるように: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial003.py!} +``` + +しかし、型を宣蚀するこずは掚奚されおいたす。そうすれば、゚ディタは`commons`のパラメヌタずしお䜕が枡されるかを知るこずができ、コヌドの補完や型チェックなどを行うのに圹立ちたす: + + + +## ショヌトカット + +しかし、ここでは`CommonQueryParams`を回曞くずいうコヌドの繰り返しが発生しおいるこずがわかりたす: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +䟝存関係が、クラス自䜓のむンスタンスを䜜成するために**FastAPI**が「呌び出す」*特定の*クラスである堎合、**FastAPI** はこれらのケヌスのショヌトカットを提䟛しおいたす。 + +それらの具䜓的なケヌスに぀いおは以䞋のようにしたす: + +以䞋のように曞く代わりに: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +...以䞋のように曞きたす: + +```Python +commons: CommonQueryParams = Depends() +``` + +パラメヌタの型ずしお䟝存関係を宣蚀し、`Depends()`の䞭でパラメヌタを指定せず、`Depends()`をその関数のパラメヌタの「デフォルト」倀`=`のあずの倀ずしお䜿甚するこずで、`Depends(CommonQueryParams)`の䞭でクラス党䜓を*もう䞀床*曞かなくおもよくなりたす。 + +同じ䟋では以䞋のようになりたす: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial004.py!} +``` + +...そしお **FastAPI** は䜕をすべきか知っおいたす。 + +!!! tip "豆知識" + 圹に立぀ずいうよりも、混乱するようであれば無芖しおください。それをする*必芁*はありたせん。 + + それは単なるショヌトカットです。なぜなら **FastAPI** はコヌドの繰り返しを最小限に抑えるこずに気を䜿っおいるからです。 diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..ec563a16d --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -0,0 +1,209 @@ +# 䟝存関係 - 最初のステップ + +** FastAPI** は非垞に匷力でありながら盎感的な **䟝存性泚入** システムを持っおいたす。 + +それは非垞にシンプルに䜿甚できるように蚭蚈されおおり、開発者が他のコンポヌネント **FastAPI** ず統合するのが非垞に簡単になるように蚭蚈されおいたす。 + +## 「䟝存性泚入」ずは + +**「䟝存性泚入」** ずは、プログラミングにおいお、コヌドこの堎合は、*path operation関数*が動䜜したり䜿甚したりするために必芁なもの「䟝存関係」を宣蚀する方法があるこずを意味したす: + +そしお、そのシステムこの堎合は、**FastAPI**は、必芁な䟝存関係をコヌドに提䟛するために必芁なこずは䜕でも行いたす䟝存関係を「泚入」したす。 + +これは以䞋のようなこずが必芁な時にずおも䟿利です: + +* ロゞックを共有しおいる。同じコヌドロゞックを䜕床も繰り返しおいる。 +* デヌタベヌス接続を共有する。 +* セキュリティ、認蚌、ロヌル芁件などを匷制する。 +* そのほかにも倚くのこず... + +これらすべおを、コヌドの繰り返しを最小限に抑えながら行いたす。 + +## 最初のステップ + +非垞にシンプルな䟋を芋おみたしょう。あたりにもシンプルなので、今のずころはあたり参考にならないでしょう。 + +しかし、この方法では **䟝存性泚入** システムがどのように機胜するかに焊点を圓おるこずができたす。 + +### 䟝存関係の䜜成 + +たずは䟝存関係に泚目しおみたしょう。 + +以䞋のように、*path operation関数*ず同じパラメヌタを党お取るこずができる関数にすぎたせん: + +```Python hl_lines="8 9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これだけです。 + +**行**。 + +そしお、それはすべおの*path operation関数*が持っおいるのず同じ圢ず構造を持っおいたす。 + +「デコレヌタ」を含たない`@app.get("/some-path")`を含たない*path operation関数*ず考えるこずもできたす。 + +そしお䜕でも返すこずができたす。 + +この堎合、この䟝存関係は以䞋を期埅しおいたす: + +* オプショナルのク゚リパラメヌタ`q`は`str`です。 +* オプショナルのク゚リパラメヌタ`skip`は`int`で、デフォルトは`0`です。 +* オプショナルのク゚リパラメヌタ`limit`は`int`で、デフォルトは`100`です。 + +そしお、これらの倀を含む`dict`を返したす。 + +### `Depends`のむンポヌト + +```Python hl_lines="3" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +### "dependant"での䟝存関係の宣蚀 + +*path operation関数*のパラメヌタに`Body`や`Query`などを䜿甚するのず同じように、新しいパラメヌタに`Depends`を䜿甚するこずができたす: + +```Python hl_lines="13 18" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +関数のパラメヌタに`Depends`を䜿甚するのは`Body`や`Query`などず同じですが、`Depends`の動䜜は少し異なりたす。 + +`Depends`は぀のパラメヌタしか䞎えられたせん。 + +このパラメヌタは関数のようなものである必芁がありたす。 + +そしお、その関数は、*path operation関数*が行うのず同じ方法でパラメヌタを取りたす。 + +!!! tip "豆知識" + 次の章では、関数以倖の「もの」が䟝存関係ずしお䜿甚できるものを芋おいきたす。 + +新しいリク゚ストが到着するたびに、**FastAPI** が以䞋のような凊理を行いたす: + +* 䟝存関係"dependable"関数を正しいパラメヌタで呌び出したす。 +* 関数の結果を取埗したす。 +* *path operation関数*のパラメヌタにその結果を代入しおください。 + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +この方法では、共有されるコヌドを䞀床曞き、**FastAPI** が*path operations*のための呌び出しを行いたす。 + +!!! check "確認" + 特別なクラスを䜜成しおどこかで **FastAPI** に枡しお「登録」する必芁はないこずに泚意しおください。 + + `Depends`を枡すだけで、**FastAPI** が残りの凊理をしおくれたす。 + +## `async`にするかどうか + +䟝存関係は **FastAPI***path operation関数*ず同じからも呌び出されるため、関数を定矩する際にも同じルヌルが適甚されたす。 + +`async def`や通垞の`def`を䜿甚するこずができたす。 + +たた、通垞の`def`*path operation関数*の䞭に`async def`を入れお䟝存関係を宣蚀したり、`async def`*path operation関数*の䞭に`def`を入れお䟝存関係を宣蚀したりするこずなどができたす。 + +それは重芁ではありたせん。**FastAPI** は䜕をすべきかを知っおいたす。 + +!!! note "備考" + わからない堎合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の䞭の`async`ず`await`に぀いおのセクションを確認しおください。 + +## OpenAPIずの統合 + +䟝存関係およびサブ䟝存関係のすべおのリク゚スト宣蚀、怜蚌、および芁件は、同じOpenAPIスキヌマに統合されたす。 + +぀たり、察話型ドキュメントにはこれらの䟝存関係から埗られる党おの情報も含たれおいるずいうこずです: + + + +## 簡単な䜿い方 + +芋おみるず、*path*ず*operation*が䞀臎した時に*path operation関数*が宣蚀されおいお、**FastAPI** が正しいパラメヌタで関数を呌び出しおリク゚ストからデヌタを抜出する凊理をしおいたす。 + +実は、すべおのあるいはほずんどのWebフレヌムワヌクは、このように動䜜したす。 + +これらの関数を盎接呌び出すこずはありたせん。これらの関数はフレヌムワヌクこの堎合は、**FastAPI**によっお呌び出されたす。 + +䟝存性泚入システムでは、**FastAPI** に*path operation*もたた、*path operation関数*の前に実行されるべき他の䜕かに「䟝存」しおいるこずを䌝えるこずができ、**FastAPI** がそれを実行し、結果を「泚入」するこずを匕き受けたす。 + +他にも、「䟝存性泚入」ず同じような考えの䞀般的な甚語がありたす: + +* リ゜ヌス +* プロバむダ +* サヌビス +* むンゞェクタブル +* コンポヌネント + +## **FastAPI** プラグむン + +統合や「プラグむン」は **䟝存性泚入** システムを䜿っお構築するこずができたす。しかし、実際には、**「プラグむン」を䜜成する必芁はありたせん**。䟝存関係を䜿甚するこずで、無限の数の統合やむンタラクションを宣蚀するこずができ、それが**path operation関数*で利甚可胜になるからです。 + +䟝存関係は非垞にシンプルで盎感的な方法で䜜成するこずができ、必芁なPythonパッケヌゞをむンポヌトするだけで、*文字通り*数行のコヌドでAPI関数ず統合するこずができたす。 + +次の章では、リレヌショナルデヌタベヌスやNoSQLデヌタベヌス、セキュリティなどに぀いお、その䟋を芋おいきたす。 + +## **FastAPI** 互換性 + +䟝存性泚入システムがシンプルなので、**FastAPI** は以䞋のようなものず互換性がありたす: + +* すべおのリレヌショナルデヌタベヌス +* NoSQLデヌタベヌス +* 倖郚パッケヌゞ +* 倖郚API +* 認蚌・認可システム +* API利甚状況監芖システム +* レスポンスデヌタ泚入システム +* など。 + +## シンプルでパワフル + +階局䟝存性泚入システムは、定矩や䜿甚方法が非垞にシンプルであるにもかかわらず、非垞に匷力なものずなっおいたす。 + +䟝存関係事態を定矩する䟝存関係を定矩するこずができたす。 + +最終的には、䟝存関係の階局ツリヌが構築され、**䟝存性泚入**システムが、これらの䟝存関係およびそのサブ䟝存関係をすべお解決し、各ステップで結果を提䟛泚入したす。 + +䟋えば、぀のAPI゚ンドポむント*path operations*があるずしたす: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +そしお、䟝存関係ずサブ䟝存関係だけで、それぞれに異なるパヌミッション芁件を远加するこずができたす: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## **OpenAPI** ずの統合 + +これら党おの䟝存関係は、芁件を宣蚀するず同時に、*path operations*にパラメヌタやバリデヌションを远加したす。 + +**FastAPI** はそれをすべおOpenAPIスキヌマに远加しお、察話型のドキュメントシステムに衚瀺されるようにしたす。 From 8ad62bd837c0d098c6d55c35f414710946c18628 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 16:10:30 +0000 Subject: [PATCH 087/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 33cd064e9..a23d367e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). From 289fbc83badcd60c9a91a2a7c1fc0e43f951d497 Mon Sep 17 00:00:00 2001 From: tokusumi <41147016+tokusumi@users.noreply.github.com> Date: Tue, 16 Jan 2024 01:12:39 +0900 Subject: [PATCH 088/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/background-tasks.md`=20(#26?= =?UTF-8?q?68)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/background-tasks.md | 94 +++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 docs/ja/docs/tutorial/background-tasks.md diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..6094c370f --- /dev/null +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -0,0 +1,94 @@ +# バックグラりンドタスク + +レスポンスを返した *埌に* 実行されるバックグラりンドタスクを定矩できたす。 + +これは、リク゚スト埌に凊理を開始する必芁があるが、クラむアントがレスポンスを受け取る前に凊理を終える必芁のない操䜜に圹立ちたす。 + +これには、たずえば次のものが含たれたす。 + +* 䜜業実行埌のメヌル通知: + * メヌルサヌバヌぞの接続ずメヌルの送信は「遅い」(数秒) 傟向があるため、すぐにレスポンスを返し、バックグラりンドでメヌル通知ができたす。 +* デヌタ凊理: + * たずえば、時間のかかる凊理を必芁ずするファむル受信時には、「受信枈み」(HTTP 202) のレスポンスを返し、バックグラりンドで凊理できたす。 + +## `BackgroundTasks` の䜿甚 + +たず初めに、`BackgroundTasks` をむンポヌトし、` BackgroundTasks` の型宣蚀ず共に、*path operation 関数* のパラメヌタヌを定矩したす: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** は、`BackgroundTasks` 型のオブゞェクトを䜜成し、そのパラメヌタヌに枡したす。 + +## タスク関数の䜜成 + +バックグラりンドタスクずしお実行される関数を䜜成したす。 + +これは、パラメヌタヌを受け取るこずができる単なる暙準的な関数です。 + +これは `async def` たたは通垞の `def` 関数であり、**FastAPI** はこれを正しく凊理したす。 + +ここで、タスク関数はファむル曞き蟌みを実行したす (メヌル送信のシミュレヌション)。 + +たた、曞き蟌み操䜜では `async` ず `await` を䜿甚しないため、通垞の `def` で関数を定矩したす。 + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## バックグラりンドタスクの远加 + +*path operations 関数* 内で、`.add_task()` メ゜ッドを䜿甚しおタスク関数を *background tasks* オブゞェクトに枡したす。 + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` は以䞋の匕数を受け取りたす: + +* バックグラりンドで実行されるタスク関数 (`write_notification`)。 +* タスク関数に順番に枡す必芁のある匕数の列 (`email`)。 +* タスク関数に枡す必芁のあるキヌワヌド匕数 (`message="some notification"`)。 + +## 䟝存性泚入 + +`BackgroundTasks` の䜿甚は䟝存性泚入システムでも機胜し、様々な階局 (*path operations 関数*、䟝存性 (䟝存可胜性)、サブ䟝存性など) で `BackgroundTasks` 型のパラメヌタヌを宣蚀できたす。 + +**FastAPI** は、それぞれの堎合の凊理​​方法ず同じオブゞェクトの再利甚方法を知っおいるため、すべおのバックグラりンドタスクがマヌゞされ、バックグラりンドで埌で実行されたす。 + +```Python hl_lines="13 15 22 25" +{!../../../docs_src/background_tasks/tutorial002.py!} +``` + +この䟋では、レスポンスが送信された *埌* にメッセヌゞが `log.txt` ファむルに曞き蟌たれたす。 + +リク゚ストにク゚リがあった堎合、バックグラりンドタスクでログに曞き蟌たれたす。 + +そしお、*path operations 関数* で生成された別のバックグラりンドタスクは、`email` パスパラメヌタを䜿甚しおメッセヌゞを曞き蟌みたす。 + +## 技術的な詳现 + +`BackgroundTasks` クラスは、`starlette.background`から盎接取埗されたす。 + +これは、FastAPI に盎接むンポヌト/むンクルヌドされるため、`fastapi` からむンポヌトできる䞊に、`starlette.background`から別の `BackgroundTask` (末尟に `s` がない) を誀っおむンポヌトするこずを回避できたす。 + +`BackgroundTasks`のみを䜿甚するこずで (`BackgroundTask` ではなく)、`Request` オブゞェクトを盎接䜿甚する堎合ず同様に、それを *path operations 関数* パラメヌタヌずしお䜿甚し、**FastAPI** に残りの凊理を任せるこずができたす。 + +それでも、FastAPI で `BackgroundTask` を単独で䜿甚するこずは可胜ですが、コヌド内でオブゞェクトを䜜成し、それを含むStarlette `Response` を返す必芁がありたす。 + +詳现に぀いおは、バックグラりンドタスクに関する Starlette の公匏ドキュメントを参照しお䞋さい。 + +## 譊告 + +倧量のバックグラりンド蚈算が必芁であり、必ずしも同じプロセスで実行する必芁がない堎合 (たずえば、メモリや倉数などを共有する必芁がない堎合)、Celery のようなより倧きな他のツヌルを䜿甚するずメリットがあるかもしれたせん。 + +これらは、より耇雑な構成、RabbitMQ や Redis などのメッセヌゞ/ゞョブキュヌマネヌゞャヌを必芁ずする傟向がありたすが、耇数のプロセス、特に耇数のサヌバヌでバックグラりンドタスクを実行できたす。 + +䟋を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照しおください。これらにはすべお、Celery が構築枈みです。 + +ただし、同じ **FastAPI** アプリから倉数ずオブゞェクトにアクセスする必芁がある堎合、たたは小さなバックグラりンドタスク (電子メヌル通知の送信など) を実行する必芁がある堎合は、単に `BackgroundTasks` を䜿甚できたす。 + +## たずめ + +`BackgroundTasks` をむンポヌトしお、*path operations 関数* や䟝存関係のパラメヌタに `BackgroundTasks`を䜿甚し、バックグラりンドタスクを远加しお䞋さい。 From 94404fc1a087fdc6f645b56af596abbf12269bd1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 16:16:10 +0000 Subject: [PATCH 089/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a23d367e9..e8fd93cac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/index.md` and `docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#1958](https://github.com/tiangolo/fastapi/pull/1958) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). From 6f3a134f6d5798ce9da6e74f4669056cc92f77d3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 16:18:40 +0000 Subject: [PATCH 090/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e8fd93cac..ba357b127 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/background-tasks.md`. PR [#2668](https://github.com/tiangolo/fastapi/pull/2668) by [@tokusumi](https://github.com/tokusumi). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/index.md` and `docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#1958](https://github.com/tiangolo/fastapi/pull/1958) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). From c68836ae46e7d78646bb4ba26d9822d21815782b Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 01:43:41 +0900 Subject: [PATCH 091/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/dependencies/sub-dependenci?= =?UTF-8?q?es.md`=20(#1959)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- .../tutorial/dependencies/sub-dependencies.md | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 docs/ja/docs/tutorial/dependencies/sub-dependencies.md diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..8848ac79e --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,86 @@ +# サブ䟝存関係 + +**サブ䟝存関係** を持぀䟝存関係を䜜成するこずができたす。 + +それらは必芁なだけ **深く** するこずができたす。 + +**FastAPI** はそれらを解決しおくれたす。 + +### 最初の䟝存関係「䟝存可胜なもの」 + +以䞋のような最初の䟝存関係「䟝存可胜なもの」を䜜成するこずができたす: + +```Python hl_lines="8 9" +{!../../../docs_src/dependencies/tutorial005.py!} +``` + +これはオプショナルのク゚リパラメヌタ`q`を`str`ずしお宣蚀し、それを返すだけです。 + +これは非垞にシンプルですあたり䟿利ではありたせんが、サブ䟝存関係がどのように機胜するかに焊点を圓おるのに圹立ちたす。 + +### 第二の䟝存関係 「䟝存可胜なもの」ず「䟝存」 + +そしお、別の䟝存関数「䟝存可胜なもの」を䜜成しお、同時にそれ自身の䟝存関係を宣蚀するこずができたす぀たりそれ自身も「䟝存」です: + +```Python hl_lines="13" +{!../../../docs_src/dependencies/tutorial005.py!} +``` + +宣蚀されたパラメヌタに泚目しおみたしょう: + +* この関数は䟝存関係「䟝存可胜なもの」そのものであるにもかかわらず、別の䟝存関係を宣蚀しおいたす䜕か他のものに「䟝存」しおいたす。 + * これは`query_extractor`に䟝存しおおり、それが返す倀をパラメヌタ`q`に代入したす。 +* たた、オプショナルの`last_query`クッキヌを`str`ずしお宣蚀したす。 + * ナヌザヌがク゚リ`q`を提䟛しなかった堎合、クッキヌに保存しおいた最埌に䜿甚したク゚リを䜿甚したす。 + +### 䟝存関係の䜿甚 + +以䞋のように䟝存関係を䜿甚するこずができたす: + +```Python hl_lines="21" +{!../../../docs_src/dependencies/tutorial005.py!} +``` + +!!! info "情報" + *path operation関数*の䞭で宣蚀しおいる䟝存関係は`query_or_cookie_extractor`の぀だけであるこずに泚意しおください。 + + しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呌び出す時に枡す必芁があるこずを知っおいたす。 + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## 同じ䟝存関係の耇数回の䜿甚 + +䟝存関係の぀が同じ*path operation*に察しお耇数回宣蚀されおいる堎合、䟋えば、耇数の䟝存関係が共通のサブ䟝存関係を持っおいる堎合、**FastAPI** はリク゚ストごずに回だけそのサブ䟝存関係を呌び出したす。 + +そしお、返された倀を「キャッシュ」に保存し、同じリク゚ストに察しお䟝存関係を䜕床も呌び出す代わりに、特定のリク゚ストでそれを必芁ずする党おの「䟝存関係」に枡すこずになりたす。 + +高床なシナリオでは、「キャッシュされた」倀を䜿うのではなく、同じリク゚ストの各ステップおそらく耇数回で䟝存関係を呌び出す必芁があるこずがわかっおいる堎合、`Depens`を䜿甚する際に、`use_cache=False`ずいうパラメヌタを蚭定するこずができたす。 + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +## たずめ + +ここで䜿われおいる掟手な蚀葉は別にしお、**䟝存性泚入** システムは非垞にシンプルです。 + +*path operation関数*ず同じように芋えるただの関数です。 + +しかし、それでも非垞に匷力で、任意の深くネストされた䟝存関係「グラフ」ツリヌを宣蚀するこずができたす。 + +!!! tip "豆知識" + これらの単玔な䟋では、党おが圹に立぀ずは蚀えないかもしれたせん。 + + しかし、**security** に぀いおの章で、それがどれほど有甚であるかがわかるでしょう。 + + そしお、あなたを救うコヌドの量もみるこずになるでしょう。 From 082eb21ba031ea2d432acba34f62c2c9ebfa6026 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 16:44:02 +0000 Subject: [PATCH 092/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ba357b127..19a33ab73 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/sub-dependencies.md`. PR [#1959](https://github.com/tiangolo/fastapi/pull/1959) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/background-tasks.md`. PR [#2668](https://github.com/tiangolo/fastapi/pull/2668) by [@tokusumi](https://github.com/tokusumi). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/index.md` and `docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#1958](https://github.com/tiangolo/fastapi/pull/1958) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc). From b518241c590027e2367366b89cd95eaba2c05705 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 01:44:28 +0900 Subject: [PATCH 093/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/dependencies/dependencies-i?= =?UTF-8?q?n-path-operation-decorators.md`=20(#1960)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- ...pendencies-in-path-operation-decorators.md | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..1684d9ca1 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,62 @@ +# path operationデコレヌタの䟝存関係 + +堎合によっおは*path operation関数*の䞭で䟝存関係の戻り倀を本圓に必芁ずしないこずもありたす。 + +もしくは、䟝存関係が倀を返さない堎合もありたす。 + +しかし、それでも実行・解決する必芁がありたす。 + +このような堎合、*path operation関数*のパラメヌタを`Depends`で宣蚀する代わりに、*path operation decorator*に`dependencies`の`list`を远加するこずができたす。 + +## *path operationデコレヌタ*ぞの`dependencies`の远加 + +*path operationデコレヌタ*はオプショナルの匕数`dependencies`を受け取りたす。 + +それは`Depends()`の`list`であるべきです: + +```Python hl_lines="17" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +これらの䟝存関係は、通垞の䟝存関係ず同様に実行・解決されたす。しかし、それらの倀䜕かを返す堎合は*path operation関数*には枡されたせん。 + +!!! tip "豆知識" + ゚ディタによっおは、未䜿甚の関数パラメヌタをチェックしお゚ラヌずしお衚瀺するものもありたす。 + + `dependencies`を`path operationデコレヌタ`で䜿甚するこずで、゚ディタやツヌルの゚ラヌを回避しながら確実に実行するこずができたす。 + + たた、コヌドの未䜿甚のパラメヌタがあるのを芋お、それが䞍芁だず思っおしたうような新しい開発者の混乱を避けるのにも圹立぀かもしれたせん。 + +## 䟝存関係の゚ラヌず戻り倀 + +通垞䜿甚しおいる䟝存関係の*関数*ず同じものを䜿甚するこずができたす。 + +### 䟝存関係の芁件 + +これらはリク゚ストの芁件ヘッダのようなものやその他のサブ䟝存関係を宣蚀するこずができたす: + +```Python hl_lines="6 11" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +### 䟋倖の発生 + +これらの䟝存関係は通垞の䟝存関係ず同じように、䟋倖を`raise`発生させるこずができたす: + +```Python hl_lines="8 13" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +### 戻り倀 + +そしお、倀を返すこずも返さないこずもできたすが、倀は䜿われたせん。 + +぀たり、すでにどこかで䜿っおいる通垞の䟝存関係倀を返すものを再利甚するこずができ、倀は䜿われなくおも䟝存関係は実行されたす: + +```Python hl_lines="9 14" +{!../../../docs_src/dependencies/tutorial006.py!} +``` + +## *path operations*のグルヌプに察する䟝存関係 + +埌で、より倧きなアプリケヌションの構造([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank})に぀いお読む時に、おそらく耇数のファむルを䜿甚しお、*path operations*のグルヌプに察しお単䞀の`dependencies`パラメヌタを宣蚀する方法を孊ぶでしょう。 From 7b462b2e69dee36db320b9977d815cdf1f8d1d2d Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 01:45:09 +0900 Subject: [PATCH 094/104] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/dependencies/dependencies-w?= =?UTF-8?q?ith-yield.md`=20(#1961)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- .../dependencies/dependencies-with-yield.md | 225 ++++++++++++++++++ 1 file changed, 225 insertions(+) create mode 100644 docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..2a89e51d2 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,225 @@ +# yieldを持぀䟝存関係 + +FastAPIは、いく぀かの終了埌の远加のステップを行う䟝存関係をサポヌトしおいたす。 + +これを行うには、`return`の代わりに`yield`を䜿い、その埌に远加のステップを曞きたす。 + +!!! tip "豆知識" + `yield`は必ず䞀床だけ䜿甚するようにしおください。 + +!!! info "情報" + これを動䜜させるには、**Python 3.7** 以䞊を䜿甚するか、**Python 3.6** では"backports"をむンストヌルする必芁がありたす: + + ``` + pip install async-exit-stack async-generator + ``` + + これによりasync-exit-stackずasync-generatorがむンストヌルされたす。 + +!!! note "技術詳现" + 以䞋ず䞀緒に䜿甚できる関数なら䜕でも有効です: + + * `@contextlib.contextmanager`たたは + * `@contextlib.asynccontextmanager` + + これらは **FastAPI** の䟝存関係ずしお䜿甚するのに有効です。 + + 実際、FastAPIは内郚的にこれら぀のデコレヌタを䜿甚しおいたす。 + +## `yield`を持぀デヌタベヌスの䟝存関係 + +䟋えば、これを䜿っおデヌタベヌスセッションを䜜成し、終了埌にそれを閉じるこずができたす。 + +レスポンスを送信する前に`yield`文を含む前のコヌドのみが実行されたす。 + +```Python hl_lines="2 3 4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +生成された倀は、*path operations*や他の䟝存関係に泚入されるものです: + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +`yield`文に続くコヌドは、レスポンスが送信された埌に実行されたす: + +```Python hl_lines="5 6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! tip "豆知識" + `async`や通垞の関数を䜿甚するこずができたす。 + + **FastAPI** は、通垞の䟝存関係ず同じように、それぞれで正しいこずを行いたす。 + +## `yield`ず`try`を持぀䟝存関係 + +`yield`を持぀䟝存関係で`try`ブロックを䜿甚した堎合、その䟝存関係を䜿甚した際に発生した䟋倖を受け取るこずになりたす。 + +䟋えば、途䞭のどこかの時点で、別の䟝存関係や*path operation*の䞭で、デヌタベヌストランザクションを「ロヌルバック」したり、その他の゚ラヌを䜜成したりするコヌドがあった堎合、䟝存関係の䞭で䟋倖を受け取るこずになりたす。 + +そのため、䟝存関係の䞭にある特定の䟋倖を`except SomeException`で探すこずができたす。 + +同様に、`finally`を甚いお䟋倖があったかどうかにかかわらず、終了ステップを確実に実行するこずができたす。 + +```Python hl_lines="3 5" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +## `yield`を持぀サブ䟝存関係 + +任意の倧きさや圢のサブ䟝存関係やサブ䟝存関係の「ツリヌ」を持぀こずができ、その䞭で`yield`を䜿甚するこずができたす。 + +**FastAPI** は、`yield`を持぀各䟝存関係の「終了コヌド」が正しい順番で実行されおいるこずを確認したす。 + +䟋えば、`dependency_c`は`dependency_b`ず`dependency_b`に䟝存する`dependency_a`に、䟝存するこずができたす: + +```Python hl_lines="4 12 20" +{!../../../docs_src/dependencies/tutorial008.py!} +``` + +そしお、それらはすべお`yield`を䜿甚するこずができたす。 + +この堎合、`dependency_c`は終了コヌドを実行するために、`dependency_b`ここでは`dep_b`ずいう名前の倀がただ利甚可胜である必芁がありたす。 + +そしお、`dependency_b`は`dependency_a`ここでは`dep_a`ずいう名前の倀を終了コヌドで利甚できるようにする必芁がありたす。 + +```Python hl_lines="16 17 24 25" +{!../../../docs_src/dependencies/tutorial008.py!} +``` + +同様に、`yield`ず`return`が混圚した䟝存関係を持぀こずもできたす。 + +たた、単䞀の䟝存関係を持っおいお、`yield`などの他の䟝存関係をいく぀か必芁ずするこずもできたす。 + +䟝存関係の組み合わせは自由です。 + +**FastAPI** は、党おが正しい順序で実行されおいるこずを確認したす。 + +!!! note "技術詳现" + これはPythonのContext Managersのおかげで動䜜したす。 + + **FastAPI** はこれを実珟するために内郚的に䜿甚しおいたす。 + +## `yield`ず`HTTPException`を持぀䟝存関係 + +`yield`ず䟋倖をキャッチする`try`ブロックを持぀こずができる䟝存関係を䜿甚するこずができるこずがわかりたした。 + +`yield`の埌の終了コヌドで`HTTPException`などを発生させたくなるかもしれたせん。しかし**それはうたくいきたせん** + +`yield`を持぀䟝存関係の終了コヌドは[䟋倖ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}の*埌に*実行されたす。䟝存関係によっお投げられた䟋倖を終了コヌド`yield`の埌でキャッチするものはなにもありたせん。 + +぀たり、`yield`の埌に`HTTPException`を発生させた堎合、`HTTTPException`をキャッチしおHTTP 400のレスポンスを返すデフォルトのあるいは任意のカスタムの䟋倖ハンドラは、その䟋倖をキャッチするこずができなくなりたす。 + +これは、䟝存関係に蚭定されおいるもの䟋えば、DBセッションを、䟋えば、バックグラりンドタスクで䜿甚できるようにするものです。 + +バックグラりンドタスクはレスポンスが送信された*埌*に実行されたす。そのため、*すでに送信されおいる*レスポンスを倉曎する方法すらないので、`HTTPException`を発生させる方法はありたせん。 + +しかし、バックグラりンドタスクがDB゚ラヌを発生させた堎合、少なくずも`yield`で䟝存関係のセッションをロヌルバックしたり、きれいに閉じたりするこずができ、゚ラヌをログに蚘録したり、リモヌトのトラッキングシステムに報告したりするこずができたす。 + +䟋倖が発生する可胜性があるコヌドがある堎合は、最も普通の「Python流」なこずをしお、コヌドのその郚分に`try`ブロックを远加しおください。 + +レスポンスを返したり、レスポンスを倉曎したり、`HTTPException`を発生させたりする*前に*凊理したいカスタム䟋倖がある堎合は、[カスタム䟋倖ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を䜜成しおください。 + +!!! tip "豆知識" + `HTTPException`を含む䟋倖は、`yield`の*前*でも発生させるこずができたす。ただし、埌ではできたせん。 + +実行の順序は倚かれ少なかれ以䞋の図のようになりたす。時間は䞊から䞋ぞず流れおいきたす。そしお、各列はコヌドを盞互䜜甚させたり、実行したりしおいる郚分の䞀぀です。 + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> handler: Raise HTTPException + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +!!! info "情報" + **぀のレスポンス** だけがクラむアントに送信されたす。それぱラヌレスポンスの䞀぀かもしれたせんし、*path operation*からのレスポンスかもしれたせん。 + + いずれかのレスポンスが送信された埌、他のレスポンスを送信するこずはできたせん。 + +!!! tip "豆知識" + この図は`HTTPException`を瀺しおいたすが、[カスタム䟋倖ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を䜜成するこずで、他の䟋倖を発生させるこずもできたす。そしお、その䟋倖は䟝存関係の終了コヌドではなく、そのカスタム䟋倖ハンドラによっお凊理されたす。 + + しかし䟋倖ハンドラで凊理されない䟋倖を発生させた堎合は、䟝存関係の終了コヌドで凊理されたす。 + +## コンテキストマネヌゞャ + +### 「コンテキストマネヌゞャ」ずは + +「コンテキストマネヌゞャ」ずは、`with`文の䞭で䜿甚できるPythonオブゞェクトのこずです。 + +䟋えば、ファむルを読み蟌むには`with`を䜿甚するこずができたす: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +その埌の`open("./somefile.txt")`は「コンテキストマネヌゞャ」ず呌ばれるオブゞェクトを䜜成したす。 + +`with`ブロックが終了するず、䟋倖があったずしおもファむルを確かに閉じたす。 + +`yield`を䟝存関係を䜜成するず、**FastAPI** は内郚的にそれをコンテキストマネヌゞャに倉換し、他の関連ツヌルず組み合わせたす。 + +### `yield`を持぀䟝存関係でのコンテキストマネヌゞャの䜿甚 + +!!! warning "泚意" + これは倚かれ少なかれ、「高床な」発想です。 + + **FastAPI** を䜿い始めたばかりの方は、ずりあえずスキップした方がよいかもしれたせん。 + +Pythonでは、以䞋の぀のメ゜ッドを持぀クラスを䜜成する: `__enter__()`ず`__exit__()`こずでコンテキストマネヌゞャを䜜成するこずができたす。 + +たた、䟝存関数の䞭で`with`や`async with`文を䜿甚するこずによっお`yield`を持぀ **FastAPI** の䟝存関係の䞭でそれらを䜿甚するこずができたす: + +```Python hl_lines="1 2 3 4 5 6 7 8 9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! tip "豆知識" + コンテキストマネヌゞャを䜜成するもう䞀぀の方法はwithです: + + * `@contextlib.contextmanager` たたは + * `@contextlib.asynccontextmanager` + + これらを䜿っお、関数を単䞀の`yield`でデコレヌトするこずができたす。 + + これは **FastAPI** が内郚的に`yield`を持぀䟝存関係のために䜿甚しおいるものです。 + + しかし、FastAPIの䟝存関係にデコレヌタを䜿う必芁はありたせんそしお䜿うべきではありたせん。 + + FastAPIが内郚的にやっおくれたす。 From e500f994035b0caa675d2bd65c3ae11d9b848a95 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 16:45:17 +0000 Subject: [PATCH 095/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 19a33ab73..baa10754b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#1960](https://github.com/tiangolo/fastapi/pull/1960) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/sub-dependencies.md`. PR [#1959](https://github.com/tiangolo/fastapi/pull/1959) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/background-tasks.md`. PR [#2668](https://github.com/tiangolo/fastapi/pull/2668) by [@tokusumi](https://github.com/tokusumi). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/index.md` and `docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#1958](https://github.com/tiangolo/fastapi/pull/1958) by [@SwftAlpc](https://github.com/SwftAlpc). From 2c670325af38a738d7cd8eecd622be77f900c6d8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 16:47:21 +0000 Subject: [PATCH 096/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index baa10754b..5d6c55709 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#1961](https://github.com/tiangolo/fastapi/pull/1961) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#1960](https://github.com/tiangolo/fastapi/pull/1960) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/sub-dependencies.md`. PR [#1959](https://github.com/tiangolo/fastapi/pull/1959) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/background-tasks.md`. PR [#2668](https://github.com/tiangolo/fastapi/pull/2668) by [@tokusumi](https://github.com/tokusumi). From 8450dc204d806bac021c6a2432d7b4a0749e77cd Mon Sep 17 00:00:00 2001 From: Rafal Skolasinski Date: Mon, 15 Jan 2024 20:41:47 +0000 Subject: [PATCH 097/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`fastapi/security/oauth2.py`=20(#10972)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/security/oauth2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 9281dfb64..be3e18cd8 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -353,7 +353,7 @@ class OAuth2(SecurityBase): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. From 2ce4c102fb64efd3e59b84359ddcebaaa21003ce Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 20:42:07 +0000 Subject: [PATCH 098/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5d6c55709..ed9fdf03b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Docs +* ✏ Fix typo in `fastapi/security/oauth2.py`. PR [#10972](https://github.com/tiangolo/fastapi/pull/10972) by [@RafalSkolasinski](https://github.com/RafalSkolasinski). * 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb). * ✏ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). From 75ea31c79e9e744832570ad0f42ff8572e9fd0dd Mon Sep 17 00:00:00 2001 From: ChanHaeng Lee <61987505+2chanhaeng@users.noreply.github.com> Date: Tue, 16 Jan 2024 06:40:57 +0900 Subject: [PATCH 099/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20error?= =?UTF-8?q?=20in=20`docs/ko/docs/tutorial/path-params.md`=20(#10758)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/path-params.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 5cf397e7a..8ebd0804e 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -101,7 +101,7 @@ ## 순서 묞제 -*겜로 동작*을 만듀때 고정 겜로륌 갖고 있는 상황듀을 맞닩뜹멮 수 있습니닀. +*겜로 동작*을 만듀때 고정 겜로륌 갖고 있는 상황듀을 맞닥뜚늎 수 있습니닀. `/users/me`처럌, 현재 사용자의 데읎터륌 가젞옚닀고 합시닀. From ae92e563b1ba0d00f1aaf2b4a472f619038bf24c Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 21:41:21 +0000 Subject: [PATCH 100/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ed9fdf03b..01fc71d3d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -44,6 +44,7 @@ hide: ### Translations +* ✏ Fix typo error in `docs/ko/docs/tutorial/path-params.md`. PR [#10758](https://github.com/tiangolo/fastapi/pull/10758) by [@2chanhaeng](https://github.com/2chanhaeng). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#1961](https://github.com/tiangolo/fastapi/pull/1961) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#1960](https://github.com/tiangolo/fastapi/pull/1960) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/sub-dependencies.md`. PR [#1959](https://github.com/tiangolo/fastapi/pull/1959) by [@SwftAlpc](https://github.com/SwftAlpc). From d1e533e3705f742c7f6abaf1d68f3af75d5036e0 Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Tue, 16 Jan 2024 13:11:15 +0100 Subject: [PATCH 101/104] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Tweak=20the=20germ?= =?UTF-8?q?an=20translation=20of=20`docs/de/docs/tutorial/index.md`=20(#10?= =?UTF-8?q?962)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/index.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md index dd7ed43bd..93a30d1b3 100644 --- a/docs/de/docs/tutorial/index.md +++ b/docs/de/docs/tutorial/index.md @@ -1,6 +1,6 @@ -# Tutorial - Benutzerhandbuch - Intro +# Tutorial – Benutzerhandbuch -Diese Anleitung zeigt Ihnen Schritt fÃŒr Schritt, wie Sie **FastAPI** mit den meisten Funktionen nutzen können. +Dieses Tutorial zeigt Ihnen Schritt fÃŒr Schritt, wie Sie **FastAPI** und die meisten seiner Funktionen verwenden können. Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema ÃŒbergehen können, um Ihre speziellen API-Anforderungen zu lösen. @@ -12,7 +12,7 @@ Dadurch können Sie jederzeit zurÃŒckkommen und sehen genau das, was Sie benöt Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt). -Um eines der Beispiele auszufÃŒhren, kopieren Sie den Code in die Datei `main.py`, und starten Sie `uvicorn` mit: +Um eines der Beispiele auszufÃŒhren, kopieren Sie den Code in eine Datei `main.py`, und starten Sie `uvicorn` mit:
@@ -50,31 +50,31 @@ $ pip install "fastapi[all]"
-...dies beinhaltet auch `uvicorn`, das Sie als Server verwenden können, auf dem Ihr Code lÀuft. +... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausfÃŒhrt. -!!! Hinweis - Sie können die Installation auch in einzelnen Schritten ausfÃŒhren. +!!! note "Hinweis" + Sie können die einzelnen Teile auch separat installieren. - Dies werden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung produktiv einsetzen möchten: + Das folgende wÃŒrden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen: ``` pip install fastapi ``` - Installieren Sie auch `uvicorn`, dies arbeitet als Server: + Installieren Sie auch `uvicorn` als Server: ``` pip install "uvicorn[standard]" ``` - Dasselbe gilt fÃŒr jede der optionalen AbhÀngigkeiten, die Sie verwenden möchten. + Das gleiche gilt fÃŒr jede der optionalen AbhÀngigkeiten, die Sie verwenden möchten. -## Erweitertes Benutzerhandbuch +## Handbuch fÃŒr fortgeschrittene Benutzer -ZusÀtzlich gibt es ein **Erweitertes Benutzerhandbuch**, dies können Sie spÀter nach diesem **Tutorial - Benutzerhandbuch** lesen. +Es gibt auch ein **Handbuch fÃŒr fortgeschrittene Benutzer**, welches Sie spÀter nach diesem **Tutorial – Benutzerhandbuch** lesen können. -Das **Erweiterte Benutzerhandbuch** baut auf dieses Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen zusÀtzliche Funktionen bei. +Das **Handbuch fÃŒr fortgeschrittene Benutzer** baut auf diesem Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen einige zusÀtzliche Funktionen bei. -Allerdings sollten Sie zuerst das **Tutorial - Benutzerhandbuch** lesen (was Sie gerade lesen). +Allerdings sollten Sie zuerst das **Tutorial – Benutzerhandbuch** lesen (was Sie hier gerade tun). -Es ist so konzipiert, dass Sie nur mit dem **Tutorial - Benutzerhandbuch** eine vollstÀndige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusÀtzlichen Ideen aus dem **Erweiterten Benutzerhandbuch** erweitern können. +Die Dokumentation ist so konzipiert, dass Sie mit dem **Tutorial – Benutzerhandbuch** eine vollstÀndige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusÀtzlichen Ideen aus dem **Handbuch fÃŒr fortgeschrittene Benutzer** vervollstÀndigen können. From d761a29908aed90703d7c561f446469104903679 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 16 Jan 2024 12:11:43 +0000 Subject: [PATCH 102/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 01fc71d3d..e42e1baf4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -44,6 +44,7 @@ hide: ### Translations +* ✏ Tweak the german translation of `docs/de/docs/tutorial/index.md`. PR [#10962](https://github.com/tiangolo/fastapi/pull/10962) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typo error in `docs/ko/docs/tutorial/path-params.md`. PR [#10758](https://github.com/tiangolo/fastapi/pull/10758) by [@2chanhaeng](https://github.com/2chanhaeng). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#1961](https://github.com/tiangolo/fastapi/pull/1961) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#1960](https://github.com/tiangolo/fastapi/pull/1960) by [@SwftAlpc](https://github.com/SwftAlpc). From 950d9ce74dd2efd73572dfb6d0631ce9687ce14a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 16 Jan 2024 14:23:25 +0100 Subject: [PATCH 103/104] =?UTF-8?q?=F0=9F=93=9D=20Deprecate=20old=20tutori?= =?UTF-8?q?als:=20Peewee,=20Couchbase,=20encode/databases=20(#10979)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/async-sql-encode-databases.md | 5 ++++- docs/en/docs/how-to/nosql-databases-couchbase.md | 5 ++++- docs/en/docs/how-to/sql-databases-peewee.md | 5 ++++- docs/en/mkdocs.yml | 7 ++++--- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md index 0e2ccce78..c7b340d67 100644 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -1,4 +1,4 @@ -# Async SQL (Relational) Databases with Encode/Databases +# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated) !!! info These docs are about to be updated. 🎉 @@ -7,6 +7,9 @@ The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. +!!! warning "Deprecated" + This tutorial is deprecated and will be removed in a future version. + You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. It is compatible with: diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md index ae6ad604b..563318984 100644 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -1,4 +1,4 @@ -# NoSQL (Distributed / Big Data) Databases with Couchbase +# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated) !!! info These docs are about to be updated. 🎉 @@ -7,6 +7,9 @@ The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. +!!! warning "Deprecated" + This tutorial is deprecated and will be removed in a future version. + **FastAPI** can also be integrated with any NoSQL. Here we'll see an example using **Couchbase**, a document based NoSQL database. diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md index 74a28b170..7211f7ed3 100644 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ b/docs/en/docs/how-to/sql-databases-peewee.md @@ -1,4 +1,7 @@ -# SQL (Relational) Databases with Peewee +# ~~SQL (Relational) Databases with Peewee~~ (deprecated) + +!!! warning "Deprecated" + This tutorial is deprecated and will be removed in a future version. !!! warning If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 92d081aa1..b8d27a35b 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -174,9 +174,6 @@ nav: - How To - Recipes: - how-to/index.md - how-to/general.md - - how-to/sql-databases-peewee.md - - how-to/async-sql-encode-databases.md - - how-to/nosql-databases-couchbase.md - how-to/graphql.md - how-to/custom-request-and-route.md - how-to/conditional-openapi.md @@ -184,6 +181,9 @@ nav: - how-to/separate-openapi-schemas.md - how-to/custom-docs-ui-assets.md - how-to/configure-swagger-ui.md + - how-to/sql-databases-peewee.md + - how-to/async-sql-encode-databases.md + - how-to/nosql-databases-couchbase.md - Reference (Code API): - reference/index.md - reference/fastapi.md @@ -242,6 +242,7 @@ markdown_extensions: format: !!python/name:pymdownx.superfences.fence_code_format '' pymdownx.tabbed: alternate_style: true + pymdownx.tilde: attr_list: null md_in_html: null extra: From fc8ea413eb8a6370c3b41de7ccad6003bf37ab13 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 16 Jan 2024 13:23:49 +0000 Subject: [PATCH 104/104] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e42e1baf4..a96954527 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Docs +* 📝 Deprecate old tutorials: Peewee, Couchbase, encode/databases. PR [#10979](https://github.com/tiangolo/fastapi/pull/10979) by [@tiangolo](https://github.com/tiangolo). * ✏ Fix typo in `fastapi/security/oauth2.py`. PR [#10972](https://github.com/tiangolo/fastapi/pull/10972) by [@RafalSkolasinski](https://github.com/RafalSkolasinski). * 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb). * ✏ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann).