Skip to content

Commit

Permalink
📝 Add docs about Environment Variables and Virtual Environments (#12054)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiangolo authored Aug 22, 2024
1 parent 4f3381a commit 705659b
Show file tree
Hide file tree
Showing 20 changed files with 1,228 additions and 263 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ FastAPI stands on the shoulders of giants:

## Installation

Create and activate a <a href="https://fastapi.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install FastAPI:

<div class="termy">

```console
Expand Down
126 changes: 4 additions & 122 deletions docs/en/docs/advanced/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,143 +6,25 @@ Most of these settings are variable (can change), like database URLs. And many c

For this reason it's common to provide them in environment variables that are read by the application.

## Environment Variables

/// tip

If you already know what "environment variables" are and how to use them, feel free to skip to the next section below.

///

An <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">environment variable</a> (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well).

You can create and use environment variables in the shell, without needing Python:

//// tab | Linux, macOS, Windows Bash

<div class="termy">

```console
// You could create an env var MY_NAME with
$ export MY_NAME="Wade Wilson"

// Then you could use it with other programs, like
$ echo "Hello $MY_NAME"

Hello Wade Wilson
```

</div>

////

//// tab | Windows PowerShell

<div class="termy">

```console
// Create an env var MY_NAME
$ $Env:MY_NAME = "Wade Wilson"

// Use it with other programs, like
$ echo "Hello $Env:MY_NAME"

Hello Wade Wilson
```

</div>

////

### Read env vars in Python

You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python.

For example you could have a file `main.py` with:

```Python hl_lines="3"
import os

name = os.getenv("MY_NAME", "World")
print(f"Hello {name} from Python")
```

/// tip

The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return.

If not provided, it's `None` by default, here we provide `"World"` as the default value to use.

///

Then you could call that Python program:

<div class="termy">

```console
// Here we don't set the env var yet
$ python main.py

// As we didn't set the env var, we get the default value

Hello World from Python

// But if we create an environment variable first
$ export MY_NAME="Wade Wilson"

// And then call the program again
$ python main.py

// Now it can read the environment variable

Hello Wade Wilson from Python
```

</div>

As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings.

You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration.

To do that, create it right before the program itself, on the same line:

<div class="termy">

```console
// Create an env var MY_NAME in line for this program call
$ MY_NAME="Wade Wilson" python main.py

// Now it can read the environment variable

Hello Wade Wilson from Python

// The env var no longer exists afterwards
$ python main.py

Hello World from Python
```

</div>

/// tip

You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}.

///

### Types and validation
## Types and validation

These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).

That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code.
That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code.

## Pydantic `Settings`

Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with <a href="https://docs.pydantic.dev/latest/concepts/pydantic_settings/" class="external-link" target="_blank">Pydantic: Settings management</a>.

### Install `pydantic-settings`

First, install the `pydantic-settings` package:
First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:

<div class="termy">

Expand Down
2 changes: 1 addition & 1 deletion docs/en/docs/advanced/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ There are utilities to configure it easily that you can use directly in your **F

## Install dependencies

Install `jinja2`:
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`:

<div class="termy">

Expand Down
2 changes: 1 addition & 1 deletion docs/en/docs/advanced/websockets.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets

## Install `WebSockets`

First you need to install `WebSockets`:
Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `websockets`:

<div class="termy">

Expand Down
138 changes: 16 additions & 122 deletions docs/en/docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,117 +6,13 @@ First, you might want to see the basic ways to [help FastAPI and get help](help-

If you already cloned the <a href="https://github.com/fastapi/fastapi" class="external-link" target="_blank">fastapi repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment.

### Virtual environment with `venv`
### Virtual environment

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):

<div class="termy">

```console
$ python -m venv env
```

</div>

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

Activate the new environment with:

//// tab | Linux, macOS

<div class="termy">

```console
$ source ./env/bin/activate
```

</div>

////

//// tab | Windows PowerShell

<div class="termy">

```console
$ .\env\Scripts\Activate.ps1
```

</div>

////

//// tab | Windows Bash

Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):

<div class="termy">

```console
$ source ./env/Scripts/activate
```

</div>

////

To check it worked, use:

//// tab | Linux, macOS, Windows Bash

<div class="termy">

```console
$ which pip

some/directory/fastapi/env/bin/pip
```

</div>

////

//// tab | Windows PowerShell

<div class="termy">

```console
$ Get-Command pip

some/directory/fastapi/env/bin/pip
```

</div>

////

If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉

Make sure you have the latest pip version on your local environment to avoid errors on the next steps:

<div class="termy">

```console
$ python -m pip install --upgrade pip

---> 100%
```

</div>

/// tip

Every time you install a new package with `pip` under that environment, activate the environment again.

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.

///
Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`.

### Install requirements using pip

After activating the environment as described above:
After activating the environment, install the required packages:

<div class="termy">

Expand Down Expand Up @@ -160,7 +56,19 @@ $ bash scripts/format.sh

It will also auto-sort all your imports.

For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`.
## Tests

There is a script that you can run locally to test all the code and generate coverage reports in HTML:

<div class="termy">

```console
$ bash scripts/test-cov-html.sh
```

</div>

This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.

## Docs

Expand Down Expand Up @@ -482,17 +390,3 @@ Serving at: http://127.0.0.1:8008
* 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:

<div class="termy">

```console
$ bash scripts/test-cov-html.sh
```

</div>

This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.
4 changes: 3 additions & 1 deletion docs/en/docs/deployment/manually.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ When referring to the remote machine, it's common to call it **server**, but als

When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command.

But you can also install an ASGI server manually:
But you can also install an ASGI server manually.

Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server:

//// tab | Uvicorn

Expand Down
2 changes: 2 additions & 0 deletions docs/en/docs/deployment/server-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of

## Install Gunicorn and Uvicorn

Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `gunicorn`:

<div class="termy">

```console
Expand Down
Loading

0 comments on commit 705659b

Please sign in to comment.