Table of Contents
- About The Project
-
Getting Started
- Make will help you
- How to feed database
- Structured & Asynchronous Logging with Rotoger
- Setup user auth
- Setup local development with uv
- Import xlsx files with polars and calamine
- Schedule jobs
- Email Configuration
- UV knowledge and inspirations
- Integration with local LLM
- High Availability sample with nginx as load balancer
- Acknowledgments
This example demonstrates the seamless integration of FastAPI, a modern, high-performance web framework, with Pydantic 2.0, a robust and powerful data validation library. The integration is further enhanced by the use of SQLAlchemy ORM, a popular and feature-rich Object-Relational Mapping tool, and PostgreSQL17 relational database.
The entire stack is connected using the asyncpg Database Client Library, which provides a robust and efficient way to interact with PostgreSQL databases in Python, leveraging the power of asyncio and event loops.
Notably, this example showcases the latest and greatest versions of SQLAlchemy and psycopg, which are renowned for their robustness, power, and speed. The inclusion of FastAPI adds a modern, fast, and high-performance web framework to the mix allowing for the rapid development of APIs with Python 3.13.
FastAPI has received significant recognition in the industry, including a review on thoughtworks Technology Radar in April 2021, where it was classified as a Trial technology, with comments praising its performance, ease of use, and features such as API documentation using OpenAPI. Additionally, FastAPI was recognized in the Python Developers Survey 2023 Results, conducted by the Python Software Foundation and JetBrains, where it was reported that 1 in 4 Python developers use FastAPI, with a 4 percentage point increase from the previous year.
To build , run and test and more ... use magic of make help to play with this project.
1. make docker-build
2. make docker-up > alternatively > make docker-up-granian
3. make docker-apply-db-migrations
4. make docker-feed-databaseIt took me a while to find nice data set. Hope works of Shakespeare as example will be able to cover first part with read only declarative base configuration and all type of funny selects :) Data set is coming form https://github.com/catherinedevlin/opensourceshakespeare Next models were generated with https://github.com/agronholm/sqlacodegen
To elevate the logging capabilities beyond simple colored output, this project has transitioned to Rotoger. This powerful library provides a comprehensive, production-ready logging setup for modern asynchronous applications, addressing challenges like log management, performance, and readability.
Rotoger is built upon the excellent structlog library and brings several key advantages:
Structured Logging: By using structlog, all log entries are generated as structured data (JSON), making them machine-readable and significantly easier to query, parse, and analyze in log management systems.Asynchronous & Non-Blocking: Designed for async frameworks like FastAPI, Rotoger performs logging operations in a non-blocking manner. This ensures that I/O-bound logging tasks do not hold up the event loop, maintaining high application performance.High-Performance JSON: It leverages orjson for serialization, which is one of the fastest JSON libraries for Python. This minimizes the overhead of converting log records to JSON strings.Built-in Log Rotation: Rotoger implements its own log rotation mechanism in Python, allowing you to manage log file sizes and retention policies directly within your application without relying on external tools like logrotate.
This setup solves common logging pain points in production environments, such as managing large log files, ensuring logs don't impact performance, and making logs easily searchable.
Setup user authentication with JWT and Redis as token storage.
uv sync
source .venv/bin/activatePower of Polars Library in data manipulation and analysis.
It uses the polars library to read the Excel data into a DataFrame by passing the bytes to the pl.read_excel() function -
https://docs.pola.rs/py-polars/html/reference/api/polars.read_excel.html
In pl.read_excel() βcalamineβ engine can be used for reading all major types of Excel Workbook (.xlsx, .xlsb, .xls) and is dramatically faster than the other options, using the fastexcel module to bind calamine.
The project uses the APScheduler library to schedule tasks in the background. The APScheduler library is a powerful and flexible in-process task scheduler with Cron-like capabilities. It allows you to schedule jobs to run at specific times or intervals, and it supports multiple job stores, triggers, and executors. The library is designed to be easy to use and highly configurable, making it suitable for a wide range of use cases. It was added to project in version 4.0.0a5 with Redis as event broker and SQLAlchemy as data store.
The project uses the smtplib library to send emails.
The smtplib library is a built-in Python library that provides a simple interface for sending emails using the Simple Mail Transfer Protocol (SMTP).
It allows you to connect to an SMTP server, send an email message, and disconnect from the server.
The library is easy to use and provides a flexible and powerful way to send emails from your Python applications.
SMTPEmailService provides a reusable interface to send emails via an SMTP server. This service supports plaintext and HTML emails, and also allows sending template-based emails using the Jinja2 template engine. It is implemented as a singleton to ensure that only one SMTP connection is maintained throughout the application lifecycle, optimizing resource usage.
The /v1/ml/chat/ endpoint is designed to handle chat-based interactions with the LLM model.
It accepts a user prompt and streams responses back in real-time.
The endpoint leverages FastAPI's asynchronous capabilities to efficiently manage multiple simultaneous requests,
ensuring low latency and high throughput.
FastAPI's async support is particularly beneficial for reducing I/O bottlenecks when connecting to the LLM model.
By using asynchronous HTTP clients like httpx,
the application can handle multiple I/O-bound tasks concurrently,
such as sending requests to the LLM server and streaming responses back to the client.
This approach minimizes idle time and optimizes resource utilization, making it ideal for high-performance applications.
Install ollama and run the server
ollama run llama3.2Sample high availability setup with nginx as load balancer and 2 uvicorn instances running on different ports.
make docker-up-ha- https://docs.astral.sh/uv/
- https://hynek.me/articles/docker-uv/
- https://thedataquarry.com/posts/towards-a-unified-python-toolchain/
- https://www.youtube.com/watch?v=ifj-izwXKRA&t=760s > UV and Ruff: Next-gen Python Tooling
- https://www.youtube.com/watch?v=8UuW8o4bHbw&t=1s > uv IS the Future of Python Packaging! ππ¦
Use this space to list resources you find helpful and would like to give credit to. I've included a few of my favorites to kick things off!
- Open Source Shakespeare Dataset
- SQL Code Generator
- Passlib - password hashing library for Python
- Polars - fast DataFrame library for Rust and Python
- Rich - Traceback and logging, made easy
- Calamine - Excel reader in Rust
- Inline Snapshots - pytest plugin for inline snapshots
- Connection pool for asyncpg
- Granian - A Rust HTTP server for Python applications
- APScheduler - In-process task scheduler with Cron-like capabilities
- Valkey - A simple and fast key-value store
2025 (3 changes)
- [SEP 2 2025] add sample high availability with nginx as load balancer
- [AUG 23 2025] intro exception handlers
- [JUL some sunny day 2025] add rotoger
- [MAY 3, 2025] add large language model integration π€
- [MAR 8 2025] switch from poetry to uv β©
- [JAN 28 2025] add SMTP setup π§
2024 (6 changes)
- [DEC 16 2024] bump project to Python 3.13 β©
- [OCT 16 2024] apscheduler added to project π
- [AUG 17 2024] granian use case implemented with docker compose and rich logger β©
- [JUN 8 2024] implement asyncpg connection pool β©
- [MAR 15, 2024] add polars and calamine to project π»
- [FEB 1 2024] bump project to Python 3.12 β©
2023 (7 changes)
- [OCT 21 2023] refactor shakespeare models to use sqlalchemy 2.0 β©
- [SEP 2 2023] add passlib and bcrypt for password hashing π π
- [JUL 25 2023] add user authentication with JWT and Redis as token storage π π
- [JUL 7 2023] migrate to pydantic 2.0 β©
- [APR 28 2023] Rainbow logs with rich π
- [APR 10 2023] implement logging with rich
- [FEB 14 2023] bump project to Python 3.11
2022 (5 changes)
- [NOV 12 2022] ruff implemented to project as linting tool
- [OCT 3 2022] poetry added to project
- [JUN 6 2022] initial dataset for shakespeare models
- [JUN 4 2022] alembic migrations added to project
- [long time ago...] it was a long time ago in galaxy far far away...
