Skip to content

pxuanbach/fastapi-essential-modules

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Fastapi Essential Modules

Essential modules for developing applications with FastAPI. This project uses Python 3.10 as the environment and Poetry as the package manager.

ko-fi

Table of Contents

  1. Quickstart
  2. Migration
  3. Logging
  4. Caching

Quickstart

  1. Open Terminal in this directory.

  2. Initialize the virtual environment by command:

    python -m venv venv  # py -m venv venv
  3. Use virtual environment by the activation command:

    venv\Scripts\activate # For Mac user: source bin/activate
  4. Install Poetry and update required packages:

    pip install poetry
    
    poetry update
  5. Run the application

    uvicorn app.main:app --reload

Migration

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

Logging

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'

Caching

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'