Essential modules for developing applications with FastAPI. This project uses Python 3.10 as the environment and Poetry as the package manager.
-
Open Terminal in this directory.
-
Initialize the virtual environment by command:
python -m venv venv # py -m venv venv
-
Use virtual environment by the activation command:
venv\Scripts\activate # For Mac user: source bin/activate
-
Install Poetry and update required packages:
pip install poetry poetry update
-
Run the application
uvicorn app.main:app --reload
To add or initialize a module, you can use the following commands:
poetry add alembic # pip install alembic
alembic init migrations
To create a new revision:
alembic revision --autogenerate -m "message"
To migrate:
alembic upgrade head
To undo the latest migration:
alembic downgrade -1
To roll back to a specific revision:
alembic downgrade <<revision_id>>
Everything is wrapped up in a function (app/core/logger.py
) and it's just a matter of calling the function when initializing the application.
from app.core.logger import setup as setup_logging
@asynccontextmanager
async def lifespan(app: FastAPI):
# start up
setup_logging()
yield
# shut down
pass
app = FastAPI(
title=settings.PROJECT_NAME,
lifespan=lifespan
)
See the example in app/api/utils.py
.
Test with curl.
curl --request POST \
--url 'http://localhost:8000/api/v1/utils/logs?text=This%20is%20log'
Install the Redis package.
poetry add redis # pip install redis
Adapter for Redis: app\core\redis.py
. To manage connections and disconnections to Redis
from app.core.redis import redis_client
@asynccontextmanager
async def lifespan(app: FastAPI):
# start up
await redis_client.connect(str(settings.REDIS_URL))
yield
# shut down
await redis_client.disconnect()
app = FastAPI(
title=settings.PROJECT_NAME,
lifespan=lifespan
)
Caching module: app\core\cache.py
See the example in app\api\user.py
Test with curl.
# Insert 20000 users
curl --request POST \
--url http://localhost:8000/api/v1/users/bulk/20000
# Get 20000 users
curl --request GET \
--url 'http://localhost:8000/api/v1/users?limit=20000&skip=0'