- Published on
Python Virtual Environment Simple Project Setup
Prerequisites and requirements
- Have
python 3
(recommended to use version 3.6 and above) installed in your machine. Make sure it is executable and confirm it by entering the shell or executing a python script file. - Make sure the
pip
is also installed and the commands are available. It should be included when python is installed. - Some fresh Linux installation will require installing the virtualenv tool using
sudo apt install python3-venv
.
About the demo
We are going to create a simple rest api project using FastAPI framework by utilizing the virtualenv.
Initialize virtualenv in a project directory
Let’s create a directory/folder anywhere on your machine named simple_restapi
for our root project directory. Open your command prompt or terminal, go inside the directory and execute this python command:
python -m venv .venv
it will create a .venv
folder inside the simple_restapi
directory.
Activating the virtualenv
For Windows users, you can execute this from the simple_restapi
directory:
.venv\Scripts\activate
For Unix/Linux users:
source ./.venv/bin/activate
Once the virtualenv is activated, it will create a virtual session indicating the python environment is changed and it is isolated from your machine’s python environment.
Installing dependencies
Make sure you are inside the virtualenv session because we are going to install packages for our project only. Here are the dependencies needed for our fastapi project and execute them:
pip install fastapi
pip install "uvicorn[standard]"
Check if those packages are listed using pip list
command.
Simple REST API example
We could use the example script from the fastapi documentation, and create a file named main.py
in the project root directory and fill it with this script:
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
Starting the server
Still inside the virtualenv session and the root project folder, we could run the project using uvicorn:
uvicorn main:app --reload
You could test the API by accessing it in your browser (GET endpoints only) by accessing http://localhost:8000/ or using API platforms like Postman or cURL.
You can stop the server later by executing Ctrl + C
Exporting the environment
Exporting the list of packages used in the environment is essential for deploying it later in another machine. You can use pip
command and redirection operator >
combination:
pip freeze > requirements.txt
Importing the environment
Later when you set up the project on another machine, you can use the created requirements.txt
to install dependencies:
pip install -r requirements.txt
Deactivating the virtualenv
To exit the virtualenv, you can use this command:
deactivate .venv