📝 Add docs for virtual environments and environment variables, update contributing (#1082)
This commit is contained in:
parent
45f49d57c1
commit
c96d6b791c
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,5 +1,4 @@
|
||||
*.pyc
|
||||
env*
|
||||
.mypy_cache
|
||||
.vscode
|
||||
.idea
|
||||
@ -12,3 +11,4 @@ coverage.xml
|
||||
site
|
||||
*.db
|
||||
.cache
|
||||
.venv*
|
||||
|
@ -65,6 +65,8 @@ As **SQLModel** is based on **Pydantic** and **SQLAlchemy**, it requires them. T
|
||||
|
||||
## Installation
|
||||
|
||||
Make sure you create a <a href="https://sqlmodel.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a>, activate it, and then install SQLModel, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
|
@ -4,49 +4,43 @@ First, you might want to see the basic ways to [help SQLModel 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 <a href="https://github.com/fastapi/sqlmodel" class="external-link" target="_blank">sqlmodel repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment.
|
||||
|
||||
### Poetry
|
||||
### Virtual Environment
|
||||
|
||||
**SQLModel** uses <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> to build, package, and publish the project.
|
||||
Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `sqlmodel`.
|
||||
|
||||
You can learn how to install it in the <a href="https://python-poetry.org/docs/#installation" class="external-link" target="_blank">Poetry docs</a>.
|
||||
### Install Requirements Using `pip`
|
||||
|
||||
After having Poetry available, you can install the development dependencies:
|
||||
After activating the environment, install the required packages:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ poetry install
|
||||
$ pip install -r requirements.txt
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
It will also create a virtual environment automatically and will install all the dependencies and your local SQLModel in it.
|
||||
It will install all the dependencies and your local SQLModel in your local environment.
|
||||
|
||||
### Poetry Shell
|
||||
### Using your Local SQLModel
|
||||
|
||||
To use your current environment, and to have access to all the tools in it (for example `pytest` for the tests) enter into a Poetry Shell:
|
||||
If you create a Python file that imports and uses SQLModel, and run it with the Python from your local environment, it will use your cloned local SQLModel source code.
|
||||
|
||||
<div class="termy">
|
||||
And if you update that local SQLModel source code when you run that Python file again, it will use the fresh version of SQLModel you just edited.
|
||||
|
||||
```console
|
||||
$ poetry shell
|
||||
```
|
||||
That way, you don't have to "install" your local version to be able to test every change.
|
||||
|
||||
</div>
|
||||
/// note | "Technical Details"
|
||||
|
||||
That will set up the environment variables needed and start a new shell with them.
|
||||
This only happens when you install using this included `requirements.txt` instead of running `pip install sqlmodel` directly.
|
||||
|
||||
#### Using your local SQLModel
|
||||
That is because inside the `requirements.txt` file, the local version of SQLModel is marked to be installed in "editable" mode, with the `-e` option.
|
||||
|
||||
If you create a Python file that imports and uses SQLModel, and run it with the Python from your local Poetry environment, it will use your local SQLModel source code.
|
||||
|
||||
And if you update that local SQLModel source code, when you run that Python file again, it will use the fresh version of SQLModel you just edited.
|
||||
|
||||
Poetry takes care of making that work. But of course, it will only work in the current Poetry environment, if you install standard SQLModel in another environment (not from the source in the GitHub repo), that will use the standard SQLModel, not your custom version.
|
||||
///
|
||||
|
||||
### Format
|
||||
|
||||
@ -62,9 +56,92 @@ $ bash scripts/format.sh
|
||||
|
||||
It will also auto-sort all your imports.
|
||||
|
||||
## 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
|
||||
|
||||
The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a> with <a href="https://squidfunk.github.io/mkdocs-material/" class="external-link" target="_blank">Material for MkDocs</a>.
|
||||
First, make sure you set up your environment as described above, that will install all the requirements.
|
||||
|
||||
### Docs Live
|
||||
|
||||
During local development, there is a script that builds the site and checks for any changes, live-reloading:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python ./scripts/docs.py live
|
||||
|
||||
<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008
|
||||
<span style="color: green;">[INFO]</span> Start watching changes
|
||||
<span style="color: green;">[INFO]</span> Start detecting changes
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
It will serve the documentation on `http://127.0.0.1:8008`.
|
||||
|
||||
That way, you can edit the documentation/source files and see the changes live.
|
||||
|
||||
/// tip
|
||||
|
||||
Alternatively, you can perform the same steps that scripts does manually.
|
||||
|
||||
Go into the docs director at `docs/`:
|
||||
|
||||
```console
|
||||
$ cd docs/
|
||||
```
|
||||
|
||||
Then run `mkdocs` in that directory:
|
||||
|
||||
```console
|
||||
$ mkdocs serve --dev-addr 8008
|
||||
```
|
||||
|
||||
///
|
||||
|
||||
#### Typer CLI (Optional)
|
||||
|
||||
The instructions here show you how to use the script at `./scripts/docs.py` with the `python` program directly.
|
||||
|
||||
But you can also use <a href="https://typer.tiangolo.com/typer-cli/" class="external-link" target="_blank">Typer CLI</a>, and you will get autocompletion in your terminal for the commands after installing completion.
|
||||
|
||||
If you install Typer CLI, you can install completion with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ typer --install-completion
|
||||
|
||||
zsh completion installed in /home/user/.bashrc.
|
||||
Completion will take effect once you restart the terminal.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### Docs Structure
|
||||
|
||||
The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.
|
||||
|
||||
And there are extra tools/scripts in place in `./scripts/docs.py`.
|
||||
|
||||
/// tip
|
||||
|
||||
You don't need to see the code in `./scripts/docs.py`, you just use it in the command line.
|
||||
|
||||
///
|
||||
|
||||
All the documentation is in Markdown format in the directory `./docs`.
|
||||
|
||||
@ -76,49 +153,12 @@ In fact, those blocks of code are not written inside the Markdown, they are Pyth
|
||||
|
||||
And those Python files are included/injected in the documentation when generating the site.
|
||||
|
||||
### Docs for tests
|
||||
### Docs for Tests
|
||||
|
||||
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.
|
||||
|
||||
During local development, there is a script that builds the site and checks for any changes, live-reloading:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ bash scripts/docs-live.sh
|
||||
|
||||
<span style="color: green;">[INFO]</span> - Building documentation...
|
||||
<span style="color: green;">[INFO]</span> - Cleaning site directory
|
||||
<span style="color: green;">[INFO]</span> - Documentation built in 2.74 seconds
|
||||
<span style="color: green;">[INFO]</span> - Serving on http://127.0.0.1:8008
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
It will serve the documentation on `http://127.0.0.1:8008`.
|
||||
|
||||
That way, you can edit the documentation/source files and see the changes live.
|
||||
|
||||
## 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.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.
|
||||
|
||||
## Thanks
|
||||
|
||||
Thanks for contributing! ☕
|
||||
|
@ -4,7 +4,7 @@
|
||||
|
||||
Are you a seasoned developer and already know everything about databases? 🤓
|
||||
|
||||
Then you can skip to the [Tutorial - User Guide: First Steps](tutorial/index.md){.internal-link target=_blank} right away.
|
||||
Then you can skip to the next sections right away.
|
||||
|
||||
///
|
||||
|
||||
|
300
docs/environment-variables.md
Normal file
300
docs/environment-variables.md
Normal file
@ -0,0 +1,300 @@
|
||||
# Environment Variables
|
||||
|
||||
Before we jump into code, let's cover a bit some of the **basics** that we'll need to understand how to work with Python (and programming) in general. Let's check a bit about **environment variables**.
|
||||
|
||||
/// tip
|
||||
|
||||
If you already know what "environment variables" are and how to use them, feel free to skip this.
|
||||
|
||||
///
|
||||
|
||||
An environment variable (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).
|
||||
|
||||
Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.
|
||||
|
||||
## Create and Use Env Vars
|
||||
|
||||
You can **create** and use environment variables in the **shell (terminal)**, 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:
|
||||
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
|
||||
<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>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<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
|
||||
$ $Env: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>.
|
||||
|
||||
///
|
||||
|
||||
## 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 any validation has to be done in code.
|
||||
|
||||
## `PATH` Environment Variable
|
||||
|
||||
There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run.
|
||||
|
||||
The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows.
|
||||
|
||||
For example, the `PATH` environment variable could look like this:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
```plaintext
|
||||
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
|
||||
```
|
||||
|
||||
This means that the system should look for programs in the directories:
|
||||
|
||||
* `/usr/local/bin`
|
||||
* `/usr/bin`
|
||||
* `/bin`
|
||||
* `/usr/sbin`
|
||||
* `/sbin`
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
```plaintext
|
||||
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32
|
||||
```
|
||||
|
||||
This means that the system should look for programs in the directories:
|
||||
|
||||
* `C:\Program Files\Python312\Scripts`
|
||||
* `C:\Program Files\Python312`
|
||||
* `C:\Windows\System32`
|
||||
|
||||
////
|
||||
|
||||
When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable.
|
||||
|
||||
For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list.
|
||||
|
||||
If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**.
|
||||
|
||||
### Installing Python and Updating the `PATH`
|
||||
|
||||
When you install Python, you might be asked if you want to update the `PATH` environment variable.
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
Let's say you install Python and it ends up in a directory `/opt/custompython/bin`.
|
||||
|
||||
If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable.
|
||||
|
||||
It could look like this:
|
||||
|
||||
```plaintext
|
||||
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin
|
||||
```
|
||||
|
||||
This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`.
|
||||
|
||||
If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable.
|
||||
|
||||
```plaintext
|
||||
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin
|
||||
```
|
||||
|
||||
This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one.
|
||||
|
||||
////
|
||||
|
||||
This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.
|
||||
|
||||
So, if you type:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
The system will **find** the `python` program in `/opt/custompython/bin` and run it.
|
||||
|
||||
It would be roughly equivalent to typing:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ /opt/custompython/bin/python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it.
|
||||
|
||||
It would be roughly equivalent to typing:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ C:\opt\custompython\bin\python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}.
|
||||
|
||||
## Conclusion
|
||||
|
||||
With this you should have a basic understanding of what **environment variables** are and how to use them in Python.
|
||||
|
||||
You can also read more about them in the <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">Wikipedia for Environment Variable</a>.
|
||||
|
||||
In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them.
|
||||
|
||||
For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md).
|
@ -78,6 +78,8 @@ As **SQLModel** is based on **Pydantic** and **SQLAlchemy**, it requires them. T
|
||||
|
||||
## Installation
|
||||
|
||||
Make sure you create a <a href="https://sqlmodel.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a>, activate it, and then install SQLModel, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
|
39
docs/install.md
Normal file
39
docs/install.md
Normal file
@ -0,0 +1,39 @@
|
||||
# Install **SQLModel**
|
||||
|
||||
Create a project directory, create a [virtual environment](virtual-environments.md){.internal-link target=_blank}, activate it, and then install **SQLModel**, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install sqlmodel
|
||||
---> 100%
|
||||
Successfully installed sqlmodel pydantic sqlalchemy
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
As **SQLModel** is built on top of <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, when you install `sqlmodel` they will also be automatically installed.
|
||||
|
||||
## Install DB Browser for SQLite
|
||||
|
||||
Remember that [SQLite is a simple database in a single file](../databases.md#a-single-file-database){.internal-link target=_blank}?
|
||||
|
||||
For most of the tutorial I'll use SQLite for the examples.
|
||||
|
||||
Python has integrated support for SQLite, it is a single file read and processed from Python. And it doesn't need an [External Database Server](../databases.md#a-server-database){.internal-link target=_blank}, so it will be perfect for learning.
|
||||
|
||||
In fact, SQLite is perfectly capable of handling quite big applications. At some point you might want to migrate to a server-based database like <a href="https://www.postgresql.org/" class="external-link" target="_blank">PostgreSQL</a> (which is also free). But for now we'll stick to SQLite.
|
||||
|
||||
Through the tutorial I will show you SQL fragments, and Python examples. And I hope (and expect 🧐) you to actually run them, and verify that the database is working as expected and showing you the same data.
|
||||
|
||||
To be able to explore the SQLite file yourself, independent of Python code (and probably at the same time), I recommend you use <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">DB Browser for SQLite</a>.
|
||||
|
||||
It's a great and simple program to interact with SQLite databases (SQLite files) in a nice user interface.
|
||||
|
||||
<img src="https://sqlitebrowser.org/images/screenshot.png">
|
||||
|
||||
Go ahead and <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">Install DB Browser for SQLite</a>, it's free.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Okay, let's get going! On the next section we'll start the [Tutorial - User Guide](tutorial/index.md). 🚀
|
@ -10,14 +10,14 @@ FastAPI is the framework to create the **web API**.
|
||||
|
||||
But we also need another type of program to run it, it is called a "**server**". We will use **Uvicorn** for that. And we will install Uvicorn with its *standard* dependencies.
|
||||
|
||||
Make sure you [have a virtual environment activated](../index.md#create-a-python-virtual-environment){.internal-link target=_blank}.
|
||||
Then install FastAPI.
|
||||
|
||||
Then install FastAPI and Uvicorn:
|
||||
Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install them, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python -m pip install fastapi "uvicorn[standard]"
|
||||
$ pip install fastapi "uvicorn[standard]"
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
@ -42,12 +42,12 @@ If you haven't done testing in FastAPI applications, first check the <a href="ht
|
||||
|
||||
Then, we can continue here, the first step is to install the dependencies, `requests` and `pytest`.
|
||||
|
||||
Make sure you do it in the same [Python environment](../index.md#create-a-python-virtual-environment){.internal-link target=_blank}.
|
||||
Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install them, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python -m pip install requests pytest
|
||||
$ pip install requests pytest
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
@ -2,8 +2,6 @@
|
||||
|
||||
In this tutorial you will learn how to use **SQLModel**.
|
||||
|
||||
But before we start playing with SQLModel, let's prepare everything else we need. A bit of type annotations, setting up the environment to install everything, and installing DB Browser for SQLite. 🤓
|
||||
|
||||
## Type hints
|
||||
|
||||
If you need a refresher about how to use Python type hints (type annotations), check <a href="https://fastapi.tiangolo.com/python-types/" class="external-link" target="_blank">FastAPI's Python types intro</a>.
|
||||
@ -33,198 +31,3 @@ Using it in your editor is what really shows you the benefits of **SQLModel**, s
|
||||
Running the examples is what will really help you understand what is going on.
|
||||
|
||||
You can learn a lot more by running some examples and playing around with them than by reading all the docs here.
|
||||
|
||||
## Create a Project
|
||||
|
||||
Please go ahead and create a directory for the project we will work on on this tutorial.
|
||||
|
||||
What I normally do is that I create a directory named `code` inside my home/user directory.
|
||||
|
||||
And inside of that I create one directory per project.
|
||||
|
||||
So, for example:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Go to the home directory
|
||||
$ cd
|
||||
// Create a directory for all your code projects
|
||||
$ mkdir code
|
||||
// Enter into that code directory
|
||||
$ cd code
|
||||
// Create a directory for this project
|
||||
$ mkdir sqlmodel-tutorial
|
||||
// Enter into that directory
|
||||
$ cd sqlmodel-tutorial
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// tip
|
||||
|
||||
Make sure you don't name it also `sqlmodel`, so that you don't end up overriding the name of the package.
|
||||
|
||||
///
|
||||
|
||||
### Make sure you have Python
|
||||
|
||||
Make sure you have an officially supported version of Python.
|
||||
|
||||
You can check which version you have with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python3 --version
|
||||
Python 3.11
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
There's a chance that you have multiple Python versions installed.
|
||||
|
||||
You might want to try with the specific versions, for example with:
|
||||
|
||||
* `python3.12`
|
||||
* `python3.11`
|
||||
* `python3.10`
|
||||
* `python3.9`
|
||||
|
||||
The code would look like this:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Let's check with just python3
|
||||
$ python3 --version
|
||||
// This is too old! 😱
|
||||
Python 3.5.6
|
||||
// Let's see if python3.10 is available
|
||||
$ python3.10 --version
|
||||
// Oh, no, this one is not available 😔
|
||||
command not found: python3.10
|
||||
$ python3.9 --version
|
||||
// Nice! This works 🎉
|
||||
Python 3.9.0
|
||||
// In this case, we would continue using python3.9 instead of python3
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If you have different versions and `python3` is not the latest, make sure you use the latest version you have available. For example `python3.9`.
|
||||
|
||||
If you don't have a valid Python version installed, go and install that first.
|
||||
|
||||
### Create a Python virtual environment
|
||||
|
||||
When writing Python code, you should **always** use virtual environments in one way or another.
|
||||
|
||||
If you don't know what that is, you can read the <a href="https://docs.python.org/3/tutorial/venv.html" class="external-link" target="_blank">official tutorial for virtual environments</a>, it's quite simple.
|
||||
|
||||
In very short, a virtual environment is a small directory that contains a copy of Python and all the libraries you need to run your code.
|
||||
|
||||
And when you "activate" it, any package that you install, for example with `pip`, will be installed in that virtual environment.
|
||||
|
||||
/// tip
|
||||
|
||||
There are other tools to manage virtual environments, like <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a>.
|
||||
|
||||
And there are alternatives that are particularly useful for deployment like <a href="https://docs.docker.com/get-started/" class="external-link" target="_blank">Docker</a> and other types of containers. In this case, the "virtual environment" is not just the Python standard files and the installed packages, but the whole system.
|
||||
|
||||
///
|
||||
|
||||
Go ahead and create a Python virtual environment for this project. And make sure to also upgrade `pip`.
|
||||
|
||||
Here are the commands you could use:
|
||||
|
||||
/// tab | Linux, macOS, Linux in Windows
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Remember that you might need to use python3.9 or similar 💡
|
||||
// Create the virtual environment using the module "venv"
|
||||
$ python3 -m venv env
|
||||
// ...here it creates the virtual environment in the directory "env"
|
||||
// Activate the virtual environment
|
||||
$ source ./env/bin/activate
|
||||
// Verify that the virtual environment is active
|
||||
# (env) $$ which python
|
||||
// The important part is that it is inside the project directory, at "code/sqlmodel-tutorial/env/bin/python"
|
||||
/home/leela/code/sqlmodel-tutorial/env/bin/python
|
||||
// Use the module "pip" to install and upgrade the package "pip" 🤯
|
||||
# (env) $$ python -m pip install --upgrade pip
|
||||
---> 100%
|
||||
Successfully installed pip
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
///
|
||||
|
||||
/// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Create the virtual environment using the module "venv"
|
||||
# >$ python3 -m venv env
|
||||
// ...here it creates the virtual environment in the directory "env"
|
||||
// Activate the virtual environment
|
||||
# >$ .\env\Scripts\Activate.ps1
|
||||
// Verify that the virtual environment is active
|
||||
# (env) >$ Get-Command python
|
||||
// The important part is that it is inside the project directory, at "code\sqlmodel-tutorial\env\python.exe"
|
||||
CommandType Name Version Source
|
||||
----------- ---- ------- ------
|
||||
Application python 0.0.0.0 C:\Users\leela\code\sqlmodel-tutorial\env\python.exe
|
||||
// Use the module "pip" to install and upgrade the package "pip" 🤯
|
||||
# (env) >$ python3 -m pip install --upgrade pip
|
||||
---> 100%
|
||||
Successfully installed pip
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
///
|
||||
|
||||
## Install **SQLModel**
|
||||
|
||||
Now, after making sure we are inside of a virtual environment in some way, we can install **SQLModel**:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
# (env) $$ pip install sqlmodel
|
||||
---> 100%
|
||||
Successfully installed sqlmodel pydantic sqlalchemy
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
As **SQLModel** is built on top of <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, when you install `sqlmodel` they will also be automatically installed.
|
||||
|
||||
## Install DB Browser for SQLite
|
||||
|
||||
Remember that [SQLite is a simple database in a single file](../databases.md#a-single-file-database){.internal-link target=_blank}?
|
||||
|
||||
For most of the tutorial I'll use SQLite for the examples.
|
||||
|
||||
Python has integrated support for SQLite, it is a single file read and processed from Python. And it doesn't need an [External Database Server](../databases.md#a-server-database){.internal-link target=_blank}, so it will be perfect for learning.
|
||||
|
||||
In fact, SQLite is perfectly capable of handling quite big applications. At some point you might want to migrate to a server-based database like <a href="https://www.postgresql.org/" class="external-link" target="_blank">PostgreSQL</a> (which is also free). But for now we'll stick to SQLite.
|
||||
|
||||
Through the tutorial I will show you SQL fragments, and Python examples. And I hope (and expect 🧐) you to actually run them, and verify that the database is working as expected and showing you the same data.
|
||||
|
||||
To be able to explore the SQLite file yourself, independent of Python code (and probably at the same time), I recommend you use <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">DB Browser for SQLite</a>.
|
||||
|
||||
It's a great and simple program to interact with SQLite databases (SQLite files) in a nice user interface.
|
||||
|
||||
<img src="https://sqlitebrowser.org/images/screenshot.png">
|
||||
|
||||
Go ahead and <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">Install DB Browser for SQLite</a>, it's free.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Okay, let's get going! On the [next section](create-db-and-table-with-db-browser.md) we'll start creating a database. 🚀
|
||||
|
844
docs/virtual-environments.md
Normal file
844
docs/virtual-environments.md
Normal file
@ -0,0 +1,844 @@
|
||||
# Virtual Environments
|
||||
|
||||
When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project.
|
||||
|
||||
/// info
|
||||
|
||||
If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
A **virtual environment** is different than an **environment variable**.
|
||||
|
||||
An **environment variable** is a variable in the system that can be used by programs.
|
||||
|
||||
A **virtual environment** is a directory with some files in it.
|
||||
|
||||
///
|
||||
|
||||
/// info
|
||||
|
||||
This page will teach you how to use **virtual environments** and how they work.
|
||||
|
||||
If you are ready to adopt a **tool that manages everything** for you (including installing Python), try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>.
|
||||
|
||||
///
|
||||
|
||||
## Create a Project
|
||||
|
||||
First, create a directory for your project.
|
||||
|
||||
What I normally do is that I create a directory named `code` inside my home/user directory.
|
||||
|
||||
And inside of that I create one directory per project.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Go to the home directory
|
||||
$ cd
|
||||
// Create a directory for all your code projects
|
||||
$ mkdir code
|
||||
// Enter into that code directory
|
||||
$ cd code
|
||||
// Create a directory for this project
|
||||
$ mkdir awesome-project
|
||||
// Enter into that project directory
|
||||
$ cd awesome-project
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Create a Virtual Environment
|
||||
|
||||
When you start working on a Python project **for the first time**, create a virtual environment **<abbr title="there are other options, this is a simple guideline">inside your project</abbr>**.
|
||||
|
||||
/// tip
|
||||
|
||||
You only need to do this **once per project**, not every time you work.
|
||||
|
||||
///
|
||||
|
||||
//// tab | `venv`
|
||||
|
||||
To create a virtual environment, you can use the `venv` module that comes with Python.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python -m venv .venv
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// details | What that command means
|
||||
|
||||
* `python`: use the program called `python`
|
||||
* `-m`: call a module as a script, we'll tell it which module next
|
||||
* `venv`: use the module called `venv` that normally comes installed with Python
|
||||
* `.venv`: create the virtual environment in the new directory `.venv`
|
||||
|
||||
///
|
||||
|
||||
////
|
||||
|
||||
//// tab | `uv`
|
||||
|
||||
If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> installed, you can use it to create a virtual environment.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uv venv
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// tip
|
||||
|
||||
By default, `uv` will create a virtual environment in a directory called `.venv`.
|
||||
|
||||
But you could customize it passing an additional argument with the directory name.
|
||||
|
||||
///
|
||||
|
||||
////
|
||||
|
||||
That command creates a new virtual environment in a directory called `.venv`.
|
||||
|
||||
/// details | `.venv` or other name
|
||||
|
||||
You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`.
|
||||
|
||||
///
|
||||
|
||||
## Activate the Virtual Environment
|
||||
|
||||
Activate the new virtual environment so that any Python command you run or package you install uses it.
|
||||
|
||||
/// tip
|
||||
|
||||
Do this **every time** you start a **new terminal session** to work on the project.
|
||||
|
||||
///
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ source .venv/bin/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ .venv\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 .venv/Scripts/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
/// tip
|
||||
|
||||
Every time you install a **new package** in that environment, **activate** the environment again.
|
||||
|
||||
This makes sure that if you use a **terminal (<abbr title="command line interface">CLI</abbr>) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need.
|
||||
|
||||
///
|
||||
|
||||
## Check the Virtual Environment is Active
|
||||
|
||||
Check that the virtual environment is active (the previous command worked).
|
||||
|
||||
/// tip
|
||||
|
||||
This is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended.
|
||||
|
||||
///
|
||||
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ which python
|
||||
|
||||
/home/user/code/awesome-project/.venv/bin/python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ Get-Command python
|
||||
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉
|
||||
|
||||
////
|
||||
|
||||
## Upgrade `pip`
|
||||
|
||||
/// tip
|
||||
|
||||
If you use <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎
|
||||
|
||||
///
|
||||
|
||||
If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version.
|
||||
|
||||
Many exotic errors while installing a package are solved by just upgrading `pip` first.
|
||||
|
||||
/// tip
|
||||
|
||||
You would normally do this **once**, right after you create the virtual environment.
|
||||
|
||||
///
|
||||
|
||||
Make sure the virtual environment is active (with the command above) and then run:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python -m pip install --upgrade pip
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Add `.gitignore`
|
||||
|
||||
If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git.
|
||||
|
||||
/// tip
|
||||
|
||||
If you used <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> to create the virtual environment, it already did this for you, you can skip this step. 😎
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
Do this **once**, right after you create the virtual environment.
|
||||
|
||||
///
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ echo "*" > .venv/.gitignore
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// details | What that command means
|
||||
|
||||
* `echo "*"`: will "print" the text `*` in the terminal (the next part changes that a bit)
|
||||
* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>`
|
||||
* `.gitignore`: the name of the file where the text should be written
|
||||
|
||||
And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory.
|
||||
|
||||
That command will create a file `.gitignore` with the content:
|
||||
|
||||
```gitignore
|
||||
*
|
||||
```
|
||||
|
||||
///
|
||||
|
||||
## Install Packages
|
||||
|
||||
After activating the environment, you can install packages in it.
|
||||
|
||||
/// tip
|
||||
|
||||
Do this **once** when installing or upgrading the packages your project needs.
|
||||
|
||||
If you need to upgrade a version or add a new package you would **do this again**.
|
||||
|
||||
///
|
||||
|
||||
### Install Packages Directly
|
||||
|
||||
If you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly.
|
||||
|
||||
/// tip
|
||||
|
||||
It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`).
|
||||
|
||||
///
|
||||
|
||||
//// tab | `pip`
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install sqlmodel
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | `uv`
|
||||
|
||||
If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uv pip install sqlmodel
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
### Install from `requirements.txt`
|
||||
|
||||
If you have a `requirements.txt`, you can now use it to install its packages.
|
||||
|
||||
//// tab | `pip`
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install -r requirements.txt
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | `uv`
|
||||
|
||||
If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uv pip install -r requirements.txt
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
/// details | `requirements.txt`
|
||||
|
||||
A `requirements.txt` with some packages could look like:
|
||||
|
||||
```requirements.txt
|
||||
sqlmodel==0.13.0
|
||||
rich==13.7.1
|
||||
```
|
||||
|
||||
///
|
||||
|
||||
## Run Your Program
|
||||
|
||||
After you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python main.py
|
||||
|
||||
Hello World
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Configure Your Editor
|
||||
|
||||
You would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors.
|
||||
|
||||
For example:
|
||||
|
||||
* <a href="https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment" class="external-link" target="_blank">VS Code</a>
|
||||
* <a href="https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html" class="external-link" target="_blank">PyCharm</a>
|
||||
|
||||
/// tip
|
||||
|
||||
You normally have to do this only **once**, when you create the virtual environment.
|
||||
|
||||
///
|
||||
|
||||
## Deactivate the Virtual Environment
|
||||
|
||||
Once you are done working on your project you can **deactivate** the virtual environment.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ deactivate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there.
|
||||
|
||||
## Ready to Work
|
||||
|
||||
Now you're ready to start working on your project.
|
||||
|
||||
|
||||
|
||||
/// tip
|
||||
|
||||
Do you want to understand what's all that above?
|
||||
|
||||
Continue reading. 👇🤓
|
||||
|
||||
///
|
||||
|
||||
## Why Virtual Environments
|
||||
|
||||
To work with SQLModel you need to install <a href="https://www.python.org/" class="external-link" target="_blank">Python</a>.
|
||||
|
||||
After that, you would need to **install** SQLModel and any other **packages** you want to use.
|
||||
|
||||
To install packages you would normally use the `pip` command that comes with Python (or similar alternatives).
|
||||
|
||||
Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python).
|
||||
|
||||
### The Problem
|
||||
|
||||
So, what's the problem with installing packages in the global Python environment?
|
||||
|
||||
At some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱
|
||||
|
||||
For example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
stone(philosophers-stone) -->|requires| harry-1[harry v1]
|
||||
```
|
||||
|
||||
Then, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]
|
||||
```
|
||||
|
||||
But now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install.
|
||||
|
||||
If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "harry==1"
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
And then you would end up with `harry` version `1` installed in your global Python environment.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph global[global env]
|
||||
harry-1[harry v1]
|
||||
end
|
||||
subgraph stone-project[philosophers-stone project]
|
||||
stone(philosophers-stone) -->|requires| harry-1
|
||||
end
|
||||
```
|
||||
|
||||
But then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`).
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "harry==3"
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
And then you would end up with `harry` version `3` installed in your global Python environment.
|
||||
|
||||
And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph global[global env]
|
||||
harry-1[<strike>harry v1</strike>]
|
||||
style harry-1 fill:#ccc,stroke-dasharray: 5 5
|
||||
harry-3[harry v3]
|
||||
end
|
||||
subgraph stone-project[philosophers-stone project]
|
||||
stone(philosophers-stone) -.-x|⛔️| harry-1
|
||||
end
|
||||
subgraph azkaban-project[prisoner-of-azkaban project]
|
||||
azkaban(prisoner-of-azkaban) --> |requires| harry-3
|
||||
end
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
It's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly.
|
||||
|
||||
///
|
||||
|
||||
Now, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working.
|
||||
|
||||
Also, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system.
|
||||
|
||||
## Where are Packages Installed
|
||||
|
||||
When you install Python, it creates some directories with some files in your computer.
|
||||
|
||||
Some of these directories are the ones in charge of having all the packages you install.
|
||||
|
||||
When you run:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Don't run this now, it's just an example 🤓
|
||||
$ pip install sqlmodel
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
That will download a compressed file with the SQLModel code, normally from <a href="https://pypi.org/project/sqlmodel/" class="external-link" target="_blank">PyPI</a>.
|
||||
|
||||
It will also **download** files for other packages that SQLModel depends on.
|
||||
|
||||
Then it will **extract** all those files and put them in a directory in your computer.
|
||||
|
||||
By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**.
|
||||
|
||||
## What are Virtual Environments
|
||||
|
||||
The solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on.
|
||||
|
||||
A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project.
|
||||
|
||||
This way, each project will have it's own virtual environment (`.venv` directory) with its own packages.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph stone-project[philosophers-stone project]
|
||||
stone(philosophers-stone) --->|requires| harry-1
|
||||
subgraph venv1[.venv]
|
||||
harry-1[harry v1]
|
||||
end
|
||||
end
|
||||
subgraph azkaban-project[prisoner-of-azkaban project]
|
||||
azkaban(prisoner-of-azkaban) --->|requires| harry-3
|
||||
subgraph venv2[.venv]
|
||||
harry-3[harry v3]
|
||||
end
|
||||
end
|
||||
stone-project ~~~ azkaban-project
|
||||
```
|
||||
|
||||
## What Does Activating a Virtual Environment Mean
|
||||
|
||||
When you activate a virtual environment, for example with:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ source .venv/bin/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ .venv\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 .venv/Scripts/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
That command will create or modify some [environment variables](environment-variables.md){.internal-link target=_blank} that will be available for the next commands.
|
||||
|
||||
One of those variables is the `PATH` variable.
|
||||
|
||||
/// tip
|
||||
|
||||
You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable){.internal-link target=_blank} section.
|
||||
|
||||
///
|
||||
|
||||
Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable.
|
||||
|
||||
Let's say that before activating the environment, the `PATH` variable looked like this:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
```plaintext
|
||||
/usr/bin:/bin:/usr/sbin:/sbin
|
||||
```
|
||||
|
||||
That means that the system would look for programs in:
|
||||
|
||||
* `/usr/bin`
|
||||
* `/bin`
|
||||
* `/usr/sbin`
|
||||
* `/sbin`
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
```plaintext
|
||||
C:\Windows\System32
|
||||
```
|
||||
|
||||
That means that the system would look for programs in:
|
||||
|
||||
* `C:\Windows\System32`
|
||||
|
||||
////
|
||||
|
||||
After activating the virtual environment, the `PATH` variable would look something like this:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
```plaintext
|
||||
/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin
|
||||
```
|
||||
|
||||
That means that the system will now start looking first look for programs in:
|
||||
|
||||
```plaintext
|
||||
/home/user/code/awesome-project/.venv/bin
|
||||
```
|
||||
|
||||
before looking in the other directories.
|
||||
|
||||
So, when you type `python` in the terminal, the system will find the Python program in
|
||||
|
||||
```plaintext
|
||||
/home/user/code/awesome-project/.venv/bin/python
|
||||
```
|
||||
|
||||
and use that one.
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
```plaintext
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32
|
||||
```
|
||||
|
||||
That means that the system will now start looking first look for programs in:
|
||||
|
||||
```plaintext
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts
|
||||
```
|
||||
|
||||
before looking in the other directories.
|
||||
|
||||
So, when you type `python` in the terminal, the system will find the Python program in
|
||||
|
||||
```plaintext
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
```
|
||||
|
||||
and use that one.
|
||||
|
||||
////
|
||||
|
||||
An important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment).
|
||||
|
||||
Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does.
|
||||
|
||||
## Checking a Virtual Environment
|
||||
|
||||
When you check if a virtual environment is active, for example with:
|
||||
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ which python
|
||||
|
||||
/home/user/code/awesome-project/.venv/bin/python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ Get-Command python
|
||||
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
That means that the `python` program that will be used is the one **in the virtual environment**.
|
||||
|
||||
you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell.
|
||||
|
||||
The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program.
|
||||
|
||||
The most important part is that when you call `python`, that is the exact "`python`" that will be executed.
|
||||
|
||||
So, you can confirm if you are in the correct virtual environment.
|
||||
|
||||
/// tip
|
||||
|
||||
It's easy to activate one virtual environment, get one Python, and then **go to another project**.
|
||||
|
||||
And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project.
|
||||
|
||||
It's useful being able to check what `python` is being used. 🤓
|
||||
|
||||
///
|
||||
|
||||
## Why Deactivate a Virtual Environment
|
||||
|
||||
For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment.
|
||||
|
||||
And then you want to work on **another project** `prisoner-of-azkaban`.
|
||||
|
||||
You go to that project:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ cd ~/code/prisoner-of-azkaban
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ cd ~/code/prisoner-of-azkaban
|
||||
|
||||
$ python main.py
|
||||
|
||||
// Error importing sirius, it's not installed 😱
|
||||
Traceback (most recent call last):
|
||||
File "main.py", line 1, in <module>
|
||||
import sirius
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
But if you deactivate the virtual environment and activate the new one for `prisoner-of-askaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ cd ~/code/prisoner-of-azkaban
|
||||
|
||||
// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎
|
||||
$ deactivate
|
||||
|
||||
// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀
|
||||
$ source .venv/bin/activate
|
||||
|
||||
// Now when you run python, it will find the package sirius installed in this virtual environment ✨
|
||||
$ python main.py
|
||||
|
||||
I solemnly swear 🐺
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Alternatives
|
||||
|
||||
This is a simple guide to get you started and teach you how everything works **underneath**.
|
||||
|
||||
There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects.
|
||||
|
||||
Once you are ready and want to use a tool to **manage the entire project**, packages dependencies, virtual environments, etc. I would suggest you try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>.
|
||||
|
||||
`uv` can do a lot of things, it can:
|
||||
|
||||
* **Install Python** for you, including different versions
|
||||
* Manage the **virtual environment** for your projects
|
||||
* Install **packages**
|
||||
* Manage package **dependencies and versions** for your project
|
||||
* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking**
|
||||
* And many other things
|
||||
|
||||
## Conclusion
|
||||
|
||||
If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓
|
||||
|
||||
Knowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎
|
@ -71,6 +71,9 @@ nav:
|
||||
- learn/index.md
|
||||
- databases.md
|
||||
- db-to-code.md
|
||||
- environment-variables.md
|
||||
- virtual-environments.md
|
||||
- install.md
|
||||
- Tutorial - User Guide:
|
||||
- tutorial/index.md
|
||||
- tutorial/create-db-and-table-with-db-browser.md
|
||||
|
Loading…
x
Reference in New Issue
Block a user