2,037 matches across 25 files for func main
snippet_mode: auto · sorted by relevance
3import email.message
4import errno
5▶import functools
6import inspect
7import json
· · ·
113# dependencies' AsyncExitStack
114def request_response(
115▶ func: Callable[[Request], Awaitable[Response] | Response],
116) -> ASGIApp:
117 """
· · ·
118▶ Takes a function or coroutine `func(request) -> response`,
119 and returns an ASGI application.
120 """
· · ·
121 f: Callable[[Request], Awaitable[Response]] = (
122▶ func # type: ignore[assignment]
123 if is_async_callable(func)
124 else functools.partial(run_in_threadpool, func) # type: ignore[call-arg]
· · ·
123▶ if is_async_callable(func)
124 else functools.partial(run_in_threadpool, func) # type: ignore[call-arg]
125 ) # ty: ignore[invalid-assignment]
+ 158 more matches in this file
42class FastAPI(Starlette):
43 """
44▶ `FastAPI` app class, the main entrypoint to use FastAPI.
45
46 Read more in the
· · ·
287
288 You would use it, for example, if your application is served from
289▶ different domains and you want to use the same Swagger UI in the
290 browser to interact with each of them (instead of having multiple
291 browser tabs open). Or if you want to leave fixed the possible URLs.
· · ·
344 from fastapi import Depends, FastAPI
345
346▶ from .dependencies import func_dep_1, func_dep_2
347
348 app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])
· · ·
348▶ app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])
349 ```
350 """
· · ·
504 Doc(
505 """
506▶ A list of startup event handler functions.
507
508 You should instead use the `lifespan` handlers.
+ 89 more matches in this file
1▶function setupTermynal() {
2 document.querySelectorAll(".use-termynal").forEach(node => {
3 node.style.display = "block";
· · ·
12 let termynals = [];
13
14▶ function createTermynals() {
15 document
16 .querySelectorAll(`.${termynalActivateClass} .highlight code`)
· · ·
20 const useLines = [];
21 let buffer = [];
22▶ function saveBuffer() {
23 if (buffer.length) {
24 let isBlankSpace = true;
· · ·
99 }
100
101▶ function loadVisibleTermynals() {
102 termynals = termynals.filter(termynal => {
103 if (termynal.container.getBoundingClientRect().top - innerHeight <= 0) {
· · ·
113}
114
115▶function shuffle(array) {
116 var currentIndex = array.length, temporaryValue, randomIndex;
117 while (0 !== currentIndex) {
+ 7 more matches in this file
3from collections.abc import Callable
4from dataclasses import dataclass, field
5▶from functools import cached_property, partial
6from typing import Any, Literal
7
· · ·
11
12if sys.version_info >= (3, 13): # pragma: no cover
13▶ from inspect import iscoroutinefunction
14else: # pragma: no cover
15 from asyncio import iscoroutinefunction
· · ·
15▶ from asyncio import iscoroutinefunction
16
17
· · ·
23
24
25▶def _impartial(func: Callable[..., Any]) -> Callable[..., Any]:
26 while isinstance(func, partial):
27 func = func.func
· · ·
26▶ while isinstance(func, partial):
27 func = func.func
28 return func
+ 21 more matches in this file
250
251 Swagger UI (that provides the `/docs` interface) has better support for the
252▶ OpenAPI-specific examples than the JSON Schema `examples`, that's the main
253 use case for this.
254
· · ·
609
610 Swagger UI (that provides the `/docs` interface) has better support for the
611▶ OpenAPI-specific examples than the JSON Schema `examples`, that's the main
612 use case for this.
613
· · ·
931
932 Swagger UI (that provides the `/docs` interface) has better support for the
933▶ OpenAPI-specific examples than the JSON Schema `examples`, that's the main
934 use case for this.
935
· · ·
1237
1238 Swagger UI (that provides the `/docs` interface) has better support for the
1239▶ OpenAPI-specific examples than the JSON Schema `examples`, that's the main
1240 use case for this.
1241
· · ·
1565
1566 Swagger UI (that provides the `/docs` interface) has better support for the
1567▶ OpenAPI-specific examples than the JSON Schema `examples`, that's the main
1568 use case for this.
1569
+ 15 more matches in this file
3import subprocess
4from collections.abc import Iterable
5▶from functools import lru_cache
6from os import sep as pathsep
7from pathlib import Path
· · ·
482
483
484▶if __name__ == "__main__":
485 app()
486
28
29 The actual encoding logic lives in the FastAPI routing layer. This class
30▶ serves mainly as a marker and sets the correct `Content-Type`.
31 """
32
· · ·
53 """Represents a single Server-Sent Event.
54
55▶ When `yield`ed from a *path operation function* that uses
56 `response_class=EventSourceResponse`, each `ServerSentEvent` is encoded
57 into the [SSE wire format](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream)
1try:
2▶ from fastapi_cli.cli import main as cli_main
3
4except ImportError: # pragma: no cover
· · ·
5▶ cli_main = None # type: ignore
6
7
· · ·
8▶def main() -> None:
9 if not cli_main: # type: ignore[truthy-function]
10 message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n'
· · ·
9▶ if not cli_main: # type: ignore[truthy-function]
10 message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n'
11 print(message)
· · ·
12 raise RuntimeError(message) # noqa: B904
13▶ cli_main()
14
162 responses={404: {"description": "Missing"}},
163 callbacks=[callback_route],
164▶ generate_unique_id_function=unique_id_b,
165 )
166 def read_item(item_id: str, request: Request):
· · ·
176 "include_in_schema": context.include_in_schema,
177 "response_class": context.response_class.__name__,
178▶ "generate_unique_id": context.generate_unique_id_function(context),
179 "strict_content_type": context.strict_content_type,
180 "has_dependency_overrides_provider": (
· · ·
729 )
730 router = APIRouter(
731▶ routes=[Host("{subdomain}.example.com", hosted_app, name="hosted")]
732 )
733 app = FastAPI()
· · ·
739 assert response.status_code == 200
740 assert response.text == "hosted"
741▶ url = app.url_path_for("hosted:read_item", subdomain="api", item_id="abc")
742 assert str(url) == "/api/items/abc"
743 assert url.host == "api.example.com"
· · ·
843 )
844 router = APIRouter(
845▶ routes=[Host("{subdomain}.example.com", hosted_app, name="hosted")]
846 )
847 app = FastAPI()
3from typing import Annotated, Any, Literal, Optional, Union
4
5▶from fastapi._compat import with_info_plain_validator_function
6from fastapi.logger import logger
7from pydantic import (
· · ·
52 cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]
53 ) -> Mapping[str, Any]:
54▶ return with_info_plain_validator_function(cls._validate)
55
56
· · ·
191 writeOnly: bool | None = None
192 examples: list[Any] | None = None
193▶ # Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object
194 # Schema Object
195 discriminator: Discriminator | None = None
118
119[project.scripts]
120▶fastapi = "fastapi.cli:main"
121
122[dependency-groups]
· · ·
274ignore = [
275 "E501", # line too long, handled by black
276▶ "B008", # do not perform function calls in argument defaults
277 "C901", # too complex
278]
15## Read the Tutorial first { #read-the-tutorial-first }
16
17▶The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/index.md).
18
19They are all based on the same concepts, but allow some extra functionalities.
· · ·
19▶They are all based on the same concepts, but allow some extra functionalities.
20
25Create a `TestClient` by passing your **FastAPI** application to it.
26
27▶Create functions with a name that starts with `test_` (this is a standard `pytest` convention).
28
29Use the `TestClient` object the same way as you do with `httpx`.
· · ·
35/// tip
36
37▶Notice that the testing functions are normal `def`, not `async def`.
38
39And the calls to the client are also normal calls, not using `await`.
· · ·
53/// tip
54
55▶If you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md) in the advanced tutorial.
56
57///
· · ·
71├── app
72│ ├── __init__.py
73▶│ └── main.py
74```
75
· · ·
76▶In the file `main.py` you have your **FastAPI** app:
77
78
+ 13 more matches in this file
18- Merge repeated words naturally while keeping the meaning.
19- Do **not** introduce extra words to replace repeated phrases unnecessarily.
20▶- Keep translations fluent and concise, but maintain the original meaning.
21
22**Example:**
· · ·
26
27Avoid translating literally as:
28▶Vamos ver como isso funciona e como alterar isso se você precisar fazer isso.
29
30Better translation:
· · ·
31▶Vamos ver como isso funciona e como alterar se você precisar.
32
33---
· · ·
50* bug: bug
51* context manager: gerenciador de contexto
52▶* cross domain: cross domain (do not translate to "domínio cruzado")
53* cross origin: cross origin (do not translate to "origem cruzada")
54* Cross-Origin Resource Sharing: Cross-Origin Resource Sharing (do not translate to "Compartilhamento de Recursos de Origem Cruzada")
· · ·
60* FastAPI app: aplicação FastAPI
61* framework: framework (do not translate)
62▶* feature: funcionalidade
63* guides: tutoriais
64* I/O (as in "input and output"): I/O (do not translate to "E/S")
+ 1 more matches in this file
25Crea un `TestClient` pasándole tu aplicación de **FastAPI**.
26
27▶Crea funciones con un nombre que comience con `test_` (esta es la convención estándar de `pytest`).
28
29Usa el objeto `TestClient` de la misma manera que con `httpx`.
· · ·
35/// tip | Consejo
36
37▶Nota que las funciones de prueba son `def` normales, no `async def`.
38
39Y las llamadas al cliente también son llamadas normales, sin usar `await`.
· · ·
53/// tip | Consejo
54
55▶Si quieres llamar a funciones `async` en tus pruebas además de enviar requests a tu aplicación FastAPI (por ejemplo, funciones asincrónicas de bases de datos), echa un vistazo a las [Pruebas Asincrónicas](../advanced/async-tests.md) en el tutorial avanzado.
56
57///
· · ·
71├── app
72│ ├── __init__.py
73▶│ └── main.py
74```
75
· · ·
76▶En el archivo `main.py` tienes tu aplicación de **FastAPI**:
77
78
+ 13 more matches in this file
80
81```console
82▶$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py
83
84<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
· · ·
107{* ../../docs_src/settings/app01_py310/config.py *}
108
109▶And then use it in a file `main.py`:
110
111{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
· · ·
111▶{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
112
113/// tip
· · ·
131Notice that now we don't create a default instance `settings = Settings()`.
132
133▶### The main app file { #the-main-app-file }
134
135Now we create a dependency that returns a new `config.Settings()`.
· · ·
136
137▶{* ../../docs_src/settings/app02_an_py310/main.py hl[6,12:13] *}
138
139/// tip
+ 26 more matches in this file
1# Tutorial - Guía del Usuario { #tutorial-user-guide }
2
3▶Este tutorial te muestra cómo usar **FastAPI** con la mayoría de sus funcionalidades, paso a paso.
4
5Cada sección se basa gradualmente en las anteriores, pero está estructurada para separar temas, de manera que puedas ir directamente a cualquier sección específica para resolver tus necesidades específicas de API.
· · ·
6
7▶También está diseñado para funcionar como una referencia futura para que puedas volver y ver exactamente lo que necesitas.
8
9## Ejecuta el código { #run-the-code }
· · ·
11Todos los bloques de código pueden ser copiados y usados directamente (de hecho, son archivos Python probados).
12
13▶Para ejecutar cualquiera de los ejemplos, copia el código a un archivo `main.py`, y comienza `fastapi dev`:
14
15<div class="termy">
· · ·
24 Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>
25
26▶ <span style="background-color:#007166"><font color="#D3D7CF"> module </font></span> 🐍 main.py
27
28 <span style="background-color:#007166"><font color="#D3D7CF"> code </font></span> Importing the FastAPI app object from the module with
· · ·
29 the following code:
30
31▶ <u style="text-decoration-style:solid">from </u><u style="text-decoration-style:solid"><b>main</b></u><u style="text-decoration-style:solid"> import </u><u style="text-decoration-style:solid"><b>app</b></u>
32
33 <span style="background-color:#007166"><font color="#D3D7CF"> app </font></span> Using import string: <font color="#3465A4">main:app</font>
+ 3 more matches in this file
80
81```console
82▶$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py
83
84<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
· · ·
107{* ../../docs_src/settings/app01_py310/config.py *}
108
109▶然後在 `main.py` 檔案中使用它:
110
111{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
· · ·
111▶{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
112
113/// tip
· · ·
131注意現在我們不再建立預設實例 `settings = Settings()`。
132
133▶### 主應用程式檔案 { #the-main-app-file }
134
135現在我們建立一個相依,回傳新的 `config.Settings()`。
· · ·
136
137▶{* ../../docs_src/settings/app02_an_py310/main.py hl[6,12:13] *}
138
139/// tip
+ 19 more matches in this file
7## Configuração e Instalação { #setup-and-installation }
8
9▶A **FastAPI Extension** está disponível para [VS Code](https://code.visualstudio.com/) e [Cursor](https://www.cursor.com/). Pode ser instalada diretamente pelo painel de Extensões de cada editor, pesquisando por "FastAPI" e selecionando a extensão publicada por **FastAPI Labs**. A extensão também funciona em editores no navegador, como [vscode.dev](https://vscode.dev) e [github.dev](https://github.dev).
10
11### Descoberta da Aplicação { #application-discovery }
· · ·
12
13▶Por padrão, a extensão descobre automaticamente aplicações FastAPI no seu workspace procurando por arquivos que instanciam `FastAPI()`. Se a detecção automática não funcionar para a estrutura do seu projeto, você pode especificar um ponto de entrada via `[tool.fastapi]` em `pyproject.toml` ou pela configuração `fastapi.entryPoint` do VS Code usando notação de módulo (por exemplo, `myapp.main:app`).
14
15## Funcionalidades { #features }
· · ·
15▶## Funcionalidades { #features }
16
17- **Explorador de Operações de Rota** - Uma visualização em árvore na barra lateral de todas as <dfn title="rotas, endpoints">*operações de rota*</dfn> da sua aplicação. Clique para ir diretamente a qualquer definição de rota ou de router.
· · ·
21- **Transmitir logs da aplicação** - Transmissão em tempo real dos logs da aplicação implantada no FastAPI Cloud, com filtragem por nível e busca de texto.
22
23▶Se quiser se familiarizar com as funcionalidades da extensão, você pode abrir o walkthrough da extensão acessando a Paleta de Comandos (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> ou no macOS: <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>), selecionando "Welcome: Open walkthrough..." e, em seguida, escolhendo o walkthrough "Get started with FastAPI".
24
7## Configuración e instalación { #setup-and-installation }
8
9▶La **Extensión de FastAPI** está disponible tanto para [VS Code](https://code.visualstudio.com/) como para [Cursor](https://www.cursor.com/). Se puede instalar directamente desde el panel de Extensiones en cada editor buscando "FastAPI" y seleccionando la extensión publicada por **FastAPI Labs**. La extensión también funciona en editores basados en navegador como [vscode.dev](https://vscode.dev) y [github.dev](https://github.dev).
10
11### Descubrimiento de la aplicación { #application-discovery }
· · ·
12
13▶Por defecto, la extensión descubrirá automáticamente aplicaciones FastAPI en tu espacio de trabajo escaneando archivos que crean un instance de `FastAPI()`. Si la detección automática no funciona con la estructura de tu proyecto, puedes especificar un punto de entrada mediante `[tool.fastapi]` en `pyproject.toml` o la configuración de VS Code `fastapi.entryPoint` usando notación de módulo (p. ej. `myapp.main:app`).
14
15## Funcionalidades { #features }
· · ·
15▶## Funcionalidades { #features }
16
17- **Explorador de Path Operations** - Una vista en árbol en la barra lateral de todas las <dfn title="rutas, endpoints">*path operations*</dfn> de tu aplicación. Haz clic para saltar a cualquier definición de ruta o de router.
· · ·
21- **Streaming de logs de la aplicación** - Streaming en tiempo real de logs desde tu aplicación desplegada en FastAPI Cloud, con filtrado por nivel y búsqueda de texto.
22
23▶Si quieres familiarizarte con las funcionalidades de la extensión, puedes revisar el recorrido guiado de la extensión abriendo la Paleta de Comandos (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> o en macOS: <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>) y seleccionando "Welcome: Open walkthrough..." y luego eligiendo el recorrido "Get started with FastAPI".
24
21## A `StreamingResponse` with `yield` { #a-streamingresponse-with-yield }
22
23▶If you declare a `response_class=StreamingResponse` in your *path operation function*, you can use `yield` to send each chunk of data in turn.
24
25{* ../../docs_src/stream_data/tutorial001_py310.py ln[1:23] hl[20,23] *}
· · ·
27FastAPI will give each chunk of data to the `StreamingResponse` as is, it won't try to convert it to JSON or anything similar.
28
29▶### Non-async *path operation functions* { #non-async-path-operation-functions }
30
31You can also use regular `def` functions (without `async`), and use `yield` the same way.
· · ·
31▶You can also use regular `def` functions (without `async`), and use `yield` the same way.
32
33{* ../../docs_src/stream_data/tutorial001_py310.py ln[26:29] hl[27] *}
· · ·
45### Stream Bytes { #stream-bytes }
46
47▶One of the main use cases would be to stream `bytes` instead of strings, you can of course do it.
48
49{* ../../docs_src/stream_data/tutorial001_py310.py ln[44:47] hl[47] *}
· · ·
59{* ../../docs_src/stream_data/tutorial002_py310.py ln[6,19:20] hl[20] *}
60
61▶Then you can use this new class in `response_class=PNGStreamingResponse` in your *path operation function*:
62
63{* ../../docs_src/stream_data/tutorial002_py310.py ln[23:27] hl[23] *}
+ 3 more matches in this file
80
81```console
82▶$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py
83
84<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
· · ·
107{* ../../docs_src/settings/app01_py310/config.py *}
108
109▶然后在 `main.py` 文件中使用它:
110
111{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
· · ·
111▶{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
112
113/// tip | 提示
· · ·
131注意,现在我们不再创建默认实例 `settings = Settings()`。
132
133▶### 主应用文件 { #the-main-app-file }
134
135现在我们创建一个依赖项,返回一个新的 `config.Settings()`。
· · ·
136
137▶{* ../../docs_src/settings/app02_an_py310/main.py hl[6,12:13] *}
138
139/// tip | 提示
+ 18 more matches in this file
53De la misma forma que con los modelos de Pydantic, declaras atributos de clase con anotaciones de tipos, y posiblemente, valores por defecto.
54
55▶Puedes usar todas las mismas funcionalidades de validación y herramientas que usas para los modelos de Pydantic, como diferentes tipos de datos y validaciones adicionales con `Field()`.
56
57{* ../../docs_src/settings/tutorial001_py310.py hl[2,5:8,11] *}
· · ·
80
81```console
82▶$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py
83
84<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
· · ·
107{* ../../docs_src/settings/app01_py310/config.py *}
108
109▶Y luego usarlo en un archivo `main.py`:
110
111{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
· · ·
111▶{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
112
113/// tip | Consejo
· · ·
131Nota que ahora no creamos un instance por defecto `settings = Settings()`.
132
133▶### El archivo principal de la app { #the-main-app-file }
134
135Ahora creamos una dependencia que devuelve un nuevo `config.Settings()`.
+ 28 more matches in this file
15{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
16
17▶### Using the *path operation function* name as the operationId { #using-the-path-operation-function-name-as-the-operationid }
18
19If you want to use your APIs' function names as `operationId`s, you can pass a custom `generate_unique_id_function` to `FastAPI`.
· · ·
19▶If you want to use your APIs' function names as `operationId`s, you can pass a custom `generate_unique_id_function` to `FastAPI`.
20
21The function receives each `APIRoute` and returns the `operationId` to use for that path operation.
· · ·
21▶The function receives each `APIRoute` and returns the `operationId` to use for that path operation.
22
23{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2,5:6,9] *}
· · ·
25/// warning
26
27▶If you do this, you have to make sure each one of your *path operation functions* has a unique name.
28
29Even if they are in different modules (Python files).
· · ·
39## Advanced description from docstring { #advanced-description-from-docstring }
40
41▶You can limit the lines used from the docstring of a *path operation function* for OpenAPI.
42
43Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate the output used for OpenAPI at this point.
+ 6 more matches in this file